flac/
stream.rs

1use metadata;
2use frame;
3use subframe;
4
5use metadata::{Metadata, StreamInfo};
6use frame::frame_parser;
7use utility::{
8  ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
9  many_metadata,
10};
11
12use std::io;
13use std::usize;
14use std::fs::File;
15
16/// FLAC stream that decodes and hold file information.
17pub struct Stream<P: StreamProducer> {
18  info: StreamInfo,
19  metadata: Vec<Metadata>,
20  producer: P,
21}
22
23/// Alias for a FLAC stream produced from `Read`.
24pub type StreamReader<R>  = Stream<ReadStream<R>>;
25
26/// Alias for a FLAC stream produced from a byte stream buffer.
27pub type StreamBuffer<'a> = Stream<ByteStream<'a>>;
28
29impl<P> Stream<P> where P: StreamProducer {
30  /// Constructor for the default state of a FLAC stream.
31  #[inline]
32  pub fn new<R: io::Read>(reader: R) -> Result<StreamReader<R>, ErrorKind> {
33    let producer = ReadStream::new(reader);
34
35    Stream::from_stream_producer(producer)
36  }
37
38  /// Returns information for the current stream.
39  #[inline]
40  pub fn info(&self) -> StreamInfo {
41    self.info
42  }
43
44  /// Returns a slice of `Metadata`
45  ///
46  /// This slice excludes `StreamInfo`, which is located in `Stream::info`.
47  /// Everything else is related to metadata for the FLAC stream is in the
48  /// slice.
49  #[inline]
50  pub fn metadata(&self) -> &[Metadata] {
51    &self.metadata
52  }
53
54  /// Constructs a decoder with the given file name.
55  ///
56  /// # Failures
57  ///
58  /// * `ErrorKind::IO(io::ErrorKind::NotFound)` is returned when the given
59  ///   filename isn't found.
60  /// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
61  ///   within the file isn't valid FLAC data.
62  /// * Several different parser specific errors that are structured as
63  ///   `ErrorKind::<parser_name>Parser`.
64  /// * Several different invalidation specific errors that are
65  ///   structured as `ErrorKind::Invalid<invalidation_name>`.
66  #[inline]
67  pub fn from_file(filename: &str) -> Result<StreamReader<File>, ErrorKind> {
68    File::open(filename).map_err(|e| ErrorKind::IO(e.kind()))
69                        .and_then(|file| {
70      let producer = ReadStream::new(file);
71
72      Stream::from_stream_producer(producer)
73    })
74  }
75
76  /// Constructs a decoder with the given buffer.
77  ///
78  /// This constructor assumes that an entire FLAC file is in the buffer.
79  ///
80  /// # Failures
81  ///
82  /// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
83  ///   within the file isn't valid FLAC data.
84  /// * Several different parser specific errors that are structured as
85  ///   `ErrorKind::<parser_name>Parser`.
86  /// * Several different invalidation specific errors that are
87  ///   structured as `ErrorKind::Invalid<invalidation_name>`.
88  #[inline]
89  pub fn from_buffer(buffer: &[u8]) -> Result<StreamBuffer, ErrorKind> {
90    let producer = ByteStream::new(buffer);
91
92    Stream::from_stream_producer(producer)
93  }
94
95  fn from_stream_producer(mut producer: P) -> Result<Self, ErrorKind> {
96    let mut stream_info = Default::default();
97    let mut metadata    = Vec::new();
98
99    many_metadata(&mut producer, |block| {
100      if let metadata::Data::StreamInfo(info) = block.data {
101        stream_info = info;
102      } else {
103        metadata.push(block);
104      }
105    }).map(|_| {
106      Stream {
107        info: stream_info,
108        metadata: metadata,
109        producer: producer,
110      }
111    })
112  }
113
114  /// Returns an iterator over the decoded samples.
115  #[inline]
116  pub fn iter<S: SampleSize>(&mut self) -> Iter<P, S::Extended> {
117    let samples_left = self.info.total_samples;
118    let channels     = self.info.channels as usize;
119    let block_size   = self.info.max_block_size as usize;
120    let buffer_size  = block_size * channels;
121
122    Iter {
123      stream: self,
124      channel: 0,
125      block_size: 0,
126      sample_index: 0,
127      samples_left: samples_left,
128      buffer: vec![S::Extended::from_i8(0); buffer_size]
129    }
130  }
131
132  fn next_frame<S>(&mut self, buffer: &mut [S]) -> Option<usize>
133   where S: Sample {
134    let stream_info = &self.info;
135
136    loop {
137      match self.producer.parse(|i| frame_parser(i, stream_info, buffer)) {
138        Ok(frame)                => {
139          let channels   = frame.header.channels as usize;
140          let block_size = frame.header.block_size as usize;
141          let subframes  = frame.subframes[0..channels].iter();
142
143          for (channel, subframe) in subframes.enumerate() {
144            let start  = channel * block_size;
145            let end    = (channel + 1) * block_size;
146            let output = &mut buffer[start..end];
147
148            subframe::decode(&subframe, block_size, output);
149          }
150
151          frame::decode(frame.header.channel_assignment, buffer);
152
153          return Some(block_size);
154        }
155        Err(ErrorKind::Continue) => continue,
156        Err(_)                   => return None,
157      }
158    }
159  }
160}
161
162/// An iterator over a reference of the decoded FLAC stream.
163pub struct Iter<'a, P, S>
164 where P: 'a + StreamProducer,
165       S: Sample{
166  stream: &'a mut Stream<P>,
167  channel: usize,
168  block_size: usize,
169  sample_index: usize,
170  samples_left: u64,
171  buffer: Vec<S>,
172}
173
174impl<'a, P, S> Iterator for Iter<'a, P, S>
175 where P: StreamProducer,
176       S: Sample {
177  type Item = S::Normal;
178
179  fn next(&mut self) -> Option<Self::Item> {
180    if self.sample_index == self.block_size {
181      let buffer = &mut self.buffer;
182
183      if let Some(block_size) = self.stream.next_frame(buffer) {
184        self.sample_index = 0;
185        self.block_size   = block_size;
186      } else {
187        return None;
188      }
189    }
190
191    let channels = self.stream.info.channels as usize;
192    let index    = self.sample_index + (self.channel * self.block_size);
193    let sample   = unsafe { *self.buffer.get_unchecked(index) };
194
195    self.channel += 1;
196
197    // Reset current channel
198    if self.channel == channels {
199      self.channel       = 0;
200      self.sample_index += 1;
201      self.samples_left -= 1;
202    }
203
204    S::to_normal(sample)
205  }
206
207  fn size_hint(&self) -> (usize, Option<usize>) {
208    let samples_left = self.samples_left as usize;
209    let max_value    = usize::max_value() as u64;
210
211    // There is a chance that samples_left will be larger than a usize since
212    // it is a u64. Make the upper bound None when it is.
213    if self.samples_left > max_value {
214      (samples_left, None)
215    } else {
216      (samples_left, Some(samples_left))
217    }
218  }
219}
220
221//impl<'a, P, S> IntoIterator for &'a mut Stream<P>
222// where P: StreamProducer,
223//       S: Sample {
224//  type Item     = S::Normal;
225//  type IntoIter = Iter<'a, P, S>;
226//
227//  #[inline]
228//  fn into_iter(self) -> Self::IntoIter {
229//    self.iter()
230//  }
231//}