Skip to main content

fyrox_sound/buffer/
streaming.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Streaming buffer.
22//!
23//! # Overview
24//!
25//! Streaming buffers are used for long sounds (usually longer than 15 seconds) to reduce memory usage.
26//! Some sounds in games are very long - music, ambient sounds, voice, etc. and it is too inefficient
27//! to load and decode them directly into memory all at once - it will just take enormous amount of memory
28//! that could be used to something more useful.
29//!
30//! # Usage
31//!
32//! There are almost no difference with generic buffers:
33//!
34//! ```no_run
35//! use std::sync::{Mutex, Arc};
36//! use fyrox_sound::buffer::{SoundBufferResource, DataSource, SoundBufferResourceExtension};
37//! use fyrox_resource::io::FsResourceIo;
38//!
39//! async fn make_streaming_buffer() -> SoundBufferResource {
40//!     let data_source = DataSource::from_file("some_long_sound.ogg", &FsResourceIo).await.unwrap();
41//!     SoundBufferResource::new_streaming(data_source).unwrap()
42//! }
43//! ```
44//!
45//! # Notes
46//!
47//! Streaming buffer cannot be shared across multiple source. On attempt to create a source with a streaming
48//! buffer that already in use you'll get error.
49
50use crate::buffer::generic::Samples;
51use crate::{
52    buffer::{generic::GenericBuffer, DataSource, RawStreamingDataSource},
53    decoder::Decoder,
54    error::SoundError,
55};
56use fyrox_core::{reflect::prelude::*, visitor::prelude::*};
57use std::{
58    ops::{Deref, DerefMut},
59    time::Duration,
60};
61
62/// Streaming buffer for long sounds. Does not support random access.
63#[derive(Debug, Default, Visit, Reflect)]
64#[reflect(non_cloneable)]
65pub struct StreamingBuffer {
66    pub(crate) generic: GenericBuffer,
67    /// Count of sources that share this buffer, it is important to keep only one
68    /// user of streaming buffer, because streaming buffer does not allow random
69    /// access.
70    #[visit(skip)]
71    pub(crate) use_count: usize,
72    #[visit(skip)]
73    #[reflect(hidden)]
74    streaming_source: StreamingSource,
75}
76
77#[derive(Debug, Default)]
78enum StreamingSource {
79    #[default]
80    Null,
81    Decoder(Decoder),
82    Raw(Box<dyn RawStreamingDataSource>),
83}
84
85impl StreamingSource {
86    #[inline]
87    fn new(data_source: DataSource) -> Result<Self, SoundError> {
88        match data_source {
89            DataSource::File { .. } | DataSource::Memory(_) => {
90                Ok(Self::Decoder(Decoder::new(data_source)?))
91            }
92            DataSource::RawStreaming(raw) => Ok(Self::Raw(raw)),
93            // It makes no sense to stream raw data which is already loaded into memory.
94            _ => Err(SoundError::UnsupportedFormat),
95        }
96    }
97
98    #[inline]
99    fn sample_rate(&self) -> usize {
100        match self {
101            StreamingSource::Decoder(decoder) => decoder.get_sample_rate(),
102            StreamingSource::Raw(raw) => raw.sample_rate(),
103            StreamingSource::Null => 0,
104        }
105    }
106
107    #[inline]
108    fn channel_count(&self) -> usize {
109        match self {
110            StreamingSource::Decoder(decoder) => decoder.get_channel_count(),
111            StreamingSource::Raw(raw) => raw.channel_count(),
112            StreamingSource::Null => 0,
113        }
114    }
115
116    fn channel_duration_in_samples(&self) -> usize {
117        match self {
118            StreamingSource::Null => 0,
119            StreamingSource::Decoder(decoder) => decoder.channel_duration_in_samples(),
120            StreamingSource::Raw(raw) => raw.channel_duration_in_samples(),
121        }
122    }
123
124    fn rewind(&mut self) -> Result<(), SoundError> {
125        match self {
126            StreamingSource::Null => Ok(()),
127            StreamingSource::Decoder(decoder) => decoder.rewind(),
128            StreamingSource::Raw(raw) => raw.rewind(),
129        }
130    }
131
132    fn time_seek(&mut self, location: Duration) -> Result<(), SoundError> {
133        match self {
134            StreamingSource::Null => Ok(()),
135            StreamingSource::Decoder(decoder) => decoder.time_seek(location),
136            StreamingSource::Raw(raw) => raw.time_seek(location),
137        }
138    }
139
140    #[inline]
141    fn read_next_samples_block_into(&mut self, buffer: &mut Vec<f32>) -> usize {
142        buffer.clear();
143        let count = StreamingBuffer::STREAM_SAMPLE_COUNT * self.channel_count();
144        match self {
145            StreamingSource::Decoder(decoder) => {
146                for _ in 0..count {
147                    if let Some(sample) = decoder.next() {
148                        buffer.push(sample)
149                    } else {
150                        break;
151                    }
152                }
153            }
154            StreamingSource::Raw(raw_streaming) => {
155                for _ in 0..count {
156                    if let Some(sample) = raw_streaming.next() {
157                        buffer.push(sample)
158                    } else {
159                        break;
160                    }
161                }
162            }
163            StreamingSource::Null => (),
164        }
165
166        buffer.len()
167    }
168}
169
170impl StreamingBuffer {
171    /// Defines amount of samples `per channel` which each streaming buffer will use for internal buffer.
172    pub const STREAM_SAMPLE_COUNT: usize = 44100;
173
174    /// Creates new streaming buffer using given data source. May fail if data source has unsupported format
175    /// or it has corrupted data. Length of internal generic buffer cannot be changed but can be fetched from
176    /// `StreamingBuffer::STREAM_SAMPLE_COUNT`
177    ///
178    /// # Notes
179    ///
180    /// This function will return Err if data source is `Raw`. It makes no sense to stream raw data which
181    /// is already loaded into memory. Use Generic source instead!
182    pub fn new(source: DataSource) -> Result<Self, SoundError> {
183        let mut streaming_source = StreamingSource::new(source)?;
184
185        let mut samples = Vec::new();
186        let channel_count = streaming_source.channel_count();
187        streaming_source.read_next_samples_block_into(&mut samples);
188        debug_assert_eq!(samples.len() % channel_count, 0);
189
190        Ok(Self {
191            generic: GenericBuffer {
192                samples: Samples(samples),
193                sample_rate: streaming_source.sample_rate(),
194                channel_count: streaming_source.channel_count(),
195                channel_duration_in_samples: streaming_source.channel_duration_in_samples(),
196            },
197            use_count: 0,
198            streaming_source,
199        })
200    }
201
202    #[inline]
203    pub(crate) fn read_next_block(&mut self) {
204        self.streaming_source
205            .read_next_samples_block_into(&mut self.generic.samples);
206    }
207
208    #[inline]
209    pub(crate) fn rewind(&mut self) -> Result<(), SoundError> {
210        self.streaming_source.rewind()
211    }
212
213    #[inline]
214    pub(crate) fn time_seek(&mut self, location: Duration) -> Result<(), SoundError> {
215        self.streaming_source.time_seek(location)
216    }
217}
218
219impl Deref for StreamingBuffer {
220    type Target = GenericBuffer;
221
222    /// Returns shared reference to internal generic buffer. Can be useful to get some info (sample rate,
223    /// channel count).
224    fn deref(&self) -> &Self::Target {
225        &self.generic
226    }
227}
228
229impl DerefMut for StreamingBuffer {
230    /// Returns mutable reference to internal generic buffer. Can be used to modify it.
231    fn deref_mut(&mut self) -> &mut Self::Target {
232        &mut self.generic
233    }
234}