1 // Vorbis decoder written in Rust 2 // 3 // Copyright (c) 2019 est31 <MTest31@outlook.com> 4 // and contributors. All rights reserved. 5 // Licensed under MIT license, or Apache 2 license, 6 // at your option. Please see the LICENSE file 7 // attached to this source distribution for details. 8 9 /*! 10 Traits for sample formats 11 */ 12 13 /// Trait for a packet of multiple samples 14 pub trait Samples { num_samples(&self) -> usize15 fn num_samples(&self) -> usize; truncate(&mut self, limit :usize)16 fn truncate(&mut self, limit :usize); from_floats(floats :Vec<Vec<f32>>) -> Self17 fn from_floats(floats :Vec<Vec<f32>>) -> Self; 18 } 19 20 impl<S :Sample> Samples for Vec<Vec<S>> { num_samples(&self) -> usize21 fn num_samples(&self) -> usize { 22 self[0].len() 23 } truncate(&mut self, limit :usize)24 fn truncate(&mut self, limit :usize) { 25 for ch in self.iter_mut() { 26 if limit < ch.len() { 27 ch.truncate(limit); 28 } 29 } 30 } 31 from_floats(floats :Vec<Vec<f32>>) -> Self32 fn from_floats(floats :Vec<Vec<f32>>) -> Self { 33 floats.into_iter() 34 .map(|samples| { 35 samples.into_iter() 36 .map(S::from_float) 37 .collect() 38 }).collect() 39 } 40 } 41 42 /// A packet of multi-channel interleaved samples 43 pub struct InterleavedSamples<S :Sample> { 44 pub samples :Vec<S>, 45 pub channel_count :usize, 46 } 47 48 impl<S :Sample> Samples for InterleavedSamples<S> { num_samples(&self) -> usize49 fn num_samples(&self) -> usize { 50 self.samples.len() / self.channel_count 51 } truncate(&mut self, limit :usize)52 fn truncate(&mut self, limit :usize) { 53 self.samples.truncate(limit * self.channel_count); 54 } from_floats(floats :Vec<Vec<f32>>) -> Self55 fn from_floats(floats :Vec<Vec<f32>>) -> Self { 56 let channel_count = floats.len(); 57 // Note that a channel count of 0 is forbidden 58 // by the spec and the header decoding code already 59 // checks for that. 60 assert!(floats.len() > 0); 61 let samples_interleaved = if channel_count == 1 { 62 // Because decoded_pck[0] doesn't work... 63 <Vec<Vec<S>> as Samples>::from_floats(floats).into_iter().next().unwrap() 64 } else { 65 let len = floats[0].len(); 66 let mut samples = Vec::with_capacity(len * channel_count); 67 for i in 0 .. len { 68 for ref chan in floats.iter() { 69 samples.push(S::from_float(chan[i])); 70 } 71 } 72 samples 73 }; 74 Self { 75 samples : samples_interleaved, 76 channel_count, 77 } 78 } 79 } 80 81 /// Trait representing a single sample 82 pub trait Sample { from_float(fl :f32) -> Self83 fn from_float(fl :f32) -> Self; 84 } 85 86 impl Sample for f32 { from_float(fl :f32) -> Self87 fn from_float(fl :f32) -> Self { 88 fl 89 } 90 } 91 92 impl Sample for i16 { from_float(fl :f32) -> Self93 fn from_float(fl :f32) -> Self { 94 let fl = fl * 32768.0; 95 if fl > 32767. { 96 32767 97 } else if fl < -32768. { 98 -32768 99 } else { 100 fl as i16 101 } 102 } 103 } 104