1use crate::callrecord::CallRecordHangupReason;
2use crate::event::{EventSender, SessionEvent};
3use crate::media::processor::ProcessorChain;
4use crate::media::track::{Track, TrackConfig, TrackPacketSender};
5use crate::media::{AudioFrame, PcmBuf, Samples, TrackId};
6use anyhow::{Result, anyhow};
7use async_trait::async_trait;
8use audio_codec::BoxedResampler;
9use hound::WavReader;
10use std::cmp::min;
11use std::fs::File;
12use std::io::BufReader;
13use std::sync::{
14 Arc,
15 atomic::{AtomicBool, Ordering},
16};
17use std::time::Instant;
18use tokio::select;
19use tokio::time::Duration;
20use tokio_util::sync::CancellationToken;
21use tracing::{debug, info, warn};
22
23trait AudioReader: Send {
24 fn fill_buffer(&mut self) -> Result<usize>;
25
26 fn read_chunk(&mut self, packet_duration_ms: u32) -> Result<Option<(PcmBuf, u32)>> {
27 let max_chunk_size = self.sample_rate() as usize * packet_duration_ms as usize / 1000;
28
29 if self.buffer_size() == 0 || self.position() >= self.buffer_size() {
30 let samples_read = self.fill_buffer()?;
31 if samples_read == 0 {
32 return Ok(None);
33 }
34 self.set_position(0);
35 }
36
37 let remaining = self.buffer_size() - self.position();
38 if remaining == 0 {
39 return Ok(None);
40 }
41
42 let chunk_size = min(max_chunk_size, remaining);
43 let end_pos = self.position() + chunk_size;
44
45 assert!(
46 end_pos <= self.buffer_size(),
47 "Buffer overrun: pos={}, end={}, size={}",
48 self.position(),
49 end_pos,
50 self.buffer_size()
51 );
52
53 let chunk = self.extract_chunk(self.position(), end_pos);
54 self.set_position(end_pos);
55
56 let final_chunk =
57 if self.sample_rate() != self.target_sample_rate() && self.sample_rate() > 0 {
58 self.resample_chunk(&chunk)
59 } else {
60 chunk
61 };
62
63 Ok(Some((final_chunk, self.target_sample_rate())))
64 }
65
66 fn buffer_size(&self) -> usize;
67 fn position(&self) -> usize;
68 fn set_position(&mut self, pos: usize);
69 fn sample_rate(&self) -> u32;
70 fn target_sample_rate(&self) -> u32;
71 fn channels(&self) -> u16;
72 fn extract_chunk(&self, start: usize, end: usize) -> Vec<i16>;
73 fn resample_chunk(&mut self, chunk: &[i16]) -> Vec<i16>;
74}
75
76struct DecodedAudioReader {
77 buffer: Vec<i16>,
78 sample_rate: u32,
79 position: usize,
80 target_sample_rate: u32,
81 resampler: Option<BoxedResampler>,
82}
83
84impl DecodedAudioReader {
85 #[cfg(test)]
86 fn from_file(
87 file: File,
88 extension: &str,
89 mime_type: Option<&str>,
90 target_sample_rate: u32,
91 ) -> Result<Self> {
92 let all_samples =
93 crate::media::loader::decode_audio(file, extension, mime_type, target_sample_rate)?;
94 Ok(Self {
95 buffer: all_samples,
96 sample_rate: target_sample_rate,
97 position: 0,
98 target_sample_rate,
99 resampler: None,
100 })
101 }
102
103 fn from_samples(buffer: Vec<i16>, sample_rate: u32, target_sample_rate: u32) -> Self {
107 Self {
108 buffer,
109 sample_rate,
110 position: 0,
111 target_sample_rate,
112 resampler: None,
113 }
114 }
115}
116
117impl AudioReader for DecodedAudioReader {
118 fn fill_buffer(&mut self) -> Result<usize> {
119 if self.position >= self.buffer.len() {
120 return Ok(0);
121 }
122 Ok(self.buffer.len() - self.position)
123 }
124
125 fn buffer_size(&self) -> usize {
126 self.buffer.len()
127 }
128
129 fn position(&self) -> usize {
130 self.position
131 }
132
133 fn set_position(&mut self, pos: usize) {
134 self.position = pos;
135 }
136
137 fn sample_rate(&self) -> u32 {
138 self.sample_rate
139 }
140
141 fn target_sample_rate(&self) -> u32 {
142 self.target_sample_rate
143 }
144
145 fn channels(&self) -> u16 {
146 1
147 }
148
149 fn extract_chunk(&self, start: usize, end: usize) -> Vec<i16> {
150 self.buffer[start..end].to_vec()
151 }
152
153 fn resample_chunk(&mut self, chunk: &[i16]) -> Vec<i16> {
154 if self.sample_rate == 0 || self.sample_rate == self.target_sample_rate {
155 return chunk.to_vec();
156 }
157
158 if let Some(resampler) = &mut self.resampler {
159 resampler.resample(chunk)
160 } else {
161 let mut new_resampler =
162 BoxedResampler::new(self.sample_rate as usize, self.target_sample_rate as usize)
163 .expect("invalid sample rate");
164 let result = new_resampler.resample(chunk);
165 self.resampler = Some(new_resampler);
166 result
167 }
168 }
169}
170
171async fn process_audio_reader(
173 mut processor_chain: ProcessorChain,
174 mut audio_reader: Box<dyn AudioReader>,
175 track_id: &str,
176 packet_duration_ms: u32,
177 target_sample_rate: u32,
178 token: CancellationToken,
179 paused: Arc<AtomicBool>,
180 packet_sender: TrackPacketSender,
181) -> Result<()> {
182 info!(
183 "streaming audio with target_sample_rate: {}, packet_duration: {}ms",
184 target_sample_rate, packet_duration_ms
185 );
186 let stream_loop = async move {
187 let start_time = Instant::now();
188 let mut ticker = tokio::time::interval(Duration::from_millis(packet_duration_ms as u64));
189 let channels = audio_reader.channels();
190 loop {
191 if paused.load(Ordering::Relaxed) {
192 ticker.tick().await;
193 continue;
194 }
195
196 let Some((chunk, chunk_sample_rate)) = audio_reader.read_chunk(packet_duration_ms)?
197 else {
198 break;
199 };
200
201 let mut packet = AudioFrame {
202 track_id: track_id.to_string(),
203 timestamp: crate::media::get_timestamp(),
204 samples: Samples::PCM { samples: chunk },
205 sample_rate: chunk_sample_rate,
206 channels,
207 ..Default::default()
208 };
209
210 match processor_chain.process_frame(&mut packet) {
211 Ok(_) => {}
212 Err(e) => {
213 warn!("failed to process audio packet: {}", e);
214 }
215 }
216
217 if let Err(e) = packet_sender.send(packet) {
218 warn!("failed to send audio packet: {}", e);
219 break;
220 }
221
222 ticker.tick().await;
223 }
224
225 info!("stream loop finished in {:?}", start_time.elapsed());
226 Ok(()) as Result<()>
227 };
228
229 select! {
230 _ = token.cancelled() => {
231 info!("stream cancelled");
232 return Ok(());
233 }
234 result = stream_loop => {
235 info!("stream loop finished");
236 result
237 }
238 }
239}
240
241pub struct FileTrack {
242 track_id: TrackId,
243 play_id: Option<String>,
244 config: TrackConfig,
245 cancel_token: CancellationToken,
246 processor_chain: ProcessorChain,
247 path: Option<String>,
248 use_cache: bool,
249 ssrc: u32,
250 offset_ms: u32,
251 hangup_reason: Option<CallRecordHangupReason>,
254 paused: Arc<AtomicBool>,
255}
256
257impl FileTrack {
258 pub fn new(id: TrackId) -> Self {
259 let config = TrackConfig::default();
260 Self {
261 track_id: id,
262 play_id: None,
263 processor_chain: ProcessorChain::new(config.samplerate),
264 config,
265 cancel_token: CancellationToken::new(),
266 path: None,
267 use_cache: true,
268 ssrc: 0,
269 offset_ms: 0,
270 hangup_reason: None,
271 paused: Arc::new(AtomicBool::new(false)),
272 }
273 }
274
275 pub fn with_play_id(mut self, play_id: Option<String>) -> Self {
276 self.play_id = play_id;
277 self
278 }
279
280 pub fn with_ssrc(mut self, ssrc: u32) -> Self {
281 self.ssrc = ssrc;
282 self
283 }
284 pub fn with_config(mut self, config: TrackConfig) -> Self {
285 self.config = config;
286 self
287 }
288
289 pub fn with_cancel_token(mut self, cancel_token: CancellationToken) -> Self {
290 self.cancel_token = cancel_token;
291 self
292 }
293
294 pub fn with_path(mut self, path: String) -> Self {
295 self.path = Some(path);
296 self
297 }
298
299 pub fn with_sample_rate(mut self, sample_rate: u32) -> Self {
300 self.config = self.config.with_sample_rate(sample_rate);
301 self
302 }
303
304 pub fn with_ptime(mut self, ptime: Duration) -> Self {
305 self.config = self.config.with_ptime(ptime);
306 self
307 }
308
309 pub fn with_cache_enabled(mut self, use_cache: bool) -> Self {
310 self.use_cache = use_cache;
311 self
312 }
313
314 pub fn with_offset_ms(mut self, offset_ms: u32) -> Self {
315 self.offset_ms = offset_ms;
316 self
317 }
318
319 pub fn with_auto_hangup(mut self, auto_hangup: Option<bool>) -> Self {
321 self.hangup_reason = if auto_hangup == Some(true) {
322 Some(CallRecordHangupReason::BySystem)
323 } else {
324 None
325 };
326 self
327 }
328}
329
330#[async_trait]
331impl Track for FileTrack {
332 fn ssrc(&self) -> u32 {
333 self.ssrc
334 }
335
336 fn cancel_token(&self) -> CancellationToken {
337 self.cancel_token.clone()
338 }
339 fn id(&self) -> &TrackId {
340 &self.track_id
341 }
342 fn config(&self) -> &TrackConfig {
343 &self.config
344 }
345 fn set_paused(&self, paused: bool) -> bool {
346 self.paused.store(paused, Ordering::Relaxed);
347 true
348 }
349 fn is_paused(&self) -> bool {
350 self.paused.load(Ordering::Relaxed)
351 }
352 fn processor_chain(&mut self) -> &mut ProcessorChain {
353 &mut self.processor_chain
354 }
355
356 async fn handshake(&mut self, _offer: String, _timeout: Option<Duration>) -> Result<String> {
357 Ok("".to_string())
358 }
359 async fn update_remote_description(&mut self, _answer: &String) -> Result<()> {
360 Ok(())
361 }
362
363 async fn start(
364 &mut self,
365 event_sender: EventSender,
366 packet_sender: TrackPacketSender,
367 ) -> Result<()> {
368 if self.path.is_none() {
369 return Err(anyhow::anyhow!("filetrack: No path provided for FileTrack"));
370 }
371 let path = self.path.clone().unwrap();
372 let id = self.track_id.clone();
373 let sample_rate = self.config.samplerate;
374 let use_cache = self.use_cache;
375 let packet_duration_ms = self.config.ptime.as_millis() as u32;
376 let processor_chain = self.processor_chain.clone();
377 let token = self.cancel_token.clone();
378 let start_time = crate::media::get_timestamp();
379 let ssrc = self.ssrc;
380 let offset_ms = self.offset_ms;
381 let paused = self.paused.clone();
382 let play_id = self.play_id.clone();
384 let hangup_reason = self.hangup_reason.clone();
385 crate::spawn(async move {
386 let res = async move {
387 let load_result = crate::media::loader::load_audio_as_pcm_cached(
390 &path,
391 sample_rate,
392 use_cache,
393 offset_ms,
394 )
395 .await;
396 let samples = match load_result {
397 Ok(samples) => samples,
398 Err(e) => {
399 warn!("filetrack: Error loading audio: {} {}", path, e);
400 event_sender
401 .send(SessionEvent::Error {
402 track_id: id.clone(),
403 timestamp: crate::media::get_timestamp(),
404 sender: format!("filetrack: {}", path),
405 error: e.to_string(),
406 code: None,
407 })
408 .ok();
409 event_sender
410 .send(SessionEvent::TrackEnd {
411 track_id: id,
412 timestamp: crate::media::get_timestamp(),
413 duration: crate::media::get_timestamp() - start_time,
414 ssrc,
415 play_id: play_id.clone(),
416 auto_hangup: hangup_reason.clone(),
417 })
418 .ok();
419 return Err(e);
420 }
421 };
422
423 let stream_result = stream_pcm_samples(
425 processor_chain,
426 samples,
427 sample_rate,
428 &id,
429 packet_duration_ms,
430 token.clone(),
431 paused,
432 packet_sender,
433 )
434 .await;
435
436 if let Err(e) = stream_result {
438 warn!("filetrack: Error streaming audio: {}, {}", path, e);
439 event_sender
440 .send(SessionEvent::Error {
441 track_id: id.clone(),
442 timestamp: crate::media::get_timestamp(),
443 sender: format!("filetrack: {}", path),
444 error: e.to_string(),
445 code: None,
446 })
447 .ok();
448 }
449
450 event_sender
452 .send(SessionEvent::TrackEnd {
453 track_id: id,
454 timestamp: crate::media::get_timestamp(),
455 duration: crate::media::get_timestamp() - start_time,
456 ssrc,
457 play_id,
458 auto_hangup: if token.is_cancelled() {
459 None
460 } else {
461 hangup_reason
462 },
463 })
464 .ok();
465 Ok::<(), anyhow::Error>(())
466 }
467 .await;
468 if let Err(e) = res {
469 debug!("filetrack: streaming task finished with error: {:?}", e);
470 }
471 });
472 Ok(())
473 }
474
475 async fn stop(&self) -> Result<()> {
476 self.cancel_token.cancel();
478 Ok(())
479 }
480
481 async fn send_packet(&mut self, _packet: &AudioFrame) -> Result<()> {
483 Ok(())
484 }
485}
486
487async fn stream_pcm_samples(
489 processor_chain: ProcessorChain,
490 samples: Vec<i16>,
491 target_sample_rate: u32,
492 track_id: &str,
493 packet_duration_ms: u32,
494 token: CancellationToken,
495 paused: Arc<AtomicBool>,
496 packet_sender: TrackPacketSender,
497) -> Result<()> {
498 let reader = DecodedAudioReader::from_samples(samples, target_sample_rate, target_sample_rate);
499 let audio_reader = Box::new(reader) as Box<dyn AudioReader>;
500 info!(
501 "filetrack: streaming {} decoded samples at {} Hz",
502 audio_reader.buffer_size(),
503 audio_reader.sample_rate(),
504 );
505 process_audio_reader(
506 processor_chain,
507 audio_reader,
508 track_id,
509 packet_duration_ms,
510 target_sample_rate,
511 token,
512 paused,
513 packet_sender,
514 )
515 .await
516}
517
518pub fn read_wav_file(path: &str) -> Result<(PcmBuf, u32)> {
520 let reader = BufReader::new(File::open(path)?);
521 let mut wav_reader = WavReader::new(reader)?;
522 let spec = wav_reader.spec();
523 let mut all_samples = Vec::new();
524
525 match spec.sample_format {
526 hound::SampleFormat::Int => match spec.bits_per_sample {
527 16 => {
528 for sample in wav_reader.samples::<i16>() {
529 all_samples.push(sample.unwrap_or(0));
530 }
531 }
532 8 => {
533 for sample in wav_reader.samples::<i8>() {
534 all_samples.push(sample.unwrap_or(0) as i16);
535 }
536 }
537 24 | 32 => {
538 for sample in wav_reader.samples::<i32>() {
539 all_samples.push((sample.unwrap_or(0) >> 16) as i16);
540 }
541 }
542 _ => {
543 return Err(anyhow!(
544 "Unsupported bits per sample: {}",
545 spec.bits_per_sample
546 ));
547 }
548 },
549 hound::SampleFormat::Float => {
550 for sample in wav_reader.samples::<f32>() {
551 all_samples.push((sample.unwrap_or(0.0) * 32767.0) as i16);
552 }
553 }
554 }
555
556 if spec.channels == 2 {
558 let mono_samples = all_samples
559 .chunks(2)
560 .map(|chunk| ((chunk[0] as i32 + chunk[1] as i32) / 2) as i16)
561 .collect();
562 all_samples = mono_samples;
563 }
564 Ok((all_samples, spec.sample_rate))
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570 use std::io::Write;
571
572 #[tokio::test]
573 async fn test_wav_reader() -> Result<()> {
574 let file_path = "fixtures/sample.wav";
575 let file = File::open(file_path)?;
576 let mut reader = DecodedAudioReader::from_file(file, "wav", None, 16000)?;
577 let mut total_samples = 0;
578 let mut total_duration_ms = 0.0;
579 let mut chunk_count = 0;
580 while let Some((chunk, chunk_sample_rate)) = reader.read_chunk(20)? {
581 total_samples += chunk.len();
582 chunk_count += 1;
583 let chunk_duration_ms = (chunk.len() as f64 / chunk_sample_rate as f64) * 1000.0;
584 total_duration_ms += chunk_duration_ms;
585 }
586
587 let duration_seconds = total_duration_ms / 1000.0;
588 println!("Total chunks: {}", chunk_count);
589 println!("Actual samples: {}", total_samples);
590 println!("Actual duration: {:.2} seconds", duration_seconds);
591 assert_eq!(format!("{:.2}", duration_seconds), "7.51");
592 Ok(())
593 }
594 #[tokio::test]
595 async fn test_wav_file_track() -> Result<()> {
596 println!("Starting WAV file track test");
597
598 let file_path = "fixtures/sample.wav";
599 let file = File::open(file_path)?;
600
601 let mut reader = hound::WavReader::new(File::open(file_path)?)?;
603 let spec = reader.spec();
604 let total_expected_samples = reader.duration() as usize;
605 let expected_duration = total_expected_samples as f64 / spec.sample_rate as f64;
606 println!("WAV file spec: {:?}", spec);
607 println!("Expected samples: {}", total_expected_samples);
608 println!("Expected duration: {:.2} seconds", expected_duration);
609
610 let mut verify_samples = Vec::new();
612 for sample in reader.samples::<i16>() {
613 verify_samples.push(sample?);
614 }
615 println!("Verified total samples: {}", verify_samples.len());
616
617 let mut reader = DecodedAudioReader::from_file(file, "wav", None, 16000)?;
618 let mut total_samples = 0;
619 let mut total_duration_ms = 0.0;
620 let mut chunk_count = 0;
621
622 while let Some((chunk, chunk_sample_rate)) = reader.read_chunk(320)? {
623 total_samples += chunk.len();
624 chunk_count += 1;
625 let chunk_duration_ms = (chunk.len() as f64 / chunk_sample_rate as f64) * 1000.0;
627 total_duration_ms += chunk_duration_ms;
628 }
629
630 let duration_seconds = total_duration_ms / 1000.0;
631 println!("Total chunks: {}", chunk_count);
632 println!("Actual samples: {}", total_samples);
633 println!("Actual duration: {:.2} seconds", duration_seconds);
634
635 const TOLERANCE: f64 = 0.01; let expected_samples = if spec.channels == 2 {
640 total_expected_samples / 2 } else {
642 total_expected_samples
643 };
644
645 assert!(
646 (duration_seconds - expected_duration).abs() < expected_duration * TOLERANCE,
647 "Duration {:.2} differs from expected {:.2} by more than {}%",
648 duration_seconds,
649 expected_duration,
650 TOLERANCE * 100.0
651 );
652
653 assert!(
654 (total_samples as f64 - expected_samples as f64).abs()
655 < expected_samples as f64 * TOLERANCE,
656 "Sample count {} differs from expected {} by more than {}%",
657 total_samples,
658 expected_samples,
659 TOLERANCE * 100.0
660 );
661
662 Ok(())
663 }
664
665 #[tokio::test]
666 async fn test_mp3_decode_sample_file() -> Result<()> {
667 let file_path = "fixtures/sample.mp3".to_string();
668 match File::open(&file_path) {
669 Ok(file) => {
670 let samples = crate::media::loader::decode_audio(file, "mp3", None, 16000)?;
671 assert!(
672 !samples.is_empty(),
673 "Decoded sample list should not be empty"
674 );
675 }
676 Err(_) => {
677 println!("Skipping MP3 test: sample file not found at {}", file_path);
678 }
679 }
680 Ok(())
681 }
682
683 #[tokio::test]
684 async fn test_mp3_file_track() -> Result<()> {
685 println!("Starting MP3 file track test");
686
687 let file_path = "fixtures/sample.mp3".to_string();
689 let file = File::open(&file_path)?;
690 let sample_rate = 16000;
691 let mut reader = DecodedAudioReader::from_file(file, "mp3", None, sample_rate)?;
692 let mut total_samples = 0;
693 let mut total_duration_ms = 0.0;
694 while let Some((chunk, _chunk_sample_rate)) = reader.read_chunk(320)? {
695 total_samples += chunk.len();
696 let chunk_duration_ms = (chunk.len() as f64 / sample_rate as f64) * 1000.0;
698 total_duration_ms += chunk_duration_ms;
699 }
700 let duration_seconds = total_duration_ms / 1000.0;
701 println!("Total samples: {}", total_samples);
702 println!("Duration: {:.2} seconds", duration_seconds);
703
704 const EXPECTED_SAMPLES: usize = 226310;
705 assert!(
706 total_samples == EXPECTED_SAMPLES,
707 "Sample count {} does not match expected {}",
708 total_samples,
709 EXPECTED_SAMPLES
710 );
711 Ok(())
712 }
713
714 #[tokio::test]
715 #[ignore = "manual debug helper: dumps raw pcm for ffplay"]
716 async fn dump_mp3_as_16k_pcm_for_ffplay() -> Result<()> {
717 let input_path = "fixtures/sample.mp3";
718 let output_path = "target/tmp/sample_16k_mono_s16le.pcm";
719
720 let file = File::open(input_path)?;
721 let mut reader = DecodedAudioReader::from_file(file, "mp3", None, 16000)?;
722
723 let mut pcm_samples = Vec::<i16>::new();
724 while let Some((chunk, _chunk_sample_rate)) = reader.read_chunk(320)? {
725 pcm_samples.extend_from_slice(&chunk);
726 }
727
728 std::fs::create_dir_all("target/tmp")?;
729 let mut out = std::fs::File::create(output_path)?;
730 for sample in pcm_samples {
731 out.write_all(&sample.to_le_bytes())?;
732 }
733 out.flush()?;
734
735 println!("PCM dumped: {}", output_path);
736 println!("ffplay -f s16le -ar 16000 -ac 1 {}", output_path);
737 Ok(())
738 }
739}