Guest User

Untitled

a guest
Jul 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.50 KB | None | 0 0
  1. extern crate cpal;
  2. extern crate hound;
  3.  
  4. use std::f32;
  5. use std::sync::{Arc, Mutex};
  6. use std::sync::atomic::{AtomicBool, Ordering};
  7. use std::thread;
  8. use std::ops;
  9.  
  10. use cpal::{StreamData, UnknownTypeOutputBuffer};
  11.  
  12.  
  13. trait Sample {
  14. fn as_u16(&self) -> u16;
  15. fn as_i16(&self) -> i16;
  16. fn as_f32(&self) -> f32;
  17. fn zero() -> Self;
  18. }
  19.  
  20. /*
  21. /// Blanket impl for references
  22. impl<'a, T: Sample> Sample for &'a T {
  23. fn as_u16(&self) -> u16 {
  24. T::as_u16(self)
  25. }
  26.  
  27. fn as_i16(&self) -> i16 {
  28. T::as_i16(self)
  29. }
  30.  
  31. fn as_f32(&self) -> f32 {
  32. T::as_f32(self)
  33. }
  34.  
  35. fn zero() -> Self {
  36. T::zero()
  37. }
  38. }*/
  39.  
  40. impl Sample for i16 {
  41. fn as_u16(&self) -> u16 {
  42. ((u16::max_value() / 2) as i32 + *self as i32) as u16
  43. }
  44.  
  45. fn as_i16(&self) -> i16 {
  46. *self
  47. }
  48.  
  49. fn as_f32(&self) -> f32 {
  50. *self as f32 / i16::max_value() as f32
  51. }
  52.  
  53. fn zero() -> Self {
  54. 0
  55. }
  56. }
  57.  
  58. impl Sample for f32 {
  59. fn as_u16(&self) -> u16 {
  60. ((u16::max_value() / 2) as i32 + self.as_i16() as i32) as u16
  61. }
  62.  
  63. fn as_i16(&self) -> i16 {
  64. (*self * i16::max_value() as f32) as i16
  65. }
  66.  
  67. fn as_f32(&self) -> f32 {
  68. *self
  69. }
  70.  
  71. fn zero() -> Self {
  72. 0.0
  73. }
  74. }
  75.  
  76. trait Stream: Iterator {
  77. fn n_channels(&self) -> usize;
  78.  
  79. fn broadcast(self, n: usize) -> Broadcast<Self::Item, Self>
  80. where
  81. Self: Sized,
  82. Self::Item: Sample,
  83. {
  84. Broadcast {
  85. inner: self,
  86. n_channels: n,
  87. current_sample: Self::Item::zero(),
  88. reps_to_go: 0,
  89. }
  90. }
  91.  
  92. fn floatify(self) -> Floatify<Self>
  93. where
  94. Self: Sized,
  95. {
  96. Floatify {
  97. inner: self,
  98. }
  99. }
  100.  
  101. fn repeat(self) -> Repeated<Self::Item>
  102. where
  103. Self: Sized,
  104. {
  105. Repeated {
  106. n_channels: self.n_channels(),
  107. buffer: self.collect(),
  108. index: 0,
  109. }
  110. }
  111. }
  112.  
  113. impl<'a, S> Stream for std::iter::Cloned<std::slice::Iter<'a, S>>
  114. where S: Sample + Clone
  115. {
  116. fn n_channels(&self) -> usize {
  117. 1
  118. }
  119. }
  120.  
  121. impl<'a, S> Stream for std::vec::IntoIter<S>
  122. where S: Sample + Clone
  123. {
  124. fn n_channels(&self) -> usize {
  125. 1
  126. }
  127. }
  128.  
  129. struct Floatify<T> {
  130. inner: T,
  131. }
  132.  
  133. impl<S, T> Stream for Floatify<T>
  134. where
  135. T: Stream<Item=S>,
  136. S: Sample,
  137. {
  138. fn n_channels(&self) -> usize {
  139. self.inner.n_channels()
  140. }
  141. }
  142.  
  143. impl<S, T> Iterator for Floatify<T>
  144. where
  145. T: Stream<Item=S>,
  146. S: Sample,
  147. {
  148. type Item = f32;
  149. fn next(&mut self) -> Option<f32> {
  150. self.inner.next().map(|s| s.as_f32())
  151. }
  152. }
  153.  
  154. struct Repeated<S> {
  155. n_channels: usize,
  156. buffer: Vec<S>,
  157. index: usize,
  158. }
  159.  
  160. impl<S> Stream for Repeated<S>
  161. where
  162. S: Clone,
  163. {
  164. fn n_channels(&self) -> usize {
  165. self.n_channels
  166. }
  167. }
  168.  
  169. impl<S> Iterator for Repeated<S>
  170. where
  171. S: Clone,
  172. {
  173. type Item = S;
  174.  
  175. fn next(&mut self) -> Option<S> {
  176. if self.index >= self.buffer.len() {
  177. if self.buffer.len() == 0 {
  178. return None
  179. }
  180. self.index = 0;
  181. }
  182.  
  183. let x = self.buffer[self.index].clone();
  184. self.index += 1;
  185. Some(x)
  186. }
  187. }
  188.  
  189. #[derive(Clone)]
  190. struct SharedBuffer<S: 'static> {
  191. n_channels: usize,
  192. buffer: Arc<Vec<S>>,
  193. index: usize,
  194. }
  195.  
  196. impl<S> Stream for SharedBuffer<S>
  197. where
  198. S: Clone + 'static,
  199. {
  200. fn n_channels(&self) -> usize {
  201. self.n_channels
  202. }
  203. }
  204.  
  205. impl<S> Iterator for SharedBuffer<S>
  206. where
  207. S: Clone + 'static,
  208. {
  209. type Item = S;
  210.  
  211. fn next(&mut self) -> Option<S> {
  212. if self.index >= self.buffer.len() {
  213. None
  214. } else {
  215. let x = self.buffer[self.index].clone();
  216. self.index += 1;
  217. Some(x)
  218. }
  219. }
  220. }
  221.  
  222. struct Broadcast<S, T>
  223. {
  224. inner: T,
  225. n_channels: usize,
  226. current_sample: S,
  227. reps_to_go: usize,
  228. }
  229.  
  230. impl<S, T> Stream for Broadcast<S, T>
  231. where
  232. T: Stream<Item=S>,
  233. S: Sample + Clone,
  234. {
  235. fn n_channels(&self) -> usize {
  236. self.n_channels
  237. }
  238. }
  239.  
  240. impl<S, T> Iterator for Broadcast<S, T>
  241. where
  242. T: Stream<Item=S>,
  243. S: Sample + Clone,
  244. {
  245. type Item = S;
  246.  
  247. fn next(&mut self) -> Option<Self::Item> {
  248. if self.reps_to_go == 0 {
  249. self.current_sample = self.inner.next()?;
  250. self.reps_to_go = self.n_channels;
  251. }
  252.  
  253. self.reps_to_go -= 1;
  254. Some(self.current_sample.clone())
  255. }
  256. }
  257.  
  258.  
  259. struct BFormat {
  260. w: f32,
  261. x: f32,
  262. y: f32,
  263. z: f32,
  264. }
  265.  
  266. impl BFormat {
  267. fn virtual_microphone(&self, dir: [f32; 3], p: f32) -> f32 {
  268. p * 2f32.sqrt() * self.w + (1.0 - p) * (dir[0] * self.x + dir[1] * self.y + dir[2] * self.z)
  269. }
  270. }
  271.  
  272. impl Default for BFormat {
  273. fn default() -> Self {
  274. BFormat {w: 0.0, x: 0.0, y: 0.0, z: 0.0}
  275. }
  276. }
  277.  
  278. impl ops::AddAssign for BFormat {
  279. fn add_assign(&mut self, other: Self) {
  280. self.w += other.w;
  281. self.x += other.x;
  282. self.y += other.y;
  283. self.z += other.z;
  284. }
  285. }
  286.  
  287. impl<'a> ops::Mul<f32> for &'a BFormat {
  288. type Output = BFormat;
  289. fn mul(self, s: f32) -> BFormat {
  290. BFormat {
  291. w: self.w * s,
  292. x: self.x * s,
  293. y: self.y * s,
  294. z: self.z * s,
  295. }
  296. }
  297. }
  298.  
  299. impl From<[f32; 3]> for BFormat {
  300. fn from(dir: [f32; 3]) -> Self {
  301. let l = (dir[0] * dir[0] + dir[1] * dir[1] + dir[1] * dir[2]).sqrt();
  302. BFormat {
  303. w: 1.0 / 2f32.sqrt(),
  304. x: dir[0] / l,
  305. y: dir[1] / l,
  306. z: dir[2] / l,
  307. }
  308. }
  309. }
  310.  
  311.  
  312. struct BStreamStereoDecoder {
  313. input: BStreamMixer,
  314. left_mic: [f32; 3],
  315. right_mic: [f32; 3],
  316.  
  317. buffered_sample: Option<f32>,
  318. }
  319.  
  320. impl BStreamStereoDecoder {
  321. fn new(input: BStreamMixer) -> Self {
  322. BStreamStereoDecoder {
  323. input,
  324. left_mic: [-1.0 / 2f32.sqrt(), 1.0 / 2f32.sqrt(), 0.0],
  325. right_mic: [1.0 / 2f32.sqrt(), 1.0 / 2f32.sqrt(), 0.0],
  326. buffered_sample: None,
  327. }
  328. }
  329. }
  330.  
  331. impl Stream for BStreamStereoDecoder {
  332. fn n_channels(&self) -> usize {
  333. 2
  334. }
  335. }
  336.  
  337. impl Iterator for BStreamStereoDecoder {
  338. type Item = f32;
  339.  
  340. fn next(&mut self) -> Option<f32> {
  341. match self.buffered_sample.take() {
  342. Some(s) => Some(s),
  343. None => {
  344. let sample = self.input.next()?;
  345.  
  346. let left = sample.virtual_microphone(self.left_mic, 0.5);
  347. let right = sample.virtual_microphone(self.right_mic, 0.5);
  348.  
  349. // emit left channel now, and right channel on next call
  350. self.buffered_sample = Some(right);
  351. Some(left)
  352. },
  353. }
  354. }
  355. }
  356.  
  357. fn bstream() -> (BStreamMixer, Arc<BStreamController>) {
  358.  
  359. let controller = Arc::new(BStreamController {
  360. pending_streams: Mutex::new(Vec::new()),
  361. has_pending: AtomicBool::new(false),
  362. });
  363.  
  364. let mixer = BStreamMixer {
  365. input: controller.clone(),
  366. active_streams: Vec::with_capacity(8),
  367. };
  368.  
  369. (mixer, controller)
  370. }
  371.  
  372. struct BStreamMixer {
  373. input: Arc<BStreamController>,
  374. active_streams: Vec<SpatialStream>,
  375. }
  376.  
  377. impl Iterator for BStreamMixer {
  378. type Item = BFormat;
  379.  
  380. fn next(&mut self) -> Option<Self::Item> {
  381. if self.input.has_pending.load(Ordering::SeqCst) {
  382. let mut pending = self.input.pending_streams.lock().expect("Cannot lock pending streams");
  383. self.active_streams.extend(pending.drain(..));
  384. self.input.has_pending.store(false, Ordering::SeqCst);
  385. }
  386.  
  387. let mut mix = BFormat::default();
  388.  
  389. let mut done = Vec::new();
  390.  
  391. for (i, stream) in self.active_streams.iter_mut().enumerate() {
  392. match stream.next() {
  393. Some(x) => mix += x,
  394. None => done.push(i),
  395. }
  396. }
  397.  
  398. for i in done {
  399. self.active_streams.remove(i);
  400. }
  401.  
  402. Some(mix)
  403. }
  404. }
  405.  
  406. struct BStreamController {
  407. pending_streams: Mutex<Vec<SpatialStream>>,
  408. has_pending: AtomicBool,
  409. }
  410.  
  411. impl BStreamController {
  412. fn attach<T: 'static + Stream<Item = f32> + Send>(&self, stream: T, direction: [f32; 3]) -> Arc<SpatialStreamController> {
  413. let controller = Arc::new(SpatialStreamController{
  414. direction: Mutex::new(direction),
  415. update: AtomicBool::new(false),
  416. });
  417.  
  418. let sstream = SpatialStream {
  419. inner: Box::new(stream),
  420. bfactors: direction.into(),
  421. controller: controller.clone(),
  422. };
  423.  
  424. self.pending_streams.lock().expect("Cannot lock pending streams").push(sstream);
  425. self.has_pending.store(true, Ordering::SeqCst);
  426.  
  427. controller
  428. }
  429. }
  430.  
  431. struct SpatialStream {
  432. inner: Box<Stream<Item = f32> + Send>,
  433. bfactors: BFormat,
  434.  
  435. controller: Arc<SpatialStreamController>,
  436. }
  437.  
  438. impl Iterator for SpatialStream {
  439. type Item = BFormat;
  440.  
  441. fn next(&mut self) -> Option<Self::Item> {
  442. if self.controller.update.load(Ordering::SeqCst) {
  443. self.bfactors = (*self.controller.direction.lock().unwrap()).into();
  444. self.controller.update.store(false, Ordering::SeqCst);
  445. }
  446.  
  447. let x = self.inner.next()?;
  448. Some(&self.bfactors * x)
  449. }
  450. }
  451.  
  452. struct SpatialStreamController {
  453. direction: Mutex<[f32; 3]>,
  454. update: AtomicBool,
  455. }
  456.  
  457. impl SpatialStreamController {
  458. fn set_direction(&self, d: [f32; 3]) {
  459. *self.direction.lock().unwrap() = d;
  460. self.update.store(true, Ordering::SeqCst);
  461. }
  462. }
  463.  
  464.  
  465. fn stream_player<T>(device: &cpal::Device, format: &cpal::Format, mut stream: T) -> thread::JoinHandle<()>
  466. where
  467. T: Stream + Send + 'static,
  468. T::Item: Sample,
  469. {
  470. let event_loop = cpal::EventLoop::new();
  471. let stream_id = event_loop.build_output_stream(&device, &format).unwrap();
  472. event_loop.play_stream(stream_id);
  473.  
  474. thread::spawn(move || {
  475. event_loop.run(move |_stream_id, stream_data| {
  476. match stream_data {
  477. StreamData::Output { buffer: UnknownTypeOutputBuffer::U16(mut buffer) } => {
  478. for elem in buffer.iter_mut() {
  479. *elem = stream.next().unwrap().as_u16();
  480. }
  481. },
  482. StreamData::Output { buffer: UnknownTypeOutputBuffer::I16(mut buffer) } => {
  483. for elem in buffer.iter_mut() {
  484. *elem = stream.next().unwrap().as_i16();
  485. }
  486. },
  487. StreamData::Output { buffer: UnknownTypeOutputBuffer::F32(mut buffer) } => {
  488. for elem in buffer.iter_mut() {
  489. *elem = stream.next().unwrap().as_f32();
  490. }
  491. },
  492. _ => (),
  493. }
  494. });
  495. })
  496. }
  497.  
  498.  
  499. fn main() {
  500. println!("Hello, world!");
  501.  
  502. let mut reader = hound::WavReader::open(r"U:\Ling\Audio wav files\short\A.wav").unwrap();
  503.  
  504. println!("{:?}", reader.spec());
  505. let sound: Vec<_> = reader
  506. .samples::<i16>()
  507. .map(|s| s.unwrap())
  508. .collect();
  509.  
  510. let sound = Arc::new(sound);
  511.  
  512. let sound = SharedBuffer {
  513. n_channels: 1,
  514. buffer: sound,
  515. index: 0,
  516. };
  517.  
  518. println!("Audio Devices:");
  519. for device in cpal::devices() {
  520. println!(" -> {}", device.name());
  521. }
  522.  
  523. let device = cpal::default_output_device().expect("no output device available");
  524. println!("Default Device:\n {}", device.name());
  525.  
  526. let supported_formats_range = device.supported_output_formats()
  527. .expect("error while querying formats");
  528.  
  529. println!("Supported formats:");
  530. for format in supported_formats_range {
  531. println!("{:?}", format);
  532. }
  533.  
  534. let format = device.supported_output_formats().unwrap().next()
  535. .expect("no supported format?!")
  536. .with_max_sample_rate();
  537.  
  538. let (mixer, controller) = bstream();
  539. let decoder = BStreamStereoDecoder::new(mixer);
  540.  
  541. let player = stream_player(&device, &format, decoder);
  542.  
  543. /*for a in 0..=16 {
  544. let a = a as f32 / 16.0 * 2.0 * f32::consts::PI;
  545. controller.attach(sound.clone().into_iter().floatify(), [a.sin(), a.cos(), 0.0]);
  546. thread::sleep_ms(1000);
  547. }*/
  548.  
  549. //let player = stream_player(&device, &format, sound.into_iter().broadcast(2));
  550.  
  551. //let sc = controller.attach(sound.clone().into_iter().floatify().repeat(), [0.0, 1.0, 0.0]);
  552.  
  553. //controller.attach(sound.clone().floatify(), [-1.0, 0.0, 0.0]);
  554. //thread::sleep_ms(500);
  555.  
  556. let sc = controller.attach(sound.floatify().repeat(), [0.0, 1.0, 0.0]);
  557.  
  558. for a in 0..1000 {
  559. let a = a as f32 / 100.0;
  560. sc.set_direction([a.sin(), a.cos(), 0.0]);
  561. thread::sleep_ms(10);
  562. }
  563.  
  564. //thread::sleep_ms(5000);
  565. //player.join();
  566. }
Add Comment
Please, Sign In to add comment