mod.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. #![allow(non_upper_case_globals)]
  2. use std::{iter, cmp, slice, mem, fmt};
  3. use std::fmt::Debug;
  4. use std::error::Error;
  5. use std::ops::{Index, IndexMut};
  6. use std::collections::HashMap;
  7. use super::*;
  8. use ::byteorder::ByteOrder;
  9. #[derive(PartialEq,Eq,Clone,Copy,Debug)]
  10. pub enum Rate {
  11. Sample,
  12. Control,
  13. }
  14. #[derive(Debug)]
  15. pub struct SampleBuffer {
  16. pub samples: Vec<Sample>,
  17. pub rate: Rate,
  18. }
  19. pub struct Environment {
  20. pub sample_rate: f32,
  21. pub default_buffer_size: usize,
  22. }
  23. impl Default for Environment {
  24. fn default() -> Environment {
  25. Environment {
  26. sample_rate: 44100.0,
  27. default_buffer_size: 64,
  28. }
  29. }
  30. }
  31. pub struct Parameters {
  32. pub env: Environment,
  33. pub vars: HashMap<String, f32>,
  34. }
  35. impl Default for Parameters {
  36. fn default() -> Parameters {
  37. Parameters {
  38. env: Default::default(),
  39. vars: HashMap::new(),
  40. }
  41. }
  42. }
  43. impl SampleBuffer {
  44. pub fn new(sz: usize) -> SampleBuffer {
  45. let mut samples = Vec::with_capacity(sz);
  46. samples.extend(iter::repeat(0 as Sample).take(sz));
  47. SampleBuffer {
  48. samples: samples,
  49. rate: Rate::Sample,
  50. }
  51. }
  52. pub fn len(&self) -> usize {
  53. self.samples.len()
  54. }
  55. pub fn iter_mut<'a>(&'a mut self) -> slice::IterMut<'a, f32> {
  56. self.samples.iter_mut()
  57. }
  58. pub fn first(&self) -> Sample {
  59. *self.samples.first().unwrap()
  60. }
  61. pub fn set(&mut self, val: Sample) {
  62. self.samples[0] = val;
  63. self.rate = Rate::Control;
  64. }
  65. pub fn update_from(&mut self, other: &SampleBuffer) {
  66. self.rate = other.rate;
  67. match self.rate {
  68. Rate::Sample => {
  69. let len = cmp::min(self.len(), other.len());
  70. self.samples[..len].clone_from_slice(&other.samples[..len]);
  71. },
  72. Rate::Control => {
  73. self.samples[0] = other.samples[0];
  74. },
  75. }
  76. }
  77. pub fn sum_into(&mut self, other: &SampleBuffer) {
  78. match self.rate {
  79. Rate::Sample => {
  80. match other.rate {
  81. Rate::Sample => {
  82. for (elt, oelt) in self.samples.iter_mut().zip(other.samples.iter()) {
  83. *elt += *oelt;
  84. }
  85. }
  86. Rate::Control => {
  87. for elt in &mut self.samples {
  88. *elt += other.samples[0];
  89. }
  90. }
  91. };
  92. },
  93. Rate::Control => {
  94. self.samples[0] += other.samples[0];
  95. },
  96. }
  97. }
  98. pub fn mul_into(&mut self, other: &SampleBuffer) {
  99. match self.rate {
  100. Rate::Sample => {
  101. match other.rate {
  102. Rate::Sample => {
  103. for (elt, oelt) in self.samples.iter_mut().zip(other.samples.iter()) {
  104. *elt *= *oelt;
  105. }
  106. }
  107. Rate::Control => {
  108. for elt in &mut self.samples {
  109. *elt *= other.samples[0];
  110. }
  111. }
  112. };
  113. },
  114. Rate::Control => {
  115. self.samples[0] *= other.samples[0];
  116. },
  117. }
  118. }
  119. pub fn zero(&mut self) {
  120. for i in 0..self.len() {
  121. self.samples[i] = 0.0;
  122. }
  123. }
  124. pub fn size(&self) -> usize {
  125. mem::size_of::<Sample>() * self.samples.len()
  126. }
  127. pub fn bytes(&self, buf: &mut [u8]) {
  128. // FIXME: Depends on f32 instead of Sample alias
  129. ::byteorder::LittleEndian::write_f32_into(&self.samples, buf);
  130. }
  131. }
  132. impl Index<usize> for SampleBuffer {
  133. type Output = Sample;
  134. fn index(&self, idx: usize) -> &Sample { &self.samples[idx] }
  135. }
  136. impl IndexMut<usize> for SampleBuffer {
  137. fn index_mut(&mut self, idx: usize) -> &mut Sample { &mut self.samples[idx] }
  138. }
  139. pub trait Generator : Debug {
  140. fn eval<'a>(&'a mut self, params: &Parameters) -> &'a SampleBuffer;
  141. fn buffer<'a>(&'a self) -> &'a SampleBuffer;
  142. fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer;
  143. }
  144. pub type GenBox = Box<Generator>;
  145. #[derive(Debug)]
  146. pub enum GenFactoryError {
  147. MissingRequiredParam(String, usize),
  148. CannotConvert(ParamKind, ParamKind),
  149. BadType(ParamKind),
  150. }
  151. #[derive(Debug)]
  152. pub struct GenFactoryErrorType {
  153. pub kind: GenFactoryError,
  154. desc: String
  155. }
  156. impl GenFactoryErrorType {
  157. pub fn new(kind: GenFactoryError) -> GenFactoryErrorType {
  158. let mut ret = GenFactoryErrorType {
  159. kind: kind,
  160. desc: "".to_string(),
  161. };
  162. ret.desc = match &ret.kind {
  163. &GenFactoryError::MissingRequiredParam(ref name, pos) => format!("Needed a parameter named {} or at pos {}", name, pos),
  164. &GenFactoryError::CannotConvert(from, to) => format!("Cannot convert {:?} to {:?}", from, to),
  165. &GenFactoryError::BadType(ty) => format!("Bad parameter type {:?}", ty),
  166. };
  167. ret
  168. }
  169. pub fn with_description(kind: GenFactoryError, desc: String) -> GenFactoryErrorType {
  170. GenFactoryErrorType {
  171. kind: kind,
  172. desc: desc,
  173. }
  174. }
  175. }
  176. impl From<GenFactoryError> for GenFactoryErrorType {
  177. fn from(e: GenFactoryError) -> GenFactoryErrorType {
  178. GenFactoryErrorType::new(e)
  179. }
  180. }
  181. impl Error for GenFactoryErrorType {
  182. fn description<'a>(&'a self) -> &'a str {
  183. &self.desc
  184. }
  185. }
  186. impl fmt::Display for GenFactoryErrorType {
  187. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  188. write!(f, "{}", self.description())
  189. }
  190. }
  191. impl Into<Box<Error>> for GenFactoryError {
  192. fn into(self) -> Box<Error> {
  193. Box::new(GenFactoryErrorType::new(self))
  194. }
  195. }
  196. #[derive(Debug,PartialEq,Eq,Clone,Copy)]
  197. pub enum ParamKind {
  198. Integer,
  199. Float,
  200. String,
  201. Generator,
  202. }
  203. pub enum ParamValue {
  204. Integer(isize),
  205. Float(f32),
  206. String(String),
  207. Generator(GenBox),
  208. }
  209. impl ParamValue {
  210. pub fn kind(&self) -> ParamKind {
  211. match *self {
  212. ParamValue::Integer(_) => ParamKind::Integer,
  213. ParamValue::Float(_) => ParamKind::Float,
  214. ParamValue::String(_) => ParamKind::String,
  215. ParamValue::Generator(_) => ParamKind::Generator,
  216. }
  217. }
  218. pub fn as_isize(&self) -> Result<isize, GenFactoryError> {
  219. match *self {
  220. ParamValue::Integer(v) => Ok(v),
  221. ParamValue::Float(v) => Ok(v as isize),
  222. ParamValue::String(ref v) => v.parse().map_err(|_| GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Integer)),
  223. ParamValue::Generator(_) => Err(GenFactoryError::CannotConvert(ParamKind::Generator, ParamKind::Integer)),
  224. }
  225. }
  226. pub fn as_f32(&self) -> Result<f32, GenFactoryError> {
  227. match *self {
  228. ParamValue::Integer(v) => Ok(v as f32),
  229. ParamValue::Float(v) => Ok(v),
  230. ParamValue::String(ref v) => v.parse().map_err(|_| GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Float)),
  231. ParamValue::Generator(_) => Err(GenFactoryError::CannotConvert(ParamKind::Generator, ParamKind::Float)),
  232. }
  233. }
  234. pub fn as_string(&self) -> Result<String, GenFactoryError> {
  235. match *self {
  236. ParamValue::Integer(v) => Ok(v.to_string()),
  237. ParamValue::Float(v) => Ok(v.to_string()),
  238. ParamValue::String(ref v) => Ok(v.clone()),
  239. ParamValue::Generator(_) => Err(GenFactoryError::CannotConvert(ParamKind::Generator, ParamKind::String)),
  240. }
  241. }
  242. pub fn as_gen(self) -> Result<GenBox, GenFactoryError> {
  243. match self {
  244. ParamValue::Integer(v) => Ok(Box::new(self::param::Param { name : "_".to_string(), default: v as f32, buf: SampleBuffer::new(1) })),
  245. ParamValue::Float(v) => Ok(Box::new(self::param::Param { name : "_".to_string(), default: v, buf: SampleBuffer::new(1) })),
  246. ParamValue::String(_) => Err(GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Generator)),
  247. ParamValue::Generator(g) => Ok(g),
  248. }
  249. }
  250. }
  251. impl<'a> From<&'a ParamValue> for ParamKind {
  252. fn from(val: &'a ParamValue) -> ParamKind {
  253. val.kind()
  254. }
  255. }
  256. #[derive(Default)]
  257. pub struct FactoryParameters {
  258. pub env: Environment,
  259. pub vars: HashMap<String, ParamValue>,
  260. }
  261. impl FactoryParameters {
  262. pub fn get_param<'a, 'b : 'a>(&'a self, name: &str, position: usize, default: &'b ParamValue) -> &'a ParamValue {
  263. (
  264. self.vars.get(name).or_else(||
  265. self.vars.get(&position.to_string()).or(Some(default))
  266. )
  267. ).unwrap()
  268. }
  269. pub fn get_req_param(&self, name: &str, position: usize) -> Result<&ParamValue, GenFactoryError> {
  270. match self.vars.get(name).or_else(|| self.vars.get(&position.to_string())) {
  271. Some(v) => Ok(v),
  272. None => Err(GenFactoryError::MissingRequiredParam(name.to_string(), position)),
  273. }
  274. }
  275. pub fn remove_param(&mut self, name: &str, position: usize) -> Result<ParamValue, GenFactoryError> {
  276. match self.vars.remove(name).or_else(|| self.vars.remove(&position.to_string())) {
  277. Some(v) => Ok(v),
  278. None => Err(GenFactoryError::MissingRequiredParam(name.to_string(), position)),
  279. }
  280. }
  281. pub fn get_pos_params(&mut self) -> Vec<ParamValue> {
  282. let mut ret = Vec::new();
  283. for i in 0.. {
  284. match self.vars.remove(&i.to_string()) {
  285. Some(v) => ret.push(v),
  286. None => return ret,
  287. }
  288. }
  289. unreachable!()
  290. }
  291. }
  292. pub trait GeneratorFactory {
  293. // NB: Like above, &self is for object safety. This should have an associated type, but that
  294. // would compromise object safety; for the same reason, the return of this may only be a
  295. // Box<Generator>, which necessitates allocation.
  296. fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError>;
  297. }
  298. pub mod param;
  299. pub use self::param::Param;
  300. pub mod math;
  301. pub use self::math::{Add, Mul, Negate, Reciprocate};
  302. pub mod rel;
  303. pub use self::rel::{Rel, RelOp};
  304. pub mod logic;
  305. pub use self::logic::IfElse;
  306. pub mod sine;
  307. pub use self::sine::Sine;
  308. pub mod saw;
  309. pub use self::saw::Saw;
  310. pub mod triangle;
  311. pub use self::triangle::Triangle;
  312. pub mod square;
  313. pub use self::square::Square;
  314. pub mod noise;
  315. pub use self::noise::Noise;
  316. //pub mod adsr;
  317. //pub use self::adsr::ADSR;
  318. pub fn all_factories() -> HashMap<String, &'static GeneratorFactory> {
  319. let mut ret = HashMap::new();
  320. ret.insert("param".to_string(), &self::param::Factory as &GeneratorFactory);
  321. ret.insert("add".to_string(), &self::math::FactoryAdd as &GeneratorFactory);
  322. ret.insert("mul".to_string(), &self::math::FactoryMul as &GeneratorFactory);
  323. ret.insert("negate".to_string(), &self::math::FactoryNegate as &GeneratorFactory);
  324. ret.insert("reciprocate".to_string(), &self::math::FactoryReciprocate as &GeneratorFactory);
  325. ret.insert("rel".to_string(), &self::rel::Factory as &GeneratorFactory);
  326. ret.insert("ifelse".to_string(), &self::logic::Factory as &GeneratorFactory);
  327. ret.insert("sine".to_string(), &self::sine::Factory as &GeneratorFactory);
  328. ret.insert("saw".to_string(), &self::saw::Factory as &GeneratorFactory);
  329. ret.insert("triangle".to_string(), &self::triangle::Factory as &GeneratorFactory);
  330. ret.insert("square".to_string(), &self::square::Factory as &GeneratorFactory);
  331. ret.insert("noise".to_string(), &self::noise::Factory as &GeneratorFactory);
  332. ret
  333. }