Class definition file FIR.cpp Next  |  Prev  |  Up  |  Top  |  Index  |  JOS Index  |  JOS Pubs  |  JOS Home  |  Search

Class definition file FIR.cpp

#include "FIR.h"

#include <string.h>

FIR :: FIR(int theLength) : Object()
{
  length = theLength;
  coeffs = (MY_FLOAT *) malloc(length * sizeof(MY_FLOAT));
  pastInputs = (MY_FLOAT *) calloc(2*length, sizeof(MY_FLOAT));
  piOffset = length;
  strcpy(name,"FIR Filter");
}

FIR :: FIR(const char *filterFile) : Object()
{
  FILE *fp;
  float d;
  int rtn,i;
  strncpy(name,filterFile,strlen(name));
  fp = fopen(filterFile,"r");
  if (!fp)   {
    char nfn[1000];
    // char nfn[strlen(FILTER_DIR) + strlen(filterFile) + 1];
    strcpy(nfn,FILTER_DIR);
    strcat(nfn,filterFile);
    printf("Couldn't find soundfile %s. Trying %s\n",filterFile,nfn);
    fp = fopen(nfn,"r");
    if (!fp)   {
      printf("Couldn't find filterfile %s or %s!\n",filterFile,nfn);
      exit(-1);
    }
  }
  rtn = fscanf(fp,"%f",&d);
  if (rtn == EOF)
    goto error;
  delay = (MY_FLOAT) d;
  rtn = fscanf(fp,"%f",&d);
  if (rtn == EOF)
    goto error;
  length = (int)d;
  coeffs = (MY_FLOAT *) malloc(length * sizeof(MY_FLOAT));
  pastInputs = (MY_FLOAT *) calloc(2*length, sizeof(MY_FLOAT));
  for (i=0;i<length;i++) {
    rtn = fscanf(fp,"%f",&d);
    if (rtn == EOF)
      goto error;
    coeffs[i] = (MY_FLOAT)d;
  }
  piOffset = length;
  return;
error: 
  fprintf(stderr,"Premature EOF or bad numbers in filter file %s\n",
          filterFile);
  exit(-1);
}

FIR :: ~FIR()
{
  free(pastInputs);
  free(coeffs);
}

void FIR :: clear()
{
  int i;
  for (i=0; i < 2*length; i++) {
    pastInputs[i] = 0;
  }
  piOffset = length;
}

void FIR :: setCoeffs(MY_FLOAT *theCoeffs)
{
  int i;
  for (i=0; i < length; i++) {
    coeffs[i] = theCoeffs[i];
  }
}

MY_FLOAT FIR :: tick(MY_FLOAT input) {
  int i;
  lastOutput = input*coeffs[0];
  for (i=1; i<length; i++)
    lastOutput += coeffs[i] * pastInputs[piOffset-i]; 
    // sample 0 unused
  pastInputs[piOffset++] = input;
  if (piOffset >= 2*length) { // sample 2*length-1 unused
    piOffset = length;
    for (i=0; i<length; i++)
      pastInputs[i] = pastInputs[length+i];
  }
  return lastOutput;
}


MY_FLOAT FIR :: getDelay(MY_FLOAT freq)
{
  return delay;
}

int FIR :: getLength(void)
{
  return length;
}

char * FIR :: getName(void)
{
  return name;
}

void FIR :: setName(char *theName)
{
  strncpy(name,theName,strlen(name));
}


Next  |  Prev  |  Up  |  Top  |  Index  |  JOS Index  |  JOS Pubs  |  JOS Home  |  Search

[How to cite this work] [Order a printed hardcopy]

``Introduction to Digital Filters with Audio Applications'', by Julius O. Smith III, (August 2006 Edition).
Copyright © 2007-02-02 by Julius O. Smith III
Center for Computer Research in Music and Acoustics (CCRMA),   Stanford University
CCRMA  [Automatic-links disclaimer]