mod.rs 11 KB

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