1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright 2023 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::fs::File;
use std::io::Error as IOError;
use std::slice;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;

use async_trait::async_trait;
use audio_streams::AsyncBufferCommit;
use audio_streams::AsyncPlaybackBuffer;
use audio_streams::AsyncPlaybackBufferStream;
use audio_streams::AudioStreamsExecutor;
use audio_streams::BoxError;
use audio_streams::NoopStreamControl;
use audio_streams::SampleFormat;
use audio_streams::StreamControl;
use audio_streams::StreamSource;
use audio_streams::StreamSourceGenerator;
use base::warn;
use base::MappedRegion;
use base::MemoryMapping;
use base::MemoryMappingBuilder;
use base::MmapError;
use thiserror::Error as ThisError;

#[derive(ThisError, Debug)]
pub enum Error {
    #[error("Failed to build memory mapping: {0}")]
    BuildMemoryMapping(MmapError),
    #[error("Failed to clone file descriptor: {0}")]
    Clone(IOError),
    #[error("Not implemented")]
    Unimplemented,
}

/// An Audio Stream that can be used to write playback buffer to a file.
/// `FileStream` doesn't directly open and write to file. It receives
/// an mmap of a file instead.
///
/// Note that `FileStream` also needs the mmap-ed file has allocated some spaces
/// to be written. If the playback buffer exceeds the allocated spaces,
/// it will invoke `panic!`
pub struct FileStream {
    /// A MemoryMapping that will hold the copy of the playback buffer.
    memory_mapping: AudioMemoryMapping,
    /// Number of bytes that has been written.
    offset: Arc<AtomicUsize>,
    /// Number of bytes in a single audio frame.
    frame_size: usize,
    /// Length of the current playback buffer in bytes.
    buffer_mem_length: usize,

    /// Duration of an audio in milliseconds for the current `buffer_size`.
    interval_ms: Duration,
    /// Time marker of correct time to return next buffer.
    next_frame: Duration,
    /// Timestamp that records when the stream starts.
    start_time: Option<Instant>,
    /// Type that will be called before the buffer is dropped.
    buffer_drop: FileStreamBufferCommit,
}

impl FileStream {
    fn new(
        memory_mapping: AudioMemoryMapping,
        offset: Arc<AtomicUsize>,
        frame_size: usize,
        buffer_mem_length: usize,
        interval_ms: Duration,
    ) -> Self {
        let max_offset = memory_mapping.size();
        FileStream {
            memory_mapping,
            offset: offset.clone(),
            frame_size,
            buffer_mem_length,

            interval_ms,
            next_frame: interval_ms,
            start_time: None,
            buffer_drop: FileStreamBufferCommit {
                frame_size,
                offset,
                max_offset,
            },
        }
    }
}

#[async_trait(?Send)]
impl AsyncPlaybackBufferStream for FileStream {
    async fn next_playback_buffer<'a>(
        &'a mut self,
        ex: &dyn AudioStreamsExecutor,
    ) -> Result<AsyncPlaybackBuffer<'a>, BoxError> {
        if let Some(start_time) = self.start_time {
            let elapsed = start_time.elapsed();
            if elapsed < self.next_frame {
                ex.delay(self.next_frame - elapsed).await?;
            }
            self.next_frame += self.interval_ms;
        } else {
            self.start_time = Some(Instant::now());
            self.next_frame = self.interval_ms;
        }

        let offset = self.offset.load(Ordering::Relaxed);
        let buffer = self
            .memory_mapping
            .get_slice_mut(offset, self.buffer_mem_length);

        Ok(AsyncPlaybackBuffer::new(
            self.frame_size,
            buffer,
            &mut self.buffer_drop,
        )?)
    }
}

struct FileStreamSource {
    file: File,
    file_size: usize,
    offset: Arc<AtomicUsize>,
}

impl FileStreamSource {
    fn new(file: File, file_size: usize, offset: Arc<AtomicUsize>) -> Self {
        FileStreamSource {
            file,
            file_size,
            offset,
        }
    }
}

impl StreamSource for FileStreamSource {
    fn new_async_playback_stream(
        &mut self,
        num_channels: usize,
        format: SampleFormat,
        frame_rate: u32,
        buffer_size: usize,
        _ex: &dyn AudioStreamsExecutor,
    ) -> Result<(Box<dyn StreamControl>, Box<dyn AsyncPlaybackBufferStream>), BoxError> {
        let memory_mapping = MemoryMappingBuilder::new(self.file_size)
            .from_file(&self.file)
            .build()
            .map_err(Error::BuildMemoryMapping)?;

        let frame_size = format.sample_bytes() * num_channels;
        let buffer_mem_length = buffer_size * frame_size;
        let memory_mapping = AudioMemoryMapping::new(memory_mapping, buffer_mem_length);
        let interval_ms = Duration::from_millis(buffer_size as u64 * 1000 / frame_rate as u64);
        Ok((
            Box::new(NoopStreamControl::new()),
            Box::new(FileStream::new(
                memory_mapping,
                self.offset.clone(),
                frame_size,
                buffer_mem_length,
                interval_ms,
            )),
        ))
    }

    fn new_playback_stream(
        &mut self,
        _num_channels: usize,
        _format: SampleFormat,
        _frame_rate: u32,
        _buffer_size: usize,
    ) -> Result<
        (
            Box<dyn StreamControl>,
            Box<dyn audio_streams::PlaybackBufferStream>,
        ),
        BoxError,
    > {
        Err(Box::new(Error::Unimplemented))
    }
}

/// `FileStreamSourceGenerator` is a struct that implements [`StreamSourceGenerator`]
/// for `FileStreamSource`.
pub struct FileStreamSourceGenerator {
    /// File descriptor which will be used to write playback buffer.
    file: File,
    /// Size of the output file in bytes.
    file_size: usize,
    /// Number of bytes that has been written to the file.
    offset: Arc<AtomicUsize>,
}

impl FileStreamSourceGenerator {
    /// Creates a new `FileStreamSourceGenerator` by given arguments.
    /// It expects `file` has `file_size` of bytes allocated spaces.
    ///
    /// # Arguments
    ///
    /// * `file` - The file where audio playback buffer will be written.
    /// * `file_size` - The size of bytes allocated for playback_file.
    pub fn new(file: File, file_size: usize) -> Self {
        FileStreamSourceGenerator {
            file,
            file_size,
            offset: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl StreamSourceGenerator for FileStreamSourceGenerator {
    fn generate(&self) -> Result<Box<dyn StreamSource>, BoxError> {
        Ok(Box::new(FileStreamSource::new(
            self.file.try_clone().map_err(Error::Clone)?,
            self.file_size,
            self.offset.clone(),
        )))
    }
}

struct FileStreamBufferCommit {
    frame_size: usize,
    offset: Arc<AtomicUsize>,
    max_offset: usize,
}

#[async_trait(?Send)]
impl AsyncBufferCommit for FileStreamBufferCommit {
    async fn commit(&mut self, nwritten: usize) {
        let written_bytes = nwritten * self.frame_size;
        if self.offset.load(Ordering::Relaxed) + written_bytes < self.max_offset {
            self.offset.fetch_add(written_bytes, Ordering::Relaxed);
        }
    }
}

struct AudioMemoryMapping {
    memory_mapping: MemoryMapping,
    zero_buffer: Vec<u8>,
}

impl AudioMemoryMapping {
    fn new(memory_mapping: MemoryMapping, buffer_mem_length: usize) -> Self {
        AudioMemoryMapping {
            memory_mapping,
            zero_buffer: vec![0; buffer_mem_length],
        }
    }

    fn get_slice_mut(&mut self, offset: usize, len: usize) -> &mut [u8] {
        if offset + len >= self.memory_mapping.size() {
            warn!("Accessing unallocated region");
            return &mut self.zero_buffer;
        }
        // SAFETY:
        // safe because the region returned is owned by self.memory_mapping
        unsafe { slice::from_raw_parts_mut(self.memory_mapping.as_ptr().add(offset), len) }
    }

    fn size(&self) -> usize {
        self.memory_mapping.size()
    }
}