diff options
| author | thajohns <thajohns@clarkson.edu> | 2021-09-09 01:15:22 -0400 | 
|---|---|---|
| committer | Graham Northup <grahamnorthup@yahoo.com> | 2021-09-10 04:05:55 -0400 | 
| commit | d6e399973e9bc6447a28b80cacffcbc6a768f1ed (patch) | |
| tree | 772939eb5d49bdb6ee8e5d632f2224867f6e817d | |
| parent | ee11b17c0e2796bd3d843a8a516c12453af75927 (diff) | |
got pre-linking steps working, removed glob includes
| -rw-r--r-- | Cargo.toml | 1 | ||||
| -rw-r--r-- | src/client.rs | 84 | ||||
| -rw-r--r-- | src/graphics/draw/mod.rs | 2 | ||||
| -rw-r--r-- | src/graphics/mod.rs | 3 | ||||
| -rw-r--r-- | src/lang/mod.rs | 4 | ||||
| -rw-r--r-- | src/lang/parser.rs | 284 | ||||
| -rw-r--r-- | src/lang/tokenizer.rs | 154 | ||||
| -rw-r--r-- | src/lib.rs | 9 | ||||
| -rw-r--r-- | src/main.rs | 103 | ||||
| -rw-r--r-- | src/monitor.rs | 4 | ||||
| -rw-r--r-- | src/proto.rs | 62 | ||||
| -rw-r--r-- | src/seq/file/iv.rs | 1 | ||||
| -rw-r--r-- | src/seq/file/mod.rs | 1 | ||||
| -rw-r--r-- | src/seq/sequencer.rs | 2 | ||||
| -rw-r--r-- | src/synth/adsr.rs | 25 | ||||
| -rw-r--r-- | src/synth/logic.rs | 50 | ||||
| -rw-r--r-- | src/synth/lut.rs | 34 | ||||
| -rw-r--r-- | src/synth/math.rs | 41 | ||||
| -rw-r--r-- | src/synth/mod.rs | 213 | ||||
| -rw-r--r-- | src/synth/noise.rs | 11 | ||||
| -rw-r--r-- | src/synth/param.rs | 16 | ||||
| -rw-r--r-- | src/synth/rel.rs | 39 | ||||
| -rw-r--r-- | src/synth/saw.rs | 13 | ||||
| -rw-r--r-- | src/synth/sine.rs | 13 | ||||
| -rw-r--r-- | src/synth/square.rs | 13 | ||||
| -rw-r--r-- | src/synth/triangle.rs | 13 | ||||
| -rw-r--r-- | src/synth/util.rs | 32 | ||||
| -rw-r--r-- | src/types.rs | 14 | 
28 files changed, 851 insertions, 390 deletions
| @@ -1,5 +1,6 @@  [package]  name = "synfone" +edition = "2018"  version = "0.1.0"  authors = ["Graham Northup <grissess@nexusg.org>"] diff --git a/src/client.rs b/src/client.rs index 5cf941a..bf661d0 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,8 +1,8 @@ -use std::net::{UdpSocket, SocketAddr}; -use std::{io, mem, iter}; +use std::io; +use std::net::{SocketAddr, UdpSocket}; -use synth::*; -use proto::*; +use crate::proto::Command; +use crate::synth::{Environment, GenBox, Parameters, SampleBuffer};  pub struct Voice {      pub gen: GenBox, @@ -15,7 +15,7 @@ pub struct Client {      pub env: Environment,      pub frames: usize,      pub buf: SampleBuffer, -    norm: SampleBuffer +    norm: SampleBuffer,  }  macro_rules! dprintln { @@ -25,7 +25,16 @@ macro_rules! dprintln {  impl Client {      pub fn new(socket: UdpSocket, gens: Vec<GenBox>, env: Environment) -> io::Result<Client> {          let buf = SampleBuffer::new(env.default_buffer_size); -        let voices = gens.into_iter().map(|g| Voice { gen: g, params: Parameters { env: env.clone(), ..Default::default() } }).collect(); +        let voices = gens +            .into_iter() +            .map(|g| Voice { +                gen: g, +                params: Parameters { +                    env: env.clone(), +                    ..Default::default() +                }, +            }) +            .collect();          Ok(Client {              socket: socket,              voices: voices, @@ -74,33 +83,54 @@ impl Client {      pub fn handle_command(&mut self, cmd: Command, sender: SocketAddr) -> bool {          dprintln!("Packet {:?} from {:?}", cmd, sender);          match cmd { -            Command::KeepAlive => {}, -            Command::Ping{..} => { +            Command::KeepAlive => {} +            Command::Ping { .. } => {                  let mut reply_buffer: [u8; Command::SIZE] = [0u8; Command::SIZE];                  cmd.write_into(&mut reply_buffer);                  self.socket.send_to(&reply_buffer, sender); -            }, +            }              Command::Quit => {                  return false; -            }, -            Command::Play{voice, freq, amp, ..} => { +            } +            Command::Play { +                voice, freq, amp, .. +            } => {                  if (voice as usize) >= self.voices.len() { -                    dprintln!("Dropping packet: tried to send to voice {} >= number of voices {}", voice, self.voices.len()); +                    dprintln!( +                        "Dropping packet: tried to send to voice {} >= number of voices {}", +                        voice, +                        self.voices.len() +                    );                      return true;                  }                  let dur = cmd.duration().unwrap();                  let frac_secs = (dur.as_secs() as f32) + (dur.subsec_nanos() as f32) / 1.0e9;                  let frames = frac_secs * (self.env.sample_rate as f32); -                dprintln!("Playing on voice {} freq {} amp {} from frame {} until frame {}", voice, freq, amp, self.frames, (self.frames as f32) + frames); - -                let mut vars = &mut self.voices[voice as usize].params.vars; -                *vars.entry("v_start".to_string()).or_insert_with(Default::default) = (self.frames as f32); -                *vars.entry("v_deadline".to_string()).or_insert_with(Default::default) = (self.frames as f32) + frames; -                *vars.entry("v_freq".to_string()).or_insert_with(Default::default) = freq as f32; -                *vars.entry("v_amp".to_string()).or_insert_with(Default::default) = amp; -            }, -            Command::Caps{..} => { +                dprintln!( +                    "Playing on voice {} freq {} amp {} from frame {} until frame {}", +                    voice, +                    freq, +                    amp, +                    self.frames, +                    (self.frames as f32) + frames +                ); + +                let vars = &mut self.voices[voice as usize].params.vars; +                *vars +                    .entry("v_start".to_string()) +                    .or_insert_with(Default::default) = self.frames as f32; +                *vars +                    .entry("v_deadline".to_string()) +                    .or_insert_with(Default::default) = self.frames as f32 + frames; +                *vars +                    .entry("v_freq".to_string()) +                    .or_insert_with(Default::default) = freq as f32; +                *vars +                    .entry("v_amp".to_string()) +                    .or_insert_with(Default::default) = amp; +            } +            Command::Caps { .. } => {                  let reply = Command::Caps {                      voices: self.voices.len() as u32,                      tp: ['S' as u8, 'Y' as u8, 'N' as u8, 'F' as u8], @@ -123,7 +153,7 @@ impl Client {              },              Command::Unknown{data} => {                  dprintln!("Dropping packet: unknown data {:?}", (&data as &[u8])); -            }, +            }          }          true @@ -133,7 +163,11 @@ impl Client {          let len = self.voices.len();          for voice in self.voices.iter_mut() { -            *voice.params.vars.entry("v_frame".to_string()).or_insert_with(Default::default) = self.frames as f32; +            *voice +                .params +                .vars +                .entry("v_frame".to_string()) +                .or_insert_with(Default::default) = self.frames as f32;          }          let (first, next) = self.voices.split_at_mut(1); @@ -155,7 +189,9 @@ impl Client {      pub fn write_frames_bytes(&self, out_buffer: &mut Vec<u8>) {          let current = out_buffer.len();          out_buffer.reserve_exact(self.buf.size() - current); -        unsafe { out_buffer.set_len(self.buf.size()); } +        unsafe { +            out_buffer.set_len(self.buf.size()); +        }          self.buf.write_bytes(out_buffer);      }  } diff --git a/src/graphics/draw/mod.rs b/src/graphics/draw/mod.rs index 75ce9f7..8f414f5 100644 --- a/src/graphics/draw/mod.rs +++ b/src/graphics/draw/mod.rs @@ -1,3 +1 @@ -use super::*; -  /* TODO */ diff --git a/src/graphics/mod.rs b/src/graphics/mod.rs index 4bb4388..365bf6b 100644 --- a/src/graphics/mod.rs +++ b/src/graphics/mod.rs @@ -1,4 +1 @@ -use super::*; -use monitor::*; -  pub mod draw; diff --git a/src/lang/mod.rs b/src/lang/mod.rs index 14a9202..7a62cd1 100644 --- a/src/lang/mod.rs +++ b/src/lang/mod.rs @@ -4,7 +4,7 @@ pub mod parser;  pub use self::parser::Parser;  // NB: No Eq due to embedded f32 -#[derive(Debug,PartialEq,Clone)] +#[derive(Debug, PartialEq, Clone)]  pub enum Token {      Ident(String),      Integer(isize), @@ -14,7 +14,7 @@ pub enum Token {      EOF,  } -#[derive(Debug,PartialEq,Eq,Clone,Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)]  pub enum TokType {      Ident,      Integer, diff --git a/src/lang/parser.rs b/src/lang/parser.rs index ec8ef40..ac7eccd 100644 --- a/src/lang/parser.rs +++ b/src/lang/parser.rs @@ -1,8 +1,11 @@ -use std::{mem, fmt}; -use std::error::Error; +use super::{TokType, Token, Tokenizer}; +use crate::synth::{ +    all_factories, Environment, FactoryParameters, GenBox, GenFactoryErrorType, GeneratorFactory, +    ParamValue, RelOp, +};  use std::collections::HashMap; -use super::*; -use synth::*; +use std::error::Error; +use std::{fmt, mem};  /*  macro_rules! dprintln { @@ -36,8 +39,12 @@ impl ErrorType {          };          ret.desc = match ret.kind { -            ErrorKind::Unexpected(found, expected) => format!("Found {:?}, expected {:?}", found, expected), -            ErrorKind::Unparseable(found, ref term) => format!("Cannot consume {:?} token in {}", found, term), +            ErrorKind::Unexpected(found, expected) => { +                format!("Found {:?}, expected {:?}", found, expected) +            } +            ErrorKind::Unparseable(found, ref term) => { +                format!("Cannot consume {:?} token in {}", found, term) +            }              ErrorKind::ExpectedOp(c, found) => format!("Expected {:?}, found {:?}", c, found),              ErrorKind::UnknownGen(ref s) => format!("Unknown generator name {}", s),          }; @@ -61,20 +68,20 @@ impl Error for ErrorType {  impl fmt::Display for ErrorType {      fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { -        write!(f, "{}", self.description()) +        write!(f, "{}", self.to_string())      }  } -pub struct Parser<T: Iterator<Item=char>> { +pub struct Parser<T: Iterator<Item = char>> {      tzr: Tokenizer<T>,      env: Environment,      token: Token,      pushback: Option<Token>, -    factories: HashMap<String, &'static GeneratorFactory>, +    factories: HashMap<String, &'static dyn GeneratorFactory>,  } -impl<T: Iterator<Item=char>> Parser<T> { -    pub fn new(mut tzr: Tokenizer<T>, env: Environment) -> Result<Parser<T>, Box<Error>> { +impl<T: Iterator<Item = char>> Parser<T> { +    pub fn new(mut tzr: Tokenizer<T>, env: Environment) -> Result<Parser<T>, Box<dyn Error>> {          let token = tzr.next_token()?;          Ok(Parser {              tzr: tzr, @@ -89,7 +96,7 @@ impl<T: Iterator<Item=char>> Parser<T> {          match self.pushback {              None => {                  self.pushback = Some(tok); -            }, +            }              Some(_) => panic!("too many pushbacks on Parser"),          }      } @@ -101,7 +108,7 @@ impl<T: Iterator<Item=char>> Parser<T> {          }      } -    pub fn expect(&mut self, ty: TokType) -> Result<Token, Box<Error>> { +    pub fn expect(&mut self, ty: TokType) -> Result<Token, Box<dyn Error>> {          if ty != self.cur_token().to_type() {              Err(ErrorType::new(ErrorKind::Unexpected(self.token.to_type(), ty)).into())          } else { @@ -112,18 +119,23 @@ impl<T: Iterator<Item=char>> Parser<T> {          }      } -    pub fn expect_ident(&mut self) -> Result<String, Box<Error>> { +    pub fn expect_ident(&mut self) -> Result<String, Box<dyn Error>> {          match self.expect(TokType::Ident)? {              Token::Ident(s) => Ok(s),              _ => unreachable!(),          }      } -    pub fn expect_op(&mut self, oper: char) -> Result<(), Box<Error>> { +    pub fn expect_op(&mut self, oper: char) -> Result<(), Box<dyn Error>> {          dprintln!("expect_op: {:?} ({})", self.cur_token(), oper);          match *self.cur_token() { -            Token::Oper(c) if c == oper => { self.expect(TokType::Oper)?; Ok(()) }, -            _ => Err(ErrorType::new(ErrorKind::ExpectedOp(oper, self.cur_token().to_type())).into()), +            Token::Oper(c) if c == oper => { +                self.expect(TokType::Oper)?; +                Ok(()) +            } +            _ => { +                Err(ErrorType::new(ErrorKind::ExpectedOp(oper, self.cur_token().to_type())).into()) +            }          }      } @@ -131,15 +143,14 @@ impl<T: Iterator<Item=char>> Parser<T> {          dprintln!("peek_op: {:?} ({})", self.cur_token(), oper);          match *self.cur_token() {              Token::Oper(c) if c == oper => true, -            _ => false +            _ => false,          }      } -    pub fn parse_gen_vec(&mut self) -> Result<Vec<GenBox>, Box<Error>> { +    pub fn parse_gen_vec(&mut self) -> Result<Vec<GenBox>, Box<dyn Error>> {          let mut ret: Vec<GenBox> = Vec::new();          self.expect_op('[')?; -          loop {              if self.expect_op(']').is_ok() {                  break; @@ -156,37 +167,70 @@ impl<T: Iterator<Item=char>> Parser<T> {          Ok(ret)      } -    pub fn parse_gen_rel(&mut self) -> Result<GenBox, Box<Error>> { +    pub fn parse_gen_rel(&mut self) -> Result<GenBox, Box<dyn Error>> {          let left = self.parse_gen_terms()?;          match *self.cur_token() {              Token::Oper(c) => { -                if c == '>' || c == '!' || c == '<' || c == '=' { // TODO: Conflict with param name +                if c == '>' || c == '!' || c == '<' || c == '=' { +                    // TODO: Conflict with param name                      self.expect(TokType::Oper)?;                      let relop = match (c, self.cur_token()) { -                        ('<', &Token::Oper('=')) => { self.expect(TokType::Oper)?; RelOp::LessEqual }, -                        ('=', &Token::Oper('=')) => { self.expect(TokType::Oper)?; RelOp::Equal }, -                        ('>', &Token::Oper('=')) => { self.expect(TokType::Oper)?; RelOp::Greater }, -                        ('!', &Token::Oper('=')) => { self.expect(TokType::Oper)?; RelOp::NotEqual }, +                        ('<', &Token::Oper('=')) => { +                            self.expect(TokType::Oper)?; +                            RelOp::LessEqual +                        } +                        ('=', &Token::Oper('=')) => { +                            self.expect(TokType::Oper)?; +                            RelOp::Equal +                        } +                        ('>', &Token::Oper('=')) => { +                            self.expect(TokType::Oper)?; +                            RelOp::Greater +                        } +                        ('!', &Token::Oper('=')) => { +                            self.expect(TokType::Oper)?; +                            RelOp::NotEqual +                        }                          ('<', _) => RelOp::Less,                          ('>', _) => RelOp::Greater, -                        _ => return Err(ErrorType::new(ErrorKind::Unparseable(TokType::Oper, "rel expr".to_string())).into()), +                        _ => { +                            return Err(ErrorType::new(ErrorKind::Unparseable( +                                TokType::Oper, +                                "rel expr".to_string(), +                            )) +                            .into()) +                        } +                    }; +                    let mut params = FactoryParameters { +                        env: self.env.clone(), +                        ..Default::default()                      }; -                    let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; -                    params.vars.insert("0".to_string(), ParamValue::Generator(left)); -                    params.vars.insert("1".to_string(), ParamValue::String(relop.to_param_string().to_string())); -                    params.vars.insert("2".to_string(), ParamValue::Generator(self.parse_gen_rel()?)); -                    let factory = self.factories.get("rel").ok_or(ErrorType::new(ErrorKind::UnknownGen("rel".to_string())))?; +                    params +                        .vars +                        .insert("0".to_string(), ParamValue::Generator(left)); +                    params.vars.insert( +                        "1".to_string(), +                        ParamValue::String(relop.to_param_string().to_string()), +                    ); +                    params.vars.insert( +                        "2".to_string(), +                        ParamValue::Generator(self.parse_gen_rel()?), +                    ); +                    let factory = self +                        .factories +                        .get("rel") +                        .ok_or(ErrorType::new(ErrorKind::UnknownGen("rel".to_string())))?;                      factory.new(&mut params).map_err(Into::into)                  } else {                      Ok(left)                  } -            }, +            }              _ => Ok(left),          }      } -    pub fn parse_gen_terms(&mut self) -> Result<GenBox, Box<Error>> { +    pub fn parse_gen_terms(&mut self) -> Result<GenBox, Box<dyn Error>> {          let mut gens: Vec<GenBox> = Vec::new();          gens.push(self.parse_gen_factors()?); @@ -195,14 +239,27 @@ impl<T: Iterator<Item=char>> Parser<T> {                  Token::Oper('+') => {                      self.expect_op('+')?;                      gens.push(self.parse_gen_factors()?); -                }, +                }                  Token::Oper('-') => {                      self.expect_op('-')?; -                    let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; -                    params.vars.insert("0".to_string(), ParamValue::Generator(self.parse_gen_factors()?)); -                    let factory = self.factories.get("negate").ok_or(ErrorType::new(ErrorKind::UnknownGen("negate".to_string())))?; -                    gens.push(factory.new(&mut params).map_err(GenFactoryErrorType::from)?); -                }, +                    let mut params = FactoryParameters { +                        env: self.env.clone(), +                        ..Default::default() +                    }; +                    params.vars.insert( +                        "0".to_string(), +                        ParamValue::Generator(self.parse_gen_factors()?), +                    ); +                    let factory = self +                        .factories +                        .get("negate") +                        .ok_or(ErrorType::new(ErrorKind::UnknownGen("negate".to_string())))?; +                    gens.push( +                        factory +                            .new(&mut params) +                            .map_err(GenFactoryErrorType::from)?, +                    ); +                }                  _ => break,              }          } @@ -211,15 +268,23 @@ impl<T: Iterator<Item=char>> Parser<T> {              return Ok(gens.pop().unwrap());          } -        let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; +        let mut params = FactoryParameters { +            env: self.env.clone(), +            ..Default::default() +        };          for (idx, gen) in gens.into_iter().enumerate() { -            params.vars.insert(idx.to_string(), ParamValue::Generator(gen)); +            params +                .vars +                .insert(idx.to_string(), ParamValue::Generator(gen));          } -        let factory = self.factories.get("add").ok_or(ErrorType::new(ErrorKind::UnknownGen("add".to_string())))?; +        let factory = self +            .factories +            .get("add") +            .ok_or(ErrorType::new(ErrorKind::UnknownGen("add".to_string())))?;          factory.new(&mut params).map_err(Into::into)      } -    pub fn parse_gen_factors(&mut self) -> Result<GenBox, Box<Error>> { +    pub fn parse_gen_factors(&mut self) -> Result<GenBox, Box<dyn Error>> {          let mut gens: Vec<GenBox> = Vec::new();          gens.push(self.parse_gen()?); @@ -228,14 +293,25 @@ impl<T: Iterator<Item=char>> Parser<T> {                  Token::Oper('*') => {                      self.expect_op('*')?;                      gens.push(self.parse_gen()?); -                }, +                }                  Token::Oper('/') => {                      self.expect_op('/')?; -                    let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; -                    params.vars.insert("0".to_string(), ParamValue::Generator(self.parse_gen()?)); -                    let factory = self.factories.get("reciprocate").ok_or(ErrorType::new(ErrorKind::UnknownGen("reciprocate".to_string())))?; -                    gens.push(factory.new(&mut params).map_err(GenFactoryErrorType::from)?); -                }, +                    let mut params = FactoryParameters { +                        env: self.env.clone(), +                        ..Default::default() +                    }; +                    params +                        .vars +                        .insert("0".to_string(), ParamValue::Generator(self.parse_gen()?)); +                    let factory = self.factories.get("reciprocate").ok_or(ErrorType::new( +                        ErrorKind::UnknownGen("reciprocate".to_string()), +                    ))?; +                    gens.push( +                        factory +                            .new(&mut params) +                            .map_err(GenFactoryErrorType::from)?, +                    ); +                }                  _ => break,              }          } @@ -244,32 +320,56 @@ impl<T: Iterator<Item=char>> Parser<T> {              return Ok(gens.pop().unwrap());          } -        let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; +        let mut params = FactoryParameters { +            env: self.env.clone(), +            ..Default::default() +        };          for (idx, gen) in gens.into_iter().enumerate() { -            params.vars.insert(idx.to_string(), ParamValue::Generator(gen)); +            params +                .vars +                .insert(idx.to_string(), ParamValue::Generator(gen));          } -        let factory = self.factories.get("mul").ok_or(ErrorType::new(ErrorKind::UnknownGen("mul".to_string())))?; +        let factory = self +            .factories +            .get("mul") +            .ok_or(ErrorType::new(ErrorKind::UnknownGen("mul".to_string())))?;          factory.new(&mut params).map_err(Into::into)      } -    pub fn parse_gen(&mut self) -> Result<GenBox, Box<Error>> { +    pub fn parse_gen(&mut self) -> Result<GenBox, Box<dyn Error>> {          match *self.cur_token() {              Token::Integer(v) => {                  self.expect(TokType::Integer)?; -                let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; -                params.vars.insert("0".to_string(), ParamValue::String("_".to_string())); +                let mut params = FactoryParameters { +                    env: self.env.clone(), +                    ..Default::default() +                }; +                params +                    .vars +                    .insert("0".to_string(), ParamValue::String("_".to_string()));                  params.vars.insert("1".to_string(), ParamValue::Integer(v)); -                let factory = self.factories.get("param").ok_or(ErrorType::new(ErrorKind::UnknownGen("param".to_string())))?; +                let factory = self +                    .factories +                    .get("param") +                    .ok_or(ErrorType::new(ErrorKind::UnknownGen("param".to_string())))?;                  factory.new(&mut params).map_err(Into::into) -            }, +            }              Token::Float(v) => {                  self.expect(TokType::Float)?; -                let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; -                params.vars.insert("0".to_string(), ParamValue::String("_".to_string())); +                let mut params = FactoryParameters { +                    env: self.env.clone(), +                    ..Default::default() +                }; +                params +                    .vars +                    .insert("0".to_string(), ParamValue::String("_".to_string()));                  params.vars.insert("1".to_string(), ParamValue::Float(v)); -                let factory = self.factories.get("param").ok_or(ErrorType::new(ErrorKind::UnknownGen("param".to_string())))?; +                let factory = self +                    .factories +                    .get("param") +                    .ok_or(ErrorType::new(ErrorKind::UnknownGen("param".to_string())))?;                  factory.new(&mut params).map_err(Into::into) -            }, +            }              Token::Ident(_) => {                  let name = self.expect_ident()?;                  if self.peek_op('(') { @@ -280,12 +380,20 @@ impl<T: Iterator<Item=char>> Parser<T> {                      };                      factory.new(&mut params).map_err(Into::into)                  } else { -                    let mut params = FactoryParameters { env: self.env.clone(), ..Default::default() }; -                    params.vars.insert("0".to_string(), ParamValue::String(name)); -                    let factory = self.factories.get("param").ok_or(ErrorType::new(ErrorKind::UnknownGen("param".to_string())))?; +                    let mut params = FactoryParameters { +                        env: self.env.clone(), +                        ..Default::default() +                    }; +                    params +                        .vars +                        .insert("0".to_string(), ParamValue::String(name)); +                    let factory = self +                        .factories +                        .get("param") +                        .ok_or(ErrorType::new(ErrorKind::UnknownGen("param".to_string())))?;                      factory.new(&mut params).map_err(Into::into)                  } -            }, +            }              Token::Oper('(') => {                  dprintln!("consuming paren in parse_gen");                  self.expect(TokType::Oper)?; @@ -293,16 +401,23 @@ impl<T: Iterator<Item=char>> Parser<T> {                  dprintln!("parenthesized generator is concluding");                  self.expect_op(')')?;                  Ok(ret) -            }, -            _ => Err(ErrorType::new(ErrorKind::Unparseable(self.cur_token().to_type(), "gen".to_string())).into()), +            } +            _ => Err(ErrorType::new(ErrorKind::Unparseable( +                self.cur_token().to_type(), +                "gen".to_string(), +            )) +            .into()),          }      } -    pub fn parse_factory_params(&mut self) -> Result<FactoryParameters, Box<Error>> { +    pub fn parse_factory_params(&mut self) -> Result<FactoryParameters, Box<dyn Error>> {          dprintln!("consuming paren in factory_params");          self.expect_op('(')?; -        let mut params: FactoryParameters = FactoryParameters { env: self.env.clone(), ..Default::default() }; +        let mut params: FactoryParameters = FactoryParameters { +            env: self.env.clone(), +            ..Default::default() +        };          let mut ctr = 0;          loop {              if self.expect_op(')').is_ok() { @@ -313,7 +428,7 @@ impl<T: Iterator<Item=char>> Parser<T> {              ctr = new_ctr;              dprintln!("before factory_params comma, tok is {:?}", self.cur_token()); -            if self.expect_op(',').map_err(|e| dprintln!("factory_params consume comma failed: {:?}", e)).is_err() { +            if self.expect_op(',').map_err(|_e| dprintln!("factory_params consume comma failed: {:?}", e)).is_err() {                  dprintln!("factory_params is concluding");                  self.expect_op(')')?;                  break; @@ -323,7 +438,10 @@ impl<T: Iterator<Item=char>> Parser<T> {          Ok(params)      } -    pub fn parse_param(&mut self, pos: usize) -> Result<(String, ParamValue, usize), Box<Error>> { +    pub fn parse_param( +        &mut self, +        pos: usize, +    ) -> Result<(String, ParamValue, usize), Box<dyn Error>> {          let mut ctr = pos;          let name = match self.expect_ident() {              Ok(nm) => { @@ -334,19 +452,29 @@ impl<T: Iterator<Item=char>> Parser<T> {                      ctr += 1;                      (ctr - 1).to_string()                  } -            }, +            }              Err(_) => {                  ctr += 1;                  (ctr - 1).to_string() -            }, +            }          };          dprintln!("about to consume param value, token is {:?}", self.cur_token()); -        match self.cur_token().clone() {  // FIXME: Does this really need to be cloned? -            Token::String(ref v) => { self.expect(TokType::String)?; Ok((name, ParamValue::String(v.clone()), ctr)) }, -            Token::Integer(_) | Token::Float(_) | Token::Ident(_) | Token::Oper('(') => Ok((name, ParamValue::Generator(self.parse_gen_rel()?), ctr)), -            _ => Err(ErrorType::new(ErrorKind::Unparseable(self.cur_token().to_type(), "param value".to_string())).into()), +        match self.cur_token().clone() { +            // FIXME: Does this really need to be cloned? +            Token::String(ref v) => { +                self.expect(TokType::String)?; +                Ok((name, ParamValue::String(v.clone()), ctr)) +            } +            Token::Integer(_) | Token::Float(_) | Token::Ident(_) | Token::Oper('(') => { +                Ok((name, ParamValue::Generator(self.parse_gen_rel()?), ctr)) +            } +            _ => Err(ErrorType::new(ErrorKind::Unparseable( +                self.cur_token().to_type(), +                "param value".to_string(), +            )) +            .into()),          }      }  } diff --git a/src/lang/tokenizer.rs b/src/lang/tokenizer.rs index 6de825b..5711ba2 100644 --- a/src/lang/tokenizer.rs +++ b/src/lang/tokenizer.rs @@ -1,8 +1,8 @@ +use super::Token;  use std::collections::HashMap;  use std::error::Error; -use std::{fmt, io, fs};  use std::io::Read; -use super::*; +use std::{fmt, fs, io};  use unicode_xid::UnicodeXID;  pub struct Lexemes { @@ -15,7 +15,7 @@ pub struct Lexemes {      com_outer: char,      com_inner: char,      include_delim: char, -    escapes: HashMap<char, char> +    escapes: HashMap<char, char>,  }  impl Default for Lexemes { @@ -65,8 +65,8 @@ pub enum NumericKind {  #[derive(Debug)]  pub enum ErrorKind {      UnexpectedEOF(Location), -    BadEscapeValue(EscapeKind, String, Option<Box<Error>>), -    BadNumericLiteral(NumericKind, String, Option<Box<Error>>), +    BadEscapeValue(EscapeKind, String, Option<Box<dyn Error>>), +    BadNumericLiteral(NumericKind, String, Option<Box<dyn Error>>),      UnknownChar(char),      IncludeError(io::Error),      TooManyRecursions(usize), @@ -86,19 +86,32 @@ impl ErrorType {          };          ret.desc = match ret.kind { -            ErrorKind::UnexpectedEOF(ref loc) => format!("Unexpected EOF {}", match *loc { -                Location::InString => "in string constant", -                Location::InStringEscape => "in string escape", -                Location::InInclude => "in include", -            }), -            ErrorKind::BadEscapeValue(ref kind, ref val, ref err) => format!("Bad {} escape {}: {:?}", match *kind { -                EscapeKind::Hexadecimal => "hexadecimal", -                EscapeKind::Octal => "octal", -            }, val, err), -            ErrorKind::BadNumericLiteral(ref kind, ref val, ref err) => format!("Bad {} literal {}: {:?}", match *kind { -                NumericKind::Integer => "integer", -                NumericKind::Float => "floating point", -            }, val, err), +            ErrorKind::UnexpectedEOF(ref loc) => format!( +                "Unexpected EOF {}", +                match *loc { +                    Location::InString => "in string constant", +                    Location::InStringEscape => "in string escape", +                    Location::InInclude => "in include", +                } +            ), +            ErrorKind::BadEscapeValue(ref kind, ref val, ref err) => format!( +                "Bad {} escape {}: {:?}", +                match *kind { +                    EscapeKind::Hexadecimal => "hexadecimal", +                    EscapeKind::Octal => "octal", +                }, +                val, +                err +            ), +            ErrorKind::BadNumericLiteral(ref kind, ref val, ref err) => format!( +                "Bad {} literal {}: {:?}", +                match *kind { +                    NumericKind::Integer => "integer", +                    NumericKind::Float => "floating point", +                }, +                val, +                err +            ),              ErrorKind::UnknownChar(c) => format!("Unknown character {}", c),              ErrorKind::IncludeError(ref e) => format!("Error including file: {:?}", e),              ErrorKind::TooManyRecursions(n) => format!("Include recursed too many times ({})", n), @@ -115,14 +128,21 @@ impl ErrorType {      }  } +impl From<io::Error> for ErrorType { +    fn from(e: io::Error) -> Self { +        Self::new(ErrorKind::IncludeError(e)) +    } +} +  impl Error for ErrorType {      fn description(&self) -> &str {          &self.desc      } -    fn cause(&self) -> Option<&Error> { +    fn cause(&self) -> Option<&dyn Error> {          match self.kind { -            ErrorKind::BadNumericLiteral(_, _, ref err) | ErrorKind::BadEscapeValue(_, _, ref err) => match *err { +            ErrorKind::BadNumericLiteral(_, _, ref err) +            | ErrorKind::BadEscapeValue(_, _, ref err) => match *err {                  Some(ref err) => Some(&**err),                  None => None,              }, @@ -133,7 +153,7 @@ impl Error for ErrorType {  impl fmt::Display for ErrorType {      fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { -        write!(f, "{}", self.description()) +        write!(f, "{}", self.to_string())      }  } @@ -150,10 +170,7 @@ pub struct ResumableChars {  impl ResumableChars {      pub fn new(s: String) -> ResumableChars { -        ResumableChars { -            string: s, -            pos: 0, -        } +        ResumableChars { string: s, pos: 0 }      }  } @@ -166,27 +183,27 @@ impl Iterator for ResumableChars {          } else {              let mut iter = self.string[self.pos..].char_indices();              match iter.next() { -                Some((pos, ch)) => { +                Some((_pos, ch)) => {                      self.pos += match iter.next() {                          Some((pos, _)) => pos,                          None => self.string.len(),                      };                      Some(ch) -                }, +                }                  None => None,              }          }      }  } -pub struct Tokenizer<T: Iterator<Item=char>> { +pub struct Tokenizer<T: Iterator<Item = char>> {      reader: T,      reader_stack: Vec<ResumableChars>,      pushback: Option<char>,      lexemes: Lexemes,  } -impl<T: Iterator<Item=char>> Tokenizer<T> { +impl<T: Iterator<Item = char>> Tokenizer<T> {      const MAX_INCLUDE_RECURSIONS: usize = 256;      pub fn new(reader: T) -> Tokenizer<T> { @@ -203,14 +220,16 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {              None => {                  self.pushback = Some(c);                  true -            }, +            }              Some(_) => false,          }      }      pub fn push_reader(&mut self, rc: ResumableChars) -> Result<(), ErrorType> {          if self.reader_stack.len() > Self::MAX_INCLUDE_RECURSIONS { -            Err(ErrorType::new(ErrorKind::TooManyRecursions(self.reader_stack.len()))) +            Err(ErrorType::new(ErrorKind::TooManyRecursions( +                self.reader_stack.len(), +            )))          } else {              self.reader_stack.push(rc);              Ok(()) @@ -222,11 +241,10 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {              Some(c) => {                  self.pushback = None;                  Some(c) -            }, +            }              None => {                  let mut ret = None;                  let mut produced_idx: usize = 0; -                let len = self.reader_stack.len();                  for (idx, rc) in self.reader_stack.iter_mut().enumerate().rev() {                      match rc.next() { @@ -234,8 +252,8 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                              ret = Some(c);                              produced_idx = idx;                              break; -                        }, -                        None => {}, +                        } +                        None => {}                      }                  } @@ -243,10 +261,10 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                      Some(c) => {                          self.reader_stack.truncate(produced_idx + 1);                          Some(c) -                    }, +                    }                      None => self.reader.next(),                  } -            }, +            }          }      } @@ -298,7 +316,9 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {              loop {                  let nc = self.next_char();                  if nc == None { -                    return Err(ErrorType::new(ErrorKind::UnexpectedEOF(Location::InInclude))); +                    return Err(ErrorType::new(ErrorKind::UnexpectedEOF( +                        Location::InInclude, +                    )));                  }                  let ncc = nc.unwrap(); @@ -314,9 +334,9 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                  Ok(f) => f,              };              let mut contents = String::new(); -            f.read_to_string(&mut contents); +            f.read_to_string(&mut contents)?;              self.push_reader(ResumableChars::new(contents))?; -            return self.next_token() +            return self.next_token();          }          /* Strings */ @@ -332,7 +352,9 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                  if ncc == self.lexemes.esc_intro {                      let ec = self.next_char();                      if ec == None { -                        return Err(ErrorType::new(ErrorKind::UnexpectedEOF(Location::InStringEscape))); +                        return Err(ErrorType::new(ErrorKind::UnexpectedEOF( +                            Location::InStringEscape, +                        )));                      }                      let ecc = ec.unwrap(); @@ -341,7 +363,9 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                          loop {                              let sc = self.next_char();                              if None == sc { -                                return Err(ErrorType::new(ErrorKind::UnexpectedEOF(Location::InStringEscape))); +                                return Err(ErrorType::new(ErrorKind::UnexpectedEOF( +                                    Location::InStringEscape, +                                )));                              }                              let scc = sc.unwrap(); @@ -354,12 +378,22 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                          }                          let rc = u32::from_str_radix(&value, 16);                          if let Err(err) = rc { -                            return Err(ErrorType::new(ErrorKind::BadEscapeValue(EscapeKind::Hexadecimal, value, Some(Box::new(err))))); +                            return Err(ErrorType::new(ErrorKind::BadEscapeValue( +                                EscapeKind::Hexadecimal, +                                value, +                                Some(Box::new(err)), +                            )));                          }                          let rc = ::std::char::from_u32(rc.unwrap());                          match rc {                              Some(rcc) => buffer.push(rcc), -                            None => return Err(ErrorType::new(ErrorKind::BadEscapeValue(EscapeKind::Hexadecimal, value, None))), +                            None => { +                                return Err(ErrorType::new(ErrorKind::BadEscapeValue( +                                    EscapeKind::Hexadecimal, +                                    value, +                                    None, +                                ))) +                            }                          }                          continue;                      } @@ -369,7 +403,9 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                          loop {                              let sc = self.next_char();                              if None == sc { -                                return Err(ErrorType::new(ErrorKind::UnexpectedEOF(Location::InStringEscape))); +                                return Err(ErrorType::new(ErrorKind::UnexpectedEOF( +                                    Location::InStringEscape, +                                )));                              }                              let scc = sc.unwrap(); @@ -382,12 +418,22 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {                          }                          let rc = u32::from_str_radix(&value, 8);                          if let Err(err) = rc { -                            return Err(ErrorType::new(ErrorKind::BadEscapeValue(EscapeKind::Octal, value, Some(Box::new(err))))); +                            return Err(ErrorType::new(ErrorKind::BadEscapeValue( +                                EscapeKind::Octal, +                                value, +                                Some(Box::new(err)), +                            )));                          }                          let rc = ::std::char::from_u32(rc.unwrap());                          match rc {                              Some(rcc) => buffer.push(rcc), -                            None => return Err(ErrorType::new(ErrorKind::BadEscapeValue(EscapeKind::Octal, value, None))), +                            None => { +                                return Err(ErrorType::new(ErrorKind::BadEscapeValue( +                                    EscapeKind::Octal, +                                    value, +                                    None, +                                ))) +                            }                          }                          continue;                      } @@ -459,12 +505,20 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {              return if floating {                  match buffer.parse::<f32>() {                      Ok(v) => Ok(Token::Float(v)), -                    Err(err) => Err(ErrorType::new(ErrorKind::BadNumericLiteral(NumericKind::Float, buffer, Some(Box::new(err))))), +                    Err(err) => Err(ErrorType::new(ErrorKind::BadNumericLiteral( +                        NumericKind::Float, +                        buffer, +                        Some(Box::new(err)), +                    ))),                  }              } else {                  match buffer.parse::<isize>() {                      Ok(v) => Ok(Token::Integer(v)), -                    Err(err) => Err(ErrorType::new(ErrorKind::BadNumericLiteral(NumericKind::Integer, buffer, Some(Box::new(err))))), +                    Err(err) => Err(ErrorType::new(ErrorKind::BadNumericLiteral( +                        NumericKind::Integer, +                        buffer, +                        Some(Box::new(err)), +                    ))),                  }              };          } @@ -497,7 +551,7 @@ impl<T: Iterator<Item=char>> Tokenizer<T> {      }  } -impl<T: Iterator<Item=char>> Iterator for Tokenizer<T> { +impl<T: Iterator<Item = char>> Iterator for Tokenizer<T> {      type Item = Token;      fn next(&mut self) -> Option<Token> { @@ -7,12 +7,12 @@ extern crate xml;  pub mod types;  pub use types::*; -pub mod synth; -pub mod proto; -pub mod lang;  pub mod client; +pub mod lang;  pub mod monitor;  pub mod seq; +pub mod proto; +pub mod synth;  #[cfg(feature = "graphics")]  pub mod graphics; @@ -20,6 +20,5 @@ pub mod graphics;  #[cfg(test)]  mod tests {      #[test] -    fn it_works() { -    } +    fn it_works() {}  } diff --git a/src/main.rs b/src/main.rs index 9c61733..38c2e78 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,26 +1,19 @@ -use std::{io, env, thread, iter, time, mem, ffi}; -use std::io::*; -use std::fs::*; +use std::collections::VecDeque; +use std::fs::File; +use std::io::Read;  use std::net::*;  use std::sync::*; -use std::collections::VecDeque; +use std::{env, iter, thread, ffi}; -extern crate synfone;  extern crate portaudio; -// #[macro_use] -// extern crate glium; -// use glium::{glutin, Surface}; -// use glium::index::PrimitiveType; -// extern crate palette; -// use palette::IntoColor;  use portaudio as pa; -use synfone::*; -use synfone::synth::*; +use synfone::client::*;  use synfone::lang::*;  use synfone::proto::*; -use synfone::client::*; +use synfone::synth::*; +use synfone::*; -fn main() { +fn main() -> Result<(), std::io::Error> {      let cmd = env::args_os().nth(1).expect("Please pass a command as the first argument; use `help` as a command for more information.");      let cmds = cmd.into_string().expect("Couldn't parse command"); @@ -28,60 +21,82 @@ fn main() {      match &*cmds {          "help" => eprintln!("TODO! Commands are help, client."), -        "client" => main_client(new_args), +        "client" => main_client(new_args)?,          _ => eprintln!("Unknown command; `help` for help."),      } +    Ok(())  } -const GFX: bool = false; - -fn main_client(args: Vec<ffi::OsString>) { +fn main_client(args: Vec<ffi::OsString>) -> Result<(), std::io::Error> {      let env = Environment::default();      let mut genfile = File::open(args.iter().nth(1).expect("Need first argument to be a file with a generator vector")).expect("Failed to open file");      let mut genstr = String::new(); -    genfile.read_to_string(&mut genstr); +    genfile.read_to_string(&mut genstr)?; -    let gens = Parser::new(Tokenizer::new(genstr.chars()), env.clone()).expect("Failed to get first token").parse_gen_vec().expect("Failed to compile generators"); +    let gens = Parser::new(Tokenizer::new(genstr.chars()), env.clone()) +        .expect("Failed to get first token") +        .parse_gen_vec() +        .expect("Failed to compile generators");      let sock = UdpSocket::bind("0.0.0.0:13676").expect("Failed to bind socket");      eprintln!("Parsed {} generator definitions", gens.len()); -    let mut client = Arc::new(Mutex::new(Client::new(sock.try_clone().expect("Failed to clone socket"), gens, env.clone()).expect("Failed to create client"))); -    let mut last_buffer = Arc::new(Mutex::new(<VecDeque<Sample>>::with_capacity(env.default_buffer_size * 9))); +    let client = Arc::new(Mutex::new( +        Client::new( +            sock.try_clone().expect("Failed to clone socket"), +            gens, +            env.clone(), +        ) +        .expect("Failed to create client"), +    )); +    let last_buffer = Arc::new(Mutex::new(<VecDeque<Sample>>::with_capacity( +        env.default_buffer_size * 9, +    )));      let last_buffer_lim = env.default_buffer_size * 8; -    last_buffer.lock().expect("Failed to init shared buffer").append(&mut iter::repeat(0.0f32).take(last_buffer_lim).collect()); +    last_buffer +        .lock() +        .expect("Failed to init shared buffer") +        .append(&mut iter::repeat(0.0f32).take(last_buffer_lim).collect());      let pa_inst = pa::PortAudio::new().expect("Failed to create PortAudio interface"); -    let settings = pa_inst.default_output_stream_settings(1, env.sample_rate as f64, env.default_buffer_size as u32).expect("Failed to instantiate stream settings"); +    let settings = pa_inst +        .default_output_stream_settings(1, env.sample_rate as f64, env.default_buffer_size as u32) +        .expect("Failed to instantiate stream settings");      let mut stream;      {          let client = client.clone();          let last_buffer = last_buffer.clone();          let mut ring: VecDeque<Sample> = VecDeque::new();          ring.reserve_exact(2 * env.default_buffer_size); -        stream = pa_inst.open_non_blocking_stream(settings, move |pa::OutputStreamCallbackArgs { buffer, frames, .. }| { -            while frames > ring.len() { -                let mut cli = client.lock().unwrap(); -                cli.next_frames(); -                { -                    let mut buf = last_buffer.lock().expect("Failed to acquire shared buffer in audio callback"); -                    buf.append(&mut cli.buffer().samples.iter().map(|&x| x).collect()); -                    let len = buf.len(); -                    if len > last_buffer_lim { -                        buf.drain(..(len - last_buffer_lim)); +        stream = pa_inst +            .open_non_blocking_stream( +                settings, +                move |pa::OutputStreamCallbackArgs { buffer, frames, .. }| { +                    while frames > ring.len() { +                        let mut cli = client.lock().unwrap(); +                        cli.next_frames(); +                        { +                            let mut buf = last_buffer +                                .lock() +                                .expect("Failed to acquire shared buffer in audio callback"); +                            buf.append(&mut cli.buffer().samples.iter().map(|&x| x).collect()); +                            let len = buf.len(); +                            if len > last_buffer_lim { +                                buf.drain(..(len - last_buffer_lim)); +                            } +                        } +                        ring.append(&mut cli.buffer().iter().map(|&x| x).collect());                      } -                } -                ring.append(&mut cli.buffer().iter().map(|&x| x).collect()); -            } -            let samps = ring.drain(..frames).collect::<Vec<f32>>(); -            buffer.copy_from_slice(&samps); -            pa::Continue -        }).expect("Failed to create stream"); +                    let samps = ring.drain(..frames).collect::<Vec<f32>>(); +                    buffer.copy_from_slice(&samps); +                    pa::Continue +                }, +            ) +            .expect("Failed to create stream");      } -      eprintln!("Starting.");      stream.start().expect("Failed to start stream"); @@ -115,4 +130,6 @@ fn main_client(args: Vec<ffi::OsString>) {      net_thread.join().expect("Network thread panicked");      eprintln!("Exiting."); + +    Ok(())  } diff --git a/src/monitor.rs b/src/monitor.rs index ffe688a..bde5b37 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -1,6 +1,6 @@  use super::*; -use synth::SampleBuffer;  use std::collections::HashMap; +use synth::SampleBuffer;  pub struct VoiceDatum {      pitch: Pitch, @@ -35,4 +35,4 @@ pub trait Monitor {      fn process(&mut self, data: &Data);  } -pub type MonBox = Box<Monitor>; +pub type MonBox = Box<dyn Monitor>; diff --git a/src/proto.rs b/src/proto.rs index 21e8903..2bf13a6 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -1,6 +1,6 @@ -use std::{mem, fmt}; +use super::Pitch;  use std::time::Duration; -use super::*; +use std::fmt;  use ::byteorder::{ByteOrder, NetworkEndian}; @@ -9,7 +9,9 @@ const OBLIGATE_POLYPHONE: u32 = 0xffffffff;  pub enum Command {      KeepAlive, -    Ping{data: [u8; 32]}, +    Ping { +        data: [u8; 32], +    },      Quit,      Play{sec: u32, usec: u32, freq: u32, amp: f32, voice: u32},      Caps{voices: u32, tp: [u8; 4], ident: [u8; 24]}, @@ -24,14 +26,14 @@ impl Command {      pub fn duration(&self) -> Option<Duration> {          match *self { -            Command::Play{sec, usec, ..} => Some(Duration::new(sec as u64, usec * 1000)), +            Command::Play { sec, usec, .. } => Some(Duration::new(sec as u64, usec * 1000)),              _ => None,          }      }      pub fn pitch(&self) -> Option<Pitch> {          match *self { -            Command::Play{freq, ..} => Some(Pitch::Freq(freq as f32)), +            Command::Play { freq, .. } => Some(Pitch::Freq(freq as f32)),              _ => None,          }      } @@ -43,22 +45,28 @@ impl Command {          match *self {              Command::KeepAlive => NetworkEndian::write_u32(&mut ret[..4], 0), -            Command::Ping{data} => { +            Command::Ping { data } => {                  NetworkEndian::write_u32(&mut ret[..4], 1);                  (&mut ret[4..]).copy_from_slice(&data); -            }, +            }              Command::Quit => NetworkEndian::write_u32(&mut ret[..4], 2), -            Command::Play{sec, usec, freq, amp, voice} => { +            Command::Play { +                sec, +                usec, +                freq, +                amp, +                voice, +            } => {                  NetworkEndian::write_u32_into(&[3u32, sec, usec, freq], &mut ret[..16]);                  NetworkEndian::write_f32(&mut ret[16..20], amp);                  NetworkEndian::write_u32(&mut ret[20..24], voice); -            }, -            Command::Caps{voices, tp, ident} => { +            } +            Command::Caps { voices, tp, ident } => {                  NetworkEndian::write_u32_into(&[4u32, voices], &mut ret[..8]);                  (&mut ret[8..12]).copy_from_slice(&tp);                  (&mut ret[12..]).copy_from_slice(&ident); -            }, -            Command::PCM{samples} => { +            } +            Command::PCM { samples } => {                  NetworkEndian::write_u32(&mut ret[..4], 5);                  NetworkEndian::write_i16_into(&samples, &mut ret[4..]);              }, @@ -71,7 +79,7 @@ impl Command {              },              Command::Unknown{data} => {                  ret.copy_from_slice(&data); -            }, +            }          };          true @@ -83,7 +91,7 @@ impl fmt::Debug for Command {          f.write_str("Command::")?;          match *self {              Command::KeepAlive => f.write_str("KeepAlive"), -            Command::Ping{data} => f.debug_struct("Ping").field("data", &data).finish(), +            Command::Ping { data } => f.debug_struct("Ping").field("data", &data).finish(),              Command::Quit => f.write_str("Quit"),              Command::Play{sec, usec, freq, amp, voice} => f.debug_struct("Play").field("sec", &sec).field("usec", &usec).field("freq", &freq).field("amp", &).field("voice", &voice).finish(),              Command::Caps{voices, tp, ident} => f.debug_struct("Caps").field("voices", &voices).field("tp", &tp).field("ident", &ident).finish(), @@ -97,20 +105,20 @@ impl fmt::Debug for Command {  impl<'a> From<&'a [u8; Command::SIZE]> for Command {      fn from(packet: &'a [u8; Command::SIZE]) -> Command { -        let mut fields_u32: [u32; Command::SIZE / 4] = unsafe { mem::uninitialized() }; -        let mut fields_f32: [f32; Command::SIZE / 4] = unsafe { mem::uninitialized() }; +        let mut fields_u32: [u32; Command::SIZE / 4] = [0; Command::SIZE / 4]; +        let mut fields_f32: [f32; Command::SIZE / 4] = [0.0; Command::SIZE / 4];          NetworkEndian::read_u32_into(packet, &mut fields_u32); -        unsafe { NetworkEndian::read_f32_into_unchecked(packet, &mut fields_f32); } +        NetworkEndian::read_f32_into(packet, &mut fields_f32);          match fields_u32[0] {              0 => Command::KeepAlive,              1 => { -                let mut data: [u8; 32] = unsafe { mem::uninitialized() }; +                let mut data: [u8; 32] = [0; 32];                  data.copy_from_slice(&packet[4..]); -                Command::Ping{data: data} +                Command::Ping { data: data }              }              2 => Command::Quit, -            3 => Command::Play{ +            3 => Command::Play {                  sec: fields_u32[1],                  usec: fields_u32[2],                  freq: fields_u32[3], @@ -118,18 +126,18 @@ impl<'a> From<&'a [u8; Command::SIZE]> for Command {                  voice: fields_u32[5],              },              4 => { -                let mut tp: [u8; 4] = unsafe { mem::uninitialized() }; -                let mut ident: [u8; 24] = unsafe { mem::uninitialized() }; +                let mut tp: [u8; 4] = [0; 4]; +                let mut ident: [u8; 24] = [0; 24];                  tp.copy_from_slice(&packet[8..12]);                  ident.copy_from_slice(&packet[12..]); -                Command::Caps{ +                Command::Caps {                      voices: fields_u32[1],                      tp: tp,                      ident: ident,                  } -            }, +            }              5 => { -                let mut samples: [i16; 16] = unsafe { mem::uninitialized() }; +                let mut samples: [i16; 16] = [0; 16];                  ::byteorder::LittleEndian::read_i16_into(&packet[4..], &mut samples);                  Command::PCM{samples: samples}              }, @@ -140,9 +148,9 @@ impl<'a> From<&'a [u8; Command::SIZE]> for Command {                  value: fields_f32[3],              },              _ => { -                let mut data: [u8; Command::SIZE] = unsafe { mem::uninitialized() }; +                let mut data: [u8; Command::SIZE] = [0; Command::SIZE];                  data.copy_from_slice(packet); -                Command::Unknown{data: data} +                Command::Unknown { data: data }              }          }      } diff --git a/src/seq/file/iv.rs b/src/seq/file/iv.rs index 570f36d..de3f0b6 100644 --- a/src/seq/file/iv.rs +++ b/src/seq/file/iv.rs @@ -10,7 +10,6 @@ use std::cmp::Eq;  use std::str::FromStr;  use std::fmt::Display;  use failure::Error; -use super::*;  struct AttrMapping(HashMap<String, String>); diff --git a/src/seq/file/mod.rs b/src/seq/file/mod.rs index 12662f8..f6fd39a 100644 --- a/src/seq/file/mod.rs +++ b/src/seq/file/mod.rs @@ -1,4 +1,3 @@  //pub mod iv;  //pub mod midi; -use super::*; diff --git a/src/seq/sequencer.rs b/src/seq/sequencer.rs index 2284656..753a2f1 100644 --- a/src/seq/sequencer.rs +++ b/src/seq/sequencer.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{NoteStream, Note, IV};  pub fn coalesce<'a, I: Iterator<Item=&'a NoteStream>>(stream_iter: I) -> NoteStream {      let mut output = NoteStream::new(); diff --git a/src/synth/adsr.rs b/src/synth/adsr.rs index ca7be9c..e7dba5d 100644 --- a/src/synth/adsr.rs +++ b/src/synth/adsr.rs @@ -1,6 +1,9 @@ -use super::*; +use super::{ +    mem, FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, Parameters, Rate, +    SampleBuffer, +}; -#[derive(Debug,Clone,Copy,PartialEq,Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)]  pub enum Phase {      Delay,      Attack, @@ -44,7 +47,7 @@ impl Generator for DAHDSR {                  self.attack_cd = delay;                  self.cur = 0.0;              } -        } else{ +        } else {              self.phase = Phase::Release;          } @@ -55,7 +58,7 @@ impl Generator for DAHDSR {                      if self.attack_cd <= 0.0 {                          self.phase = Phase::Attack;                      } -                }, +                }                  Phase::Attack => {                      self.cur += attack;                      if self.cur >= 1.0 { @@ -63,36 +66,38 @@ impl Generator for DAHDSR {                          self.phase = Phase::Hold;                          self.decay_cd = hold;                      } -                }, +                }                  Phase::Hold => {                      self.decay_cd -= 1.0;                      if self.decay_cd <= 0.0 {                          self.phase = Phase::Decay;                      } -                }, +                }                  Phase::Decay => {                      self.cur -= decay;                      if self.cur <= sustain {                          self.cur = sustain;                          self.phase = Phase::Sustain;                      } -                }, +                }                  Phase::Sustain => {                      self.cur = sustain; -                }, +                }                  Phase::Release => {                      self.cur -= release;                      if self.cur < 0.0 {                          self.cur = 0.0;                      } -                }, +                }              }              *samp = self.cur;          }          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } diff --git a/src/synth/logic.rs b/src/synth/logic.rs index d5f9401..f6cb013 100644 --- a/src/synth/logic.rs +++ b/src/synth/logic.rs @@ -1,5 +1,8 @@ -use std::{mem, cmp}; -use super::*; +use super::{ +    FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, Parameters, Rate, +    SampleBuffer, +}; +use std::{cmp, mem};  #[derive(Debug)]  pub struct IfElse { @@ -14,11 +17,10 @@ impl Generator for IfElse {          let cond_buf = self.cond.eval(params);          let iftrue_buf = self.iftrue.eval(params);          let iffalse_buf = self.iffalse.eval(params); -         -        if -            cond_buf.rate == Rate::Control && -            iftrue_buf.rate == Rate::Control && -            iffalse_buf.rate == Rate::Control + +        if cond_buf.rate == Rate::Control +            && iftrue_buf.rate == Rate::Control +            && iffalse_buf.rate == Rate::Control          {              self.buf.set(if cond_buf.first() >= 0.5 {                  iftrue_buf.first() @@ -31,9 +33,15 @@ impl Generator for IfElse {          self.buf.rate = Rate::Sample;          let mut bound = self.buf.len(); -        if cond_buf.rate == Rate::Sample { bound = cmp::min(bound, cond_buf.len()); } -        if iftrue_buf.rate == Rate::Sample { bound = cmp::min(bound, iftrue_buf.len()); } -        if iffalse_buf.rate == Rate::Sample { bound = cmp::min(bound, iffalse_buf.len()); } +        if cond_buf.rate == Rate::Sample { +            bound = cmp::min(bound, cond_buf.len()); +        } +        if iftrue_buf.rate == Rate::Sample { +            bound = cmp::min(bound, iftrue_buf.len()); +        } +        if iffalse_buf.rate == Rate::Sample { +            bound = cmp::min(bound, iffalse_buf.len()); +        }          for i in 0..bound {              let tv = match iftrue_buf.rate { @@ -48,16 +56,14 @@ impl Generator for IfElse {                  Rate::Sample => cond_buf[i],                  Rate::Control => cond_buf.first(),              }; -            self.buf[i] = if cv >= 0.5 { -                tv -            } else { -                fv -            }; +            self.buf[i] = if cv >= 0.5 { tv } else { fv };          }          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -70,8 +76,16 @@ impl GeneratorFactory for IfElseFactory {          let cond = params.remove_param("cond", 0)?.into_gen()?;          let iftrue = params.remove_param("iftrue", 1)?.into_gen()?;          let iffalse = params.remove_param("iffalse", 2)?.into_gen()?; -        let buf = SampleBuffer::new(cmp::max(cmp::max(cond.buffer().len(), iftrue.buffer().len()), iffalse.buffer().len())); -        Ok(Box::new(IfElse { cond: cond, iftrue: iftrue, iffalse: iffalse, buf: buf })) +        let buf = SampleBuffer::new(cmp::max( +            cmp::max(cond.buffer().len(), iftrue.buffer().len()), +            iffalse.buffer().len(), +        )); +        Ok(Box::new(IfElse { +            cond: cond, +            iftrue: iftrue, +            iffalse: iffalse, +            buf: buf, +        }))      }  } diff --git a/src/synth/lut.rs b/src/synth/lut.rs index 73b5efa..deda6d9 100644 --- a/src/synth/lut.rs +++ b/src/synth/lut.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ +    mem, FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, ParamValue, +    Parameters, Rate, Sample, SampleBuffer, +};  #[derive(Debug)]  pub struct Lut { @@ -14,13 +17,16 @@ impl Generator for Lut {          let pvel = self.freq.eval(params).first() / params.env.sample_rate;          for i in 0..self.buf.len() { -            self.buf[i] = self.lut[(((self.phase + pvel * (i as f32)) % 1.0) * (self.lut.len() as f32)) as usize]; +            self.buf[i] = self.lut +                [(((self.phase + pvel * (i as f32)) % 1.0) * (self.lut.len() as f32)) as usize];          }          self.phase = (self.phase + pvel * (self.buf.len() as f32)) % 1.0;          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -32,7 +38,9 @@ impl GeneratorFactory for LutDataFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Lut {              freq: params.remove_param("freq", 0)?.into_gen()?, -            phase: params.get_param("phase", 1, &mut ParamValue::Float(0.0)).as_f32()?, +            phase: params +                .get_param("phase", 1, &mut ParamValue::Float(0.0)) +                .as_f32()?,              buf: SampleBuffer::new(params.env.default_buffer_size),              lut: {                  let mut lut: Vec<Sample> = Vec::new(); @@ -44,7 +52,10 @@ impl GeneratorFactory for LutDataFactory {                  }                  if lut.is_empty() { -                    return Err(GenFactoryError::MissingRequiredParam("samples".to_string(), 2)); +                    return Err(GenFactoryError::MissingRequiredParam( +                        "samples".to_string(), +                        2, +                    ));                  }                  lut @@ -62,13 +73,20 @@ impl GeneratorFactory for LutGenFactory {          eprintln!("LutGenFactory::new({:?})", params);          Ok(Box::new(Lut {              freq: params.remove_param("freq", 2)?.into_gen()?, -            phase: params.get_param("phase", 3, &mut ParamValue::Float(0.0)).as_f32()?, +            phase: params +                .get_param("phase", 3, &mut ParamValue::Float(0.0)) +                .as_f32()?,              buf: SampleBuffer::new(params.env.default_buffer_size),              lut: {                  let mut gen = params.remove_param("gen", 0)?.into_gen()?;                  let samps = params.get_req_param("samples", 1)?.as_f32()?; -                let var = params.get_param("var", 4, &mut ParamValue::String("lut_freq".to_string())).as_string()?; -                let mut genparams = Parameters { env: params.env.clone(), ..Default::default() }; +                let var = params +                    .get_param("var", 4, &mut ParamValue::String("lut_freq".to_string())) +                    .as_string()?; +                let mut genparams = Parameters { +                    env: params.env.clone(), +                    ..Default::default() +                };                  genparams.env.sample_rate = samps;                  genparams.vars.insert(var, 1.0); diff --git a/src/synth/math.rs b/src/synth/math.rs index 1889139..c73c0c4 100644 --- a/src/synth/math.rs +++ b/src/synth/math.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ +    FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, Parameters, Rate, +    SampleBuffer, +};  use std::mem;  #[derive(Debug)] @@ -20,7 +23,9 @@ impl Generator for Add {          }          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -31,7 +36,11 @@ pub struct AddFactory;  impl GeneratorFactory for AddFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Add { -            terms: params.get_pos_params().into_iter().map(|x| x.into_gen()).collect::<Result<Vec<_>, _>>()?, +            terms: params +                .get_pos_params() +                .into_iter() +                .map(|x| x.into_gen()) +                .collect::<Result<Vec<_>, _>>()?,              buf: SampleBuffer::new(params.env.default_buffer_size),          }))      } @@ -58,7 +67,9 @@ impl Generator for Mul {          }          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -69,7 +80,11 @@ pub struct MulFactory;  impl GeneratorFactory for MulFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Mul { -            factors: params.get_pos_params().into_iter().map(|x| x.into_gen()).collect::<Result<Vec<_>, _>>()?, +            factors: params +                .get_pos_params() +                .into_iter() +                .map(|x| x.into_gen()) +                .collect::<Result<Vec<_>, _>>()?,              buf: SampleBuffer::new(params.env.default_buffer_size),          }))      } @@ -91,14 +106,16 @@ impl Generator for Negate {                  for v in self.buf.iter_mut() {                      *v *= -1.0;                  } -            }, +            }              Rate::Control => {                  self.buf[0] *= -1.0; -            }, +            }          }          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -133,14 +150,16 @@ impl Generator for Reciprocate {                  for v in self.buf.iter_mut() {                      *v = v.powf(-1.0);                  } -            }, +            }              Rate::Control => {                  self.buf[0] = self.buf[0].powf(-1.0); -            }, +            }          }          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } diff --git a/src/synth/mod.rs b/src/synth/mod.rs index 862ca38..b832863 100644 --- a/src/synth/mod.rs +++ b/src/synth/mod.rs @@ -1,15 +1,15 @@  #![allow(non_upper_case_globals)] -use std::{iter, cmp, slice, mem, fmt}; -use std::fmt::Debug; +use super::Sample; +use std::collections::HashMap;  use std::error::Error; +use std::fmt::Debug;  use std::ops::{Index, IndexMut}; -use std::collections::HashMap; -use super::*; +use std::{cmp, fmt, iter, mem, slice};  use ::byteorder::ByteOrder; -#[derive(PartialEq,Eq,Clone,Copy,Debug)] +#[derive(PartialEq, Eq, Clone, Copy, Debug)]  pub enum Rate {      Sample,      Control, @@ -21,7 +21,7 @@ pub struct SampleBuffer {      pub rate: Rate,  } -#[derive(Debug,Clone)] +#[derive(Debug, Clone)]  pub struct Environment {      pub sample_rate: f32,      pub default_buffer_size: usize, @@ -87,10 +87,10 @@ impl SampleBuffer {              Rate::Sample => {                  let len = cmp::min(self.len(), other.len());                  self.samples[..len].clone_from_slice(&other.samples[..len]); -            }, +            }              Rate::Control => {                  self.samples[0] = other.samples[0]; -            }, +            }          }      } @@ -109,10 +109,10 @@ impl SampleBuffer {                          }                      }                  }; -            }, +            }              Rate::Control => {                  self.samples[0] += other.samples[0]; -            }, +            }          }      } @@ -131,10 +131,10 @@ impl SampleBuffer {                          }                      }                  }; -            }, +            }              Rate::Control => {                  self.samples[0] *= other.samples[0]; -            }, +            }          }      } @@ -156,11 +156,15 @@ impl SampleBuffer {  impl Index<usize> for SampleBuffer {      type Output = Sample; -    fn index(&self, idx: usize) -> &Sample { &self.samples[idx] } +    fn index(&self, idx: usize) -> &Sample { +        &self.samples[idx] +    }  }  impl IndexMut<usize> for SampleBuffer { -    fn index_mut(&mut self, idx: usize) -> &mut Sample { &mut self.samples[idx] } +    fn index_mut(&mut self, idx: usize) -> &mut Sample { +        &mut self.samples[idx] +    }  }  impl Clone for SampleBuffer { @@ -172,13 +176,13 @@ impl Clone for SampleBuffer {      }  } -pub trait Generator : Debug + Send { +pub trait Generator: Debug + Send {      fn eval<'a>(&'a mut self, params: &Parameters) -> &'a SampleBuffer;      fn buffer(&self) -> &SampleBuffer;      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer;  } -pub type GenBox = Box<Generator>; +pub type GenBox = Box<dyn Generator>;  #[derive(Debug)]  pub enum GenFactoryError { @@ -190,7 +194,7 @@ pub enum GenFactoryError {  #[derive(Debug)]  pub struct GenFactoryErrorType {      pub kind: GenFactoryError, -    desc: String +    desc: String,  }  impl GenFactoryErrorType { @@ -201,8 +205,12 @@ impl GenFactoryErrorType {          };          ret.desc = match ret.kind { -            GenFactoryError::MissingRequiredParam(ref name, pos) => format!("Needed a parameter named {} or at pos {}", name, pos), -            GenFactoryError::CannotConvert(from, to) => format!("Cannot convert {:?} to {:?}", from, to), +            GenFactoryError::MissingRequiredParam(ref name, pos) => { +                format!("Needed a parameter named {} or at pos {}", name, pos) +            } +            GenFactoryError::CannotConvert(from, to) => { +                format!("Cannot convert {:?} to {:?}", from, to) +            }              GenFactoryError::BadType(ty) => format!("Bad parameter type {:?}", ty),          }; @@ -231,17 +239,17 @@ impl Error for GenFactoryErrorType {  impl fmt::Display for GenFactoryErrorType {      fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { -        write!(f, "{}", self.description()) +        write!(f, "{}", self.to_string())      }  } -impl Into<Box<Error>> for GenFactoryError { -    fn into(self) -> Box<Error> { +impl Into<Box<dyn Error>> for GenFactoryError { +    fn into(self) -> Box<dyn Error> {          Box::new(GenFactoryErrorType::new(self))      }  } -#[derive(Debug,PartialEq,Eq,Clone,Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)]  pub enum ParamKind {      Integer,      Float, @@ -271,7 +279,9 @@ impl ParamValue {          match *self {              ParamValue::Integer(v) => Ok(v),              ParamValue::Float(v) => Ok(v as isize), -            ParamValue::String(ref v) => v.parse().map_err(|_| GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Integer)), +            ParamValue::String(ref v) => v +                .parse() +                .map_err(|_| GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Integer)),              ParamValue::Generator(ref mut g) => Ok(g.eval(&Default::default()).first() as isize),          }      } @@ -280,7 +290,9 @@ impl ParamValue {          match *self {              ParamValue::Integer(v) => Ok(v as f32),              ParamValue::Float(v) => Ok(v), -            ParamValue::String(ref v) => v.parse().map_err(|_| GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Float)), +            ParamValue::String(ref v) => v +                .parse() +                .map_err(|_| GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Float)),              ParamValue::Generator(ref mut g) => Ok(g.eval(&Default::default()).first()),          }      } @@ -290,15 +302,29 @@ impl ParamValue {              ParamValue::Integer(v) => Ok(v.to_string()),              ParamValue::Float(v) => Ok(v.to_string()),              ParamValue::String(ref v) => Ok(v.clone()), -            ParamValue::Generator(_) => Err(GenFactoryError::CannotConvert(ParamKind::Generator, ParamKind::String)), +            ParamValue::Generator(_) => Err(GenFactoryError::CannotConvert( +                ParamKind::Generator, +                ParamKind::String, +            )),          }      }      pub fn into_gen(self) -> Result<GenBox, GenFactoryError> {          match self { -            ParamValue::Integer(v) => Ok(Box::new(self::param::Param { name : "_".to_string(), default: v as f32, buf: SampleBuffer::new(1) })), -            ParamValue::Float(v) => Ok(Box::new(self::param::Param { name : "_".to_string(), default: v, buf: SampleBuffer::new(1) })), -            ParamValue::String(_) => Err(GenFactoryError::CannotConvert(ParamKind::String, ParamKind::Generator)), +            ParamValue::Integer(v) => Ok(Box::new(self::param::Param { +                name: "_".to_string(), +                default: v as f32, +                buf: SampleBuffer::new(1), +            })), +            ParamValue::Float(v) => Ok(Box::new(self::param::Param { +                name: "_".to_string(), +                default: v, +                buf: SampleBuffer::new(1), +            })), +            ParamValue::String(_) => Err(GenFactoryError::CannotConvert( +                ParamKind::String, +                ParamKind::Generator, +            )),              ParamValue::Generator(g) => Ok(g),          }      } @@ -310,37 +336,63 @@ impl<'a> From<&'a ParamValue> for ParamKind {      }  } -#[derive(Debug,Default)] +#[derive(Debug, Default)]  pub struct FactoryParameters {      pub env: Environment,      pub vars: HashMap<String, ParamValue>,  }  impl FactoryParameters { -    pub fn get_param<'a, 'b : 'a>(&'a mut self, name: &str, position: usize, default: &'b mut ParamValue) -> &'a mut ParamValue { +    pub fn get_param<'a, 'b: 'a>( +        &'a mut self, +        name: &str, +        position: usize, +        default: &'b mut ParamValue, +    ) -> &'a mut ParamValue {          let position = position.to_string(); -        match (self.vars.contains_key(name), self.vars.contains_key(&position)) { +        match ( +            self.vars.contains_key(name), +            self.vars.contains_key(&position), +        ) {              (true, _) => self.vars.get_mut(name).unwrap(),              (false, true) => self.vars.get_mut(&position).unwrap(),              (false, false) => default,          }      } -    pub fn get_req_param(&mut self, name: &str, position: usize) -> Result<&mut ParamValue, GenFactoryError> { +    pub fn get_req_param( +        &mut self, +        name: &str, +        position: usize, +    ) -> Result<&mut ParamValue, GenFactoryError> {          let pos = position.to_string();          match (self.vars.contains_key(name), self.vars.contains_key(&pos)) {              (true, _) => Ok(self.vars.get_mut(name).unwrap()),              (false, true) => Ok(self.vars.get_mut(&pos).unwrap()), -            (false, false) => Err(GenFactoryError::MissingRequiredParam(name.to_string(), position)), +            (false, false) => Err(GenFactoryError::MissingRequiredParam( +                name.to_string(), +                position, +            )),          }      } -    pub fn remove_param(&mut self, name: &str, position: usize) -> Result<ParamValue, GenFactoryError> { -        match self.vars.remove(name).or_else(|| self.vars.remove(&position.to_string())) { +    pub fn remove_param( +        &mut self, +        name: &str, +        position: usize, +    ) -> Result<ParamValue, GenFactoryError> { +        match self +            .vars +            .remove(name) +            .or_else(|| self.vars.remove(&position.to_string())) +        {              Some(v) => Ok(v), -            None => Err(GenFactoryError::MissingRequiredParam(name.to_string(), position)), +            None => Err(GenFactoryError::MissingRequiredParam( +                name.to_string(), +                position, +            )),          }      } @@ -390,26 +442,77 @@ pub use self::noise::Noise;  pub mod adsr;  pub use self::adsr::DAHDSR; -pub fn all_factories() -> HashMap<String, &'static GeneratorFactory> { +pub fn all_factories() -> HashMap<String, &'static dyn GeneratorFactory> {      let mut ret = HashMap::new(); -    ret.insert("param".to_string(), &self::param::Factory as &GeneratorFactory); -    ret.insert("add".to_string(), &self::math::FactoryAdd as &GeneratorFactory); -    ret.insert("mul".to_string(), &self::math::FactoryMul as &GeneratorFactory); -    ret.insert("negate".to_string(), &self::math::FactoryNegate as &GeneratorFactory); -    ret.insert("reciprocate".to_string(), &self::math::FactoryReciprocate as &GeneratorFactory); -    ret.insert("rel".to_string(), &self::rel::Factory as &GeneratorFactory); -    ret.insert("ifelse".to_string(), &self::logic::Factory as &GeneratorFactory); -    ret.insert("controlrate".to_string(), &self::util::FactoryControlRate as &GeneratorFactory); -    ret.insert("samplerate".to_string(), &self::util::FactorySampleRate as &GeneratorFactory); -    ret.insert("lutdata".to_string(), &self::lut::FactoryLutData as &GeneratorFactory); -    ret.insert("lutgen".to_string(), &self::lut::FactoryLutGen as &GeneratorFactory); -    ret.insert("sine".to_string(), &self::sine::Factory as &GeneratorFactory); -    ret.insert("saw".to_string(), &self::saw::Factory as &GeneratorFactory); -    ret.insert("triangle".to_string(), &self::triangle::Factory as &GeneratorFactory); -    ret.insert("square".to_string(), &self::square::Factory as &GeneratorFactory); -    ret.insert("noise".to_string(), &self::noise::Factory as &GeneratorFactory); -    ret.insert("dahdsr".to_string(), &self::adsr::Factory as &GeneratorFactory); +    ret.insert( +        "param".to_string(), +        &self::param::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "add".to_string(), +        &self::math::FactoryAdd as &dyn GeneratorFactory, +    ); +    ret.insert( +        "mul".to_string(), +        &self::math::FactoryMul as &dyn GeneratorFactory, +    ); +    ret.insert( +        "negate".to_string(), +        &self::math::FactoryNegate as &dyn GeneratorFactory, +    ); +    ret.insert( +        "reciprocate".to_string(), +        &self::math::FactoryReciprocate as &dyn GeneratorFactory, +    ); +    ret.insert( +        "rel".to_string(), +        &self::rel::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "ifelse".to_string(), +        &self::logic::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "controlrate".to_string(), +        &self::util::FactoryControlRate as &dyn GeneratorFactory, +    ); +    ret.insert( +        "samplerate".to_string(), +        &self::util::FactorySampleRate as &dyn GeneratorFactory, +    ); +    ret.insert( +        "lutdata".to_string(), +        &self::lut::FactoryLutData as &dyn GeneratorFactory, +    ); +    ret.insert( +        "lutgen".to_string(), +        &self::lut::FactoryLutGen as &dyn GeneratorFactory, +    ); +    ret.insert( +        "sine".to_string(), +        &self::sine::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "saw".to_string(), +        &self::saw::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "triangle".to_string(), +        &self::triangle::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "square".to_string(), +        &self::square::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "noise".to_string(), +        &self::noise::Factory as &dyn GeneratorFactory, +    ); +    ret.insert( +        "dahdsr".to_string(), +        &self::adsr::Factory as &dyn GeneratorFactory, +    );      ret  } diff --git a/src/synth/noise.rs b/src/synth/noise.rs index 850b75b..765d17e 100644 --- a/src/synth/noise.rs +++ b/src/synth/noise.rs @@ -1,7 +1,10 @@ +use super::{ +    FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, Parameters, Rate, +    SampleBuffer, +};  use std::mem; -use super::*; -use ::rand::{XorShiftRng, Rng, SeedableRng}; +use ::rand::{Rng, SeedableRng, XorShiftRng};  #[derive(Debug)]  pub struct Noise { @@ -19,7 +22,9 @@ impl Generator for Noise {          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } diff --git a/src/synth/param.rs b/src/synth/param.rs index 602be1d..dd3ecb8 100644 --- a/src/synth/param.rs +++ b/src/synth/param.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ +    mem, FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, ParamValue, +    Parameters, Sample, SampleBuffer, +};  #[derive(Debug)]  pub struct Param { @@ -9,10 +12,13 @@ pub struct Param {  impl Generator for Param {      fn eval<'a>(&'a mut self, params: &Parameters) -> &'a SampleBuffer { -        self.buf.set(*params.vars.get(&self.name).unwrap_or(&self.default)); +        self.buf +            .set(*params.vars.get(&self.name).unwrap_or(&self.default)); +        &self.buf +    } +    fn buffer(&self) -> &SampleBuffer {          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -24,7 +30,9 @@ impl GeneratorFactory for ParamFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Param {              name: params.get_req_param("name", 0)?.as_string()?, -            default: params.get_param("default", 1, &mut ParamValue::Float(0.0)).as_f32()?, +            default: params +                .get_param("default", 1, &mut ParamValue::Float(0.0)) +                .as_f32()?,              buf: SampleBuffer::new(1),          }))      } diff --git a/src/synth/rel.rs b/src/synth/rel.rs index d2fbb70..93b0cd1 100644 --- a/src/synth/rel.rs +++ b/src/synth/rel.rs @@ -1,5 +1,8 @@ +use super::{ +    FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, ParamKind, ParamValue, +    Parameters, Rate, SampleBuffer, +};  use std::{cmp, mem}; -use super::*;  #[derive(Debug)]  pub enum RelOp { @@ -97,28 +100,32 @@ impl Generator for Rel {                          0.0                      };                  } -            }, +            }              Rate::Control => {                  let val = left_buf.first();                  let thres = right_buf.first(); -                self.buf.set(if match self.op { -                    RelOp::Greater => val > thres, -                    RelOp::GreaterEqual => val >= thres, -                    RelOp::Equal => val == thres, -                    RelOp::NotEqual => val != thres, -                    RelOp::LessEqual => val <= thres, -                    RelOp::Less => val < thres, -                } { -                    1.0 -                } else { -                    0.0 -                }); -            }, +                self.buf.set( +                    if match self.op { +                        RelOp::Greater => val > thres, +                        RelOp::GreaterEqual => val >= thres, +                        RelOp::Equal => val == thres, +                        RelOp::NotEqual => val != thres, +                        RelOp::LessEqual => val <= thres, +                        RelOp::Less => val < thres, +                    } { +                        1.0 +                    } else { +                        0.0 +                    }, +                ); +            }          }          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } diff --git a/src/synth/saw.rs b/src/synth/saw.rs index 3e30ca6..5c36cc1 100644 --- a/src/synth/saw.rs +++ b/src/synth/saw.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ +    mem, FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, ParamValue, +    Parameters, Rate, SampleBuffer, +};  #[derive(Debug)]  pub struct Saw { @@ -19,7 +22,9 @@ impl Generator for Saw {          self.phase = (self.phase + pvel * (self.buf.len() as f32)) % 1.0;          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -31,7 +36,9 @@ impl GeneratorFactory for SawFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Saw {              freq: params.remove_param("freq", 0)?.into_gen()?, -            phase: params.get_param("phase", 1, &mut ParamValue::Float(0.0)).as_f32()?, +            phase: params +                .get_param("phase", 1, &mut ParamValue::Float(0.0)) +                .as_f32()?,              buf: SampleBuffer::new(params.env.default_buffer_size),          }))      } diff --git a/src/synth/sine.rs b/src/synth/sine.rs index 4476d4a..3be79db 100644 --- a/src/synth/sine.rs +++ b/src/synth/sine.rs @@ -1,5 +1,8 @@ +use super::{ +    mem, FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, ParamValue, +    Parameters, Rate, SampleBuffer, +};  use std::f32::consts::PI; -use super::*;  const TAU: f32 = 2f32 * PI; @@ -22,7 +25,9 @@ impl Generator for Sine {          self.phase = (self.phase + pvel * (self.buf.len() as f32)) % TAU;          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -34,7 +39,9 @@ impl GeneratorFactory for SineFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Sine {              freq: params.remove_param("freq", 0)?.into_gen()?, -            phase: params.get_param("phase", 1, &mut ParamValue::Float(0.0)).as_f32()?, +            phase: params +                .get_param("phase", 1, &mut ParamValue::Float(0.0)) +                .as_f32()?,              buf: SampleBuffer::new(params.env.default_buffer_size),          }))      } diff --git a/src/synth/square.rs b/src/synth/square.rs index 4b01e07..ef49020 100644 --- a/src/synth/square.rs +++ b/src/synth/square.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ +    mem, FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, ParamValue, +    Parameters, Rate, SampleBuffer, +};  #[derive(Debug)]  pub struct Square { @@ -23,7 +26,9 @@ impl Generator for Square {          self.phase = (self.phase + pvel * (self.buf.len() as f32)) % 1.0;          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -35,7 +40,9 @@ impl GeneratorFactory for SquareFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Square {              freq: params.remove_param("freq", 0)?.into_gen()?, -            phase: params.get_param("phase", 1, &mut ParamValue::Float(0.0)).as_f32()?, +            phase: params +                .get_param("phase", 1, &mut ParamValue::Float(0.0)) +                .as_f32()?,              buf: SampleBuffer::new(params.env.default_buffer_size),          }))      } diff --git a/src/synth/triangle.rs b/src/synth/triangle.rs index 944c539..7d88ec1 100644 --- a/src/synth/triangle.rs +++ b/src/synth/triangle.rs @@ -1,5 +1,8 @@ +use super::{ +    FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, ParamValue, +    Parameters, Rate, SampleBuffer, +};  use std::mem; -use super::*;  #[derive(Debug)]  pub struct Triangle { @@ -27,7 +30,9 @@ impl Generator for Triangle {          self.phase = (self.phase + pvel * (self.buf.len() as f32)) % 1.0;          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -39,7 +44,9 @@ impl GeneratorFactory for TriangleFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {          Ok(Box::new(Triangle {              freq: params.remove_param("freq", 0)?.into_gen()?, -            phase: params.get_param("phase", 1, &mut ParamValue::Float(0.0)).as_f32()?, +            phase: params +                .get_param("phase", 1, &mut ParamValue::Float(0.0)) +                .as_f32()?,              buf: SampleBuffer::new(params.env.default_buffer_size),          }))      } diff --git a/src/synth/util.rs b/src/synth/util.rs index 5bde721..16d6f7f 100644 --- a/src/synth/util.rs +++ b/src/synth/util.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ +    mem, FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, Parameters, Rate, +    SampleBuffer, +};  #[derive(Debug)]  pub struct ControlRate { @@ -9,7 +12,10 @@ pub struct ControlRate {  impl ControlRate {      pub fn new(mut gen: GenBox) -> ControlRate {          gen.set_buffer(SampleBuffer::new(1)); -        ControlRate { value: gen, buf: SampleBuffer::new(1) } +        ControlRate { +            value: gen, +            buf: SampleBuffer::new(1), +        }      }  } @@ -19,15 +25,21 @@ impl Generator for ControlRate {          self.buf.update_from(self.value.eval(params));          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } -    fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer { mem::replace(&mut self.buf, buf) } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    } +    fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer { +        mem::replace(&mut self.buf, buf) +    }  }  pub struct ControlRateFactory;  impl GeneratorFactory for ControlRateFactory {      fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> { -        Ok(Box::new(ControlRate::new(params.remove_param("gen", 0)?.into_gen()?))) +        Ok(Box::new(ControlRate::new( +            params.remove_param("gen", 0)?.into_gen()?, +        )))      }  } @@ -43,7 +55,9 @@ impl Generator for SampleRate {          self.buf.set(params.env.sample_rate);          &self.buf      } -    fn buffer(&self) -> &SampleBuffer { &self.buf } +    fn buffer(&self) -> &SampleBuffer { +        &self.buf +    }      fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {          mem::replace(&mut self.buf, buf)      } @@ -52,8 +66,10 @@ impl Generator for SampleRate {  pub struct SampleRateFactory;  impl GeneratorFactory for SampleRateFactory { -    fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> { -        Ok(Box::new(SampleRate { buf: SampleBuffer::new(1) })) +    fn new(&self, _params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> { +        Ok(Box::new(SampleRate { +            buf: SampleBuffer::new(1), +        }))      }  } diff --git a/src/types.rs b/src/types.rs index b54eb42..ddef51e 100644 --- a/src/types.rs +++ b/src/types.rs @@ -10,18 +10,20 @@ impl Pitch {      pub fn to_midi(&self) -> f32 {          match *self {              Pitch::MIDI(x) => x, -            Pitch::Freq(x) =>  -                12.0 * (x / 440.0).log2() + 69.0, +            Pitch::Freq(x) => 12.0 * (x / 440.0).log2() + 69.0,          }      } -    pub fn to_midi_pitch(&self) -> Pitch { Pitch::MIDI(self.to_midi()) } +    pub fn to_midi_pitch(&self) -> Pitch { +        Pitch::MIDI(self.to_midi()) +    }      pub fn to_freq(&self) -> f32 {          match *self { -            Pitch::MIDI(x) => -                440.0 * (2.0f32).powf((x - 69.0) / 12.0), +            Pitch::MIDI(x) => 440.0 * (2.0f32).powf((x - 69.0) / 12.0),              Pitch::Freq(x) => x,          }      } -    pub fn to_freq_pitch(&self) -> Pitch { Pitch::Freq(self.to_freq()) } +    pub fn to_freq_pitch(&self) -> Pitch { +        Pitch::Freq(self.to_freq()) +    }  } | 
