Пример #1
0
H2_3D_Tree::H2_3D_Tree(doft *dof, double L, int level, int n,  double epsilon, int use_chebyshev){
    this->dof   =   dof;
    this->L     =   L;
    this->level =   level;
    this->n    =   n;
    this->epsilon   =   epsilon;
    this->use_chebyshev = use_chebyshev;
    alpha = 0;
    n2 = n*n;         // n2 = n^2
	n3 = n2*n;       // n3 = n^3
	dofn3_s = dof->s * n3;
	dofn3_f = dof->f * n3;
    
    // Omega matrix
	Kweights = (double *)malloc(n3 * sizeof(double));    
	// Chebyshev interpolation coefficients: Sn (page 8715)
	Cweights = (double *)malloc(2 * n2 * sizeof(double));
    Tkz      = (double *)malloc(n2 * sizeof(double));
    K       =   NULL;
    U       =   NULL;
    VT      =   NULL;
    tree    =   NULL;
    skipLevel = 0;
    computed   =   false;
    
    int fftSize = (int)round(pow(2*n-1, 3));
	p_r2c = rfftw_create_plan(fftSize, FFTW_REAL_TO_COMPLEX,
                                         FFTW_ESTIMATE);
	p_c2r = rfftw_create_plan(fftSize, FFTW_COMPLEX_TO_REAL,
                                         FFTW_ESTIMATE);
}
Пример #2
0
inline void impulse2freq(int id, float *imp, unsigned int length, fftw_real *out)
{
  fftw_real impulse_time[MAX_FFT_LENGTH];
#ifdef FFTW3
  fft_plan tmp_plan;
#endif
  unsigned int i, fftl = 128;

  while (fftl < length+SEG_LENGTH) {
          fftl *= 2;
  }

  fft_length[id] = fftl;
#ifdef FFTW3
  plan_rc[id] = fftwf_plan_r2r_1d(fftl, real_in, comp_out, FFTW_R2HC, FFTW_MEASURE);
  plan_cr[id] = fftwf_plan_r2r_1d(fftl, comp_in, real_out, FFTW_HC2R, FFTW_MEASURE);
  tmp_plan = fftwf_plan_r2r_1d(fftl, impulse_time, out, FFTW_R2HC, FFTW_MEASURE);
#else
  plan_rc[id] = rfftw_create_plan(fftl, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE);
  plan_cr[id] = rfftw_create_plan(fftl, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE);
#endif

  for (i=0; i<length; i++) {
    impulse_time[i] = imp[i];
  }
  for (; i<fftl; i++) {
    impulse_time[i] = 0.0f;
  }
#ifdef FFTW3
  fftwf_execute(tmp_plan);
  fftwf_destroy_plan(tmp_plan);
#else
  rfftw_one(plan_rc[id], impulse_time, out);
#endif
}
Пример #3
0
FFTwrapper::FFTwrapper(int fftsize_){
    fftsize=fftsize_;
    tmpfftdata1=new fftw_real[fftsize];
    tmpfftdata2=new fftw_real[fftsize];
#ifdef FFTW_VERSION_2
    planfftw=rfftw_create_plan(fftsize,FFTW_REAL_TO_COMPLEX,FFTW_ESTIMATE|FFTW_IN_PLACE);
    planfftw_inv=rfftw_create_plan(fftsize,FFTW_COMPLEX_TO_REAL,FFTW_ESTIMATE|FFTW_IN_PLACE);
#else
    planfftw=fftwf_plan_r2r_1d(fftsize,tmpfftdata1,tmpfftdata1,FFTW_R2HC,FFTW_ESTIMATE);
    planfftw_inv=fftwf_plan_r2r_1d(fftsize,tmpfftdata2,tmpfftdata2,FFTW_HC2R,FFTW_ESTIMATE);
#endif
};
Пример #4
0
int
padsynth_init(void)
{
    global.padsynth_table_size = -1;
    global.padsynth_outfreqs = NULL;
    global.padsynth_outsamples = NULL;
    global.padsynth_fft_plan = NULL;
    global.padsynth_ifft_plan = NULL;

    /* allocate input FFT buffer */
    global.padsynth_inbuf = (float *)fftwf_malloc(WAVETABLE_POINTS * sizeof(float));
    if (!global.padsynth_inbuf) {
        return 0;
    }

    /* create input FFTW plan */
#ifdef FFTW_VERSION_2
    global.padsynth_fft_plan  = (void *)rfftw_create_plan(WAVETABLE_POINTS,
                                                          FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE);
#else
    global.padsynth_fft_plan  = (void *)fftwf_plan_r2r_1d(WAVETABLE_POINTS,
                                                          global.padsynth_inbuf,
                                                          global.padsynth_inbuf,
                                                          FFTW_R2HC, FFTW_ESTIMATE);
#endif
    if (!global.padsynth_fft_plan) {
        padsynth_fini();
        return 0;
    }

    return 1;
}
Пример #5
0
void F77_FUNC_(rfftw_f77_create_plan,RFFTW_F77_CREATE_PLAN)
(fftw_plan *p, int *n, int *idir, int *flags)
{
     fftw_direction dir = *idir < 0 ? FFTW_FORWARD : FFTW_BACKWARD;

     *p = rfftw_create_plan(*n,dir,*flags);
}
Пример #6
0
/*
 * Class:     jfftw_real_Plan
 * Method:    createPlan
 * Signature: (III)V
 */
JNIEXPORT void JNICALL Java_jfftw_real_Plan_createPlan( JNIEnv *env, jobject obj, jint n, jint dir, jint flags )
{
	jclass clazz;
	jfieldID id;
	jbyteArray arr;
	unsigned char* carr;

	if( sizeof( jdouble ) != sizeof( fftw_real ) )
	{
		(*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/RuntimeException" ), "jdouble and fftw_real are incompatible" );
		return;
	}

	clazz = (*env)->GetObjectClass( env, obj );
	id    = (*env)->GetFieldID( env, clazz, "plan", "[B" );
	arr   = (*env)->NewByteArray( env, sizeof( rfftw_plan ) );
	carr  = (*env)->GetByteArrayElements( env, arr, 0 );

	(*env)->MonitorEnter( env, (*env)->FindClass( env, "jfftw/Plan" ) );

	*(rfftw_plan*)carr = rfftw_create_plan( n, dir, flags );

	(*env)->MonitorExit( env, (*env)->FindClass( env, "jfftw/Plan" ) );

	(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
	(*env)->SetObjectField( env, obj, id, arr );
}
Пример #7
0
	OneDataMultiplierMHT::OneDataMultiplierMHT(double AFreq, int dataBySecond, double rep, double win_factor, int minHT, int maxHT)
	: m_rep(int(rep))
	{
		int nbHT = maxHT - minHT + 1;
		m_components.resize(nbHT);
		m_convolutions.resize(nbHT);

		for(int h=minHT; h<=maxHT; h++)
			m_convolutions[h-minHT] = new SingleHalfTone(AFreq, dataBySecond, rep, win_factor, h);

		//	m_length = int(dataBySecond * 1.0/h2f(minHT, AFreq));
		m_length = int(rep/FACTOR * dataBySecond * 1.0/h2f(minHT, AFreq));
		m_size = int(rep * dataBySecond * 1.0/h2f(minHT, AFreq));

		m_fwd_plan = rfftw_create_plan(m_size, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE | FFTW_OUT_OF_PLACE | FFTW_USE_WISDOM);
		m_bck_plan = rfftw_create_plan(m_size, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE | FFTW_OUT_OF_PLACE | FFTW_USE_WISDOM);
		m_in = new fftw_real[m_size];
		m_out = new fftw_real[m_size];
	}
Пример #8
0
int main(int argc, char** argv) {

  fftw_real out[N], in[N];
  rfftw_plan plan_backward;
  buffer_t buffer[N];

  int i, time = 0;

  song_t* head;
  song_t* next;

  print_prologoue(N, SR);

  next = head = read_song("song.txt");
  dump_song(head);
  plan_backward = rfftw_create_plan(N, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE);

  while ( next ) {

	// clear out
	for ( i = 0; i < N; i++ )
		out[i] =  0.0f;

	i = 0;
	while (i < ACCORD_SIZE && next->accord[i] != 0)
	  play_note(next->accord[i++], ADSR(time, next->duration), out);

	rfftw_one(plan_backward, out, in);

	for ( i = 0; i < N; i++ )
	  buffer[i] = limit_output(in[i]);;

  	write(1, buffer, N* sizeof(buffer_t));

	time ++;
	if ( time == next->duration ) {
	  // play next note

	  next = next->next;
	  time = 0;

	  // loop:
	  if (next == NULL) next = head;
	}
  }

  rfftw_destroy_plan(plan_backward);
  free_song(head);
  print_epilogue();
  return 0;
}
void test_speed_aux(int n, fftw_direction dir, int flags, int specific)
{
     fftw_real *in, *out;
     fftw_plan plan;
     double t;
     fftw_time begin, end;

     in = (fftw_real *) fftw_malloc(n * howmany_fields
				    * sizeof(fftw_real));
     out = (fftw_real *) fftw_malloc(n * howmany_fields
				     * sizeof(fftw_real));

     if (specific) {
	  begin = fftw_get_time();
	  plan = rfftw_create_plan_specific(n, dir,
					    speed_flag | flags
					    | wisdom_flag | no_vector_flag,
					    in, howmany_fields,
					    out, howmany_fields);
	  end = fftw_get_time();
     } else {
	  begin = fftw_get_time();
	  plan = rfftw_create_plan(n, dir, speed_flag | flags 
				   | wisdom_flag | no_vector_flag);
	  end = fftw_get_time();
     }
     CHECK(plan != NULL, "can't create plan");

     t = fftw_time_to_sec(fftw_time_diff(end, begin));
     WHEN_VERBOSE(2, printf("time for planner: %f s\n", t));

     WHEN_VERBOSE(2, rfftw_print_plan(plan));

     FFTW_TIME_FFT(rfftw(plan, howmany_fields,
			 in, howmany_fields, 1, out, howmany_fields, 1),
		   in, n * howmany_fields, t);

     rfftw_destroy_plan(plan);

     WHEN_VERBOSE(1, printf("time for one fft: %s", smart_sprint_time(t)));
     WHEN_VERBOSE(1, printf(" (%s/point)\n", smart_sprint_time(t / n)));
     WHEN_VERBOSE(1, printf("\"mflops\" = 5/2 (n log2 n) / (t in microseconds)"
			" = %f\n", 0.5 * howmany_fields * mflops(t, n)));

     fftw_free(in);
     fftw_free(out);

     WHEN_VERBOSE(1, printf("\n"));
}
Пример #10
0
int main(void) {

  fftw_real out[N], in[N];
  rfftw_plan plan_backward;
  buffer_t buffer[N];

  int i, rd;
  long bytes = 0;

  plan_backward = rfftw_create_plan(N, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE);

  print_prologoue(N, SR);

  while ( 1 ) {

	out[0] = 0.0;
	for ( i = 1; i < N/2; i++ ) {
	  if ( i % F_BASE == 0 ){
		out[i] = out[N-i] = N * exp(-10*i/N) / 5.0;
	  }
	  else {
		out[i] = out[N-i] = 0.0f;
	  }
	}

	
	rfftw_one(plan_backward, out, in);

	for ( i = 0; i < N; i++ ) 
	  buffer[i] = in[i]/N;

  	rd = write(1, buffer, N* sizeof(buffer_t));
	bytes += rd;
  }

  rfftw_destroy_plan(plan_backward);

  print_epilogue();

  return 0;
}
Пример #11
0
int
gmx_fft_init_1d_real(gmx_fft_t *        pfft,
                     int                nx,
                     enum gmx_fft_flag  flags) 
{
    int i,j;
    gmx_fft_t             fft;
    int                    fftw_flags;
    
    /* FFTW2 is slow to measure, so we do not use it */
    /* If you change this, add an #ifndef for GMX_DISABLE_FFTW_MEASURE around it! */
    fftw_flags = FFTW_ESTIMATE;    
    
    if(pfft==NULL)
    {
        gmx_fatal(FARGS,"Invalid opaque FFT datatype pointer.");
        return EINVAL;
    }
    *pfft = NULL;

    if( (fft = (gmx_fft_t)malloc(sizeof(struct gmx_fft))) == NULL)
    {
        return ENOMEM;
    }    
 
 
    fft->single[0][0] = rfftw_create_plan(nx,FFTW_COMPLEX_TO_REAL,FFTW_OUT_OF_PLACE|fftw_flags);
    fft->single[0][1] = rfftw_create_plan(nx,FFTW_REAL_TO_COMPLEX,FFTW_OUT_OF_PLACE|fftw_flags);
    fft->single[1][0] = rfftw_create_plan(nx,FFTW_COMPLEX_TO_REAL,FFTW_IN_PLACE|fftw_flags);
    fft->single[1][1] = rfftw_create_plan(nx,FFTW_REAL_TO_COMPLEX,FFTW_IN_PLACE|fftw_flags);

    
    fft->multi[0][0] = NULL;
    fft->multi[0][1] = NULL;
    fft->multi[1][0] = NULL;
    fft->multi[1][1] = NULL;
    
    for(i=0;i<2;i++)
    {
        for(j=0;j<2;j++)
        {
            if(fft->single[i][j] == NULL)
            {
                gmx_fatal(FARGS,"Error initializing FFTW2 plan.");
                gmx_fft_destroy(fft);
                return -1;
            }        
        }
    }
    
    /* FFTW2 overwrites the input when doing out-of-place complex-to-real FFTs.
     * This is not acceptable for the Gromacs interface, so we define a
     * work array and copy the data there before doing complex-to-real FFTs.
     */
    fft->work = (real *)malloc(sizeof(real)*( (nx/2 + 1)*2) );
    if(fft->work == NULL)
    {
        gmx_fatal(FARGS,"Cannot allocate complex-to-real FFT workspace.");
        gmx_fft_destroy(fft);
        return ENOMEM;
    }
    
    fft->ndim = 1;
    fft->nx   = nx;
  
    *pfft = fft;
    return 0;
}
Пример #12
0
static LADSPA_Handle instantiateMbeq(
 const LADSPA_Descriptor *descriptor,
 unsigned long s_rate) {
	Mbeq *plugin_data = (Mbeq *)malloc(sizeof(Mbeq));
	int *bin_base = NULL;
	float *bin_delta = NULL;
	fftw_real *comp = NULL;
	float *db_table = NULL;
	long fifo_pos;
	LADSPA_Data *in_fifo = NULL;
	LADSPA_Data *out_accum = NULL;
	LADSPA_Data *out_fifo = NULL;
	fftw_real *real = NULL;
	float *window = NULL;

#line 52 "mbeq_1197.xml"
	int i, bin;
	float last_bin, next_bin;
	float db;
	float hz_per_bin = (float)s_rate / (float)FFT_LENGTH;
	
	in_fifo = calloc(FFT_LENGTH, sizeof(LADSPA_Data));
	out_fifo = calloc(FFT_LENGTH, sizeof(LADSPA_Data));
	out_accum = calloc(FFT_LENGTH * 2, sizeof(LADSPA_Data));
	real = calloc(FFT_LENGTH, sizeof(fftw_real));
	comp = calloc(FFT_LENGTH, sizeof(fftw_real));
	window = calloc(FFT_LENGTH, sizeof(float));
	bin_base = calloc(FFT_LENGTH/2, sizeof(int));
	bin_delta = calloc(FFT_LENGTH/2, sizeof(float));
	fifo_pos = 0;
	
	#ifdef FFTW3
	plan_rc = fftwf_plan_r2r_1d(FFT_LENGTH, real, comp, FFTW_R2HC, FFTW_MEASURE);
	plan_cr = fftwf_plan_r2r_1d(FFT_LENGTH, comp, real, FFTW_HC2R, FFTW_MEASURE);
	#else
	plan_rc = rfftw_create_plan(FFT_LENGTH, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE);
	plan_cr = rfftw_create_plan(FFT_LENGTH, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE);
	#endif
	
	// Create raised cosine window table
	for (i=0; i < FFT_LENGTH; i++) {
	        window[i] = -0.5f*cos(2.0f*M_PI*(double)i/(double)FFT_LENGTH)+0.5f;
	}
	
	// Create db->coeffiecnt lookup table
	db_table = malloc(1000 * sizeof(float));
	for (i=0; i < 1000; i++) {
	        db = ((float)i/10) - 70;
	        db_table[i] = pow(10.0f, db/20.0f);
	}
	
	// Create FFT bin -> band + delta tables
	bin = 0;
	while (bin <= bands[0]/hz_per_bin) {
	        bin_base[bin] = 0;
	        bin_delta[bin++] = 0.0f;
	}
	for (i = 1; 1 < BANDS-1 && bin < (FFT_LENGTH/2)-1 && bands[i+1] < s_rate/2; i++) {
	        last_bin = bin;
	        next_bin = (bands[i+1])/hz_per_bin;
	        while (bin <= next_bin) {
	                bin_base[bin] = i;
	                bin_delta[bin] = (float)(bin - last_bin) / (float)(next_bin - last_bin);
	                bin++;
	        }
	}
	for (; bin < (FFT_LENGTH/2); bin++) {
	        bin_base[bin] = BANDS-1;
	        bin_delta[bin] = 0.0f;
	}

	plugin_data->bin_base = bin_base;
	plugin_data->bin_delta = bin_delta;
	plugin_data->comp = comp;
	plugin_data->db_table = db_table;
	plugin_data->fifo_pos = fifo_pos;
	plugin_data->in_fifo = in_fifo;
	plugin_data->out_accum = out_accum;
	plugin_data->out_fifo = out_fifo;
	plugin_data->real = real;
	plugin_data->window = window;

	return (LADSPA_Handle)plugin_data;
}
Пример #13
0
int main (int argc, char** argv)
{
  extern int abs_flg; /* flag for absolute/relative cutoff  */
  extern double adj_pitch;
  extern double pitch_shift;
  extern int n_pitch;

  char *file_midi = NULL;
  char *file_wav = NULL;
  char *file_patch = NULL;

  int i;

  // default value
  double cut_ratio; // log10 of cutoff ratio for scale velocity
  cut_ratio = -5.0;
  double rel_cut_ratio; // log10 of cutoff ratio relative to average
  rel_cut_ratio = 1.0; // this value is ignored when abs_flg == 1
  long len = 2048;
  int flag_window = 3; // hanning window
  /* for 76 keys piano  */
  int notetop = 103; /* G8  */
  int notelow = 28; /* E2  */

  abs_flg = 1;

  long hop = 0;
  int show_help = 0;
  int show_version = 0;
  adj_pitch = 0.0;
  /* to select peaks in a note  */
  int peak_threshold = 128; /* this means no peak search  */

  int flag_phase = 1; // use the phase correction
  int psub_n = 0;
  double psub_f = 0.0;
  double oct_f = 0.0;
  for (i = 1; i < argc; i++)
    {
      if ((strcmp (argv[i], "-input" ) == 0)
	 || (strcmp (argv[i], "-i" ) == 0))
	{
	  if ( i+1 < argc )
	    {
	      file_wav = (char *)malloc (sizeof (char)
					 * (strlen (argv[++i]) + 1));
	      CHECK_MALLOC (file_wav, "main");
	      strcpy (file_wav, argv[i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "-output" ) == 0)
	      || (strcmp (argv[i], "-o" ) == 0))
	{
	  if ( i+1 < argc )
	    {
	      file_midi = (char *)malloc (sizeof (char)
					 * (strlen (argv[++i]) + 1));
	      CHECK_MALLOC (file_midi, "main");
	      strcpy (file_midi, argv[i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--cutoff") == 0)
	       || (strcmp (argv[i], "-c") == 0))
	{
	  if ( i+1 < argc )
	    {
	      cut_ratio = atof (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--top") == 0)
	       || (strcmp (argv[i], "-t") == 0))
	{
	  if ( i+1 < argc )
	    {
	      notetop = atoi( argv[++i] );
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--bottom") == 0)
	       || (strcmp (argv[i], "-b") == 0))
	{
	  if ( i+1 < argc )
	    {
	      notelow = atoi (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--window") == 0)
	       || (strcmp (argv[i], "-w") == 0))
	{
	  if ( i+1 < argc )
	    {
	      flag_window = atoi (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ( strcmp (argv[i], "-n") == 0)
	{
	  if ( i+1 < argc )
	    {
	      len = atoi (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--shift") == 0)
	       || (strcmp (argv[i], "-s") == 0))
	{
	  if ( i+1 < argc )
	    {
	      hop = atoi (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--patch") == 0)
	       || (strcmp (argv[i], "-p") == 0))
	{
	  if ( i+1 < argc )
	    {
	      file_patch = argv[++i];
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--relative") == 0)
	       || (strcmp (argv[i], "-r") == 0))
	{
	  if ( i+1 < argc )
	    {
	      rel_cut_ratio = atof (argv[++i]);
	      abs_flg = 0;
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--peak") == 0)
	       || (strcmp (argv[i], "-k") == 0))
	{
	  if ( i+1 < argc )
	    {
	      peak_threshold = atoi (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--adjust") == 0)
	       || (strcmp (argv[i], "-a") == 0))
	{
	  if ( i+1 < argc )
	    {
	      adj_pitch = atof (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if ((strcmp (argv[i], "--help") == 0)
	       || (strcmp (argv[i], "-h") == 0))
	{
	  show_help = 1;
	  break;
	}
      else if (strcmp (argv[i], "-nophase") == 0)
	{
	  flag_phase = 0;
	}
      else if (strcmp (argv[i], "-psub-n") == 0)
	{
	  if ( i+1 < argc )
	    {
	      psub_n = atoi (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if (strcmp (argv[i], "-psub-f") == 0)
	{
	  if ( i+1 < argc )
	    {
	      psub_f = atof (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if (strcmp (argv[i], "-oct") == 0)
	{
	  if ( i+1 < argc )
	    {
	      oct_f = atof (argv[++i]);
	    }
	  else
	    {
	      show_help = 1;
	      break;
	    }
	}
      else if (strcmp (argv[i], "-v") == 0 ||
	       strcmp (argv[i], "--version") == 0)
	{
	  show_version = 1;
	}
      else
	{
	  show_help = 1;
	}
    }
  if (show_help == 1)
    {
      print_usage (argv[0]);
      exit (1);
    }
  else if (show_version == 1)
    {
      print_version ();
      exit (1);
    }

  if (flag_window < 0 || flag_window > 6)
    {
      flag_window = 0;
    }
  if (hop == 0)
    {
      hop = len / 4;
    }
  if (psub_n == 0) psub_f = 0.0;
  if (psub_f == 0.0) psub_n = 0;


  struct WAON_notes *notes = WAON_notes_init();
  CHECK_MALLOC (notes, "main");
  char vel[128];     // velocity at the current step
  int on_event[128]; // event index of struct WAON_notes.
  for (i = 0; i < 128; i ++)
    {
      vel[i]      = 0;
      on_event[i] = -1;
    }

  // allocate buffers
  double *left  = (double *)malloc (sizeof (double) * len);
  double *right = (double *)malloc (sizeof (double) * len);
  CHECK_MALLOC (left,  "main");
  CHECK_MALLOC (right, "main");

  double *x = NULL; /* wave data for FFT  */
  double *y = NULL; /* spectrum data for FFT */ 
#ifdef FFTW2
  x = (double *)malloc (sizeof (double) * len);
  y = (double *)malloc (sizeof (double) * len);
#else // FFTW3
  x = (double *)fftw_malloc (sizeof (double) * len);
  y = (double *)fftw_malloc (sizeof (double) * len);
#endif // FFTW2
  CHECK_MALLOC (x, "main");
  CHECK_MALLOC (y, "main");

  /* power spectrum  */
  double *p = (double *)malloc (sizeof (double) * (len / 2 + 1));
  CHECK_MALLOC (p, "main");

  double *p0 = NULL;
  double *dphi = NULL;
  double *ph0 = NULL;
  double *ph1 = NULL;
  if (flag_phase != 0)
    {
      p0 = (double *)malloc (sizeof (double) * (len / 2 + 1));
      CHECK_MALLOC (p0, "main");

      dphi = (double *)malloc (sizeof (double) * (len / 2 + 1));
      CHECK_MALLOC (dphi, "main");

      ph0 = (double *)malloc (sizeof (double) * (len/2+1));
      ph1 = (double *)malloc (sizeof (double) * (len/2+1));
      CHECK_MALLOC (ph0, "main");
      CHECK_MALLOC (ph1, "main");
    }

  double *pmidi = (double *)malloc (sizeof (double) * 128);
  CHECK_MALLOC (pmidi, "main");


  // MIDI output
  if (file_midi == NULL)
    {
      file_midi = (char *)malloc (sizeof (char) * (strlen("output.mid") + 1));
      CHECK_MALLOC (file_midi, "main");
      strcpy (file_midi, "output.mid");
    }

  // open input wav file
  if (file_wav == NULL)
    {
      file_wav = (char *) malloc (sizeof (char) * 2);
      CHECK_MALLOC (file_wav, "main");
      file_wav [0] = '-';
    }
  SF_INFO sfinfo;
  SNDFILE *sf = sf_open (file_wav, SFM_READ, &sfinfo);
  if (sf == NULL)
    {
      fprintf (stderr, "Can't open input file %s : %s\n",
	       file_wav, strerror (errno));
      exit (1);
    }
  sndfile_print_info (&sfinfo);


  // check stereo or mono
  if (sfinfo.channels != 2 && sfinfo.channels != 1)
    {
      fprintf (stderr, "only mono and stereo inputs are supported.\n");
      exit (1);
    }


  // time-period for FFT (inverse of smallest frequency)
  double t0 = (double)len/(double)sfinfo.samplerate;

  // weight of window function for FFT
  double den = init_den (len, flag_window);

  /* set range to analyse (search notes) */
  /* -- after 't0' is calculated  */
  int i0 = (int)(mid2freq[notelow]*t0 - 0.5);
  int i1 = (int)(mid2freq[notetop]*t0 - 0.5)+1;
  if (i0 <= 0)
    {
      i0 = 1; // i0=0 means DC component (frequency = 0)
    }
  if (i1 >= (len/2))
    {
      i1 = len/2 - 1;
    }

  // init patch
  init_patch (file_patch, len, flag_window);
  /*                      ^^^ len could be given by option separately  */

  // initialization plan for FFTW
#ifdef FFTW2
  rfftw_plan plan;
  plan = rfftw_create_plan (len, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE);
#else // FFTW3
  fftw_plan plan;
  plan = fftw_plan_r2r_1d (len, x, y, FFTW_R2HC, FFTW_ESTIMATE);
#endif

  // for first step
  if (hop != len)
    {
      if (sndfile_read (sf, sfinfo,
			left + hop,
			right + hop,
			(len - hop))
	  != (len - hop))
	{
	  fprintf (stderr, "No Wav Data!\n");
	  exit(0);
	}
    }

  /** main loop (icnt) **/
  pitch_shift = 0.0;
  n_pitch = 0;
  int icnt; /* counter  */
  for (icnt=0; ; icnt++)
    {
      // shift
      for (i = 0; i < len - hop; i ++)
	{
	  if (sfinfo.channels == 2) // stereo
	    {
	      left  [i] = left  [i + hop];
	      right [i] = right [i + hop];
	    }
	  else // mono
	    {
	      left  [i] = left  [i + hop];
	    }
	}
      // read from wav
      if (sndfile_read (sf, sfinfo,
			left  + (len - hop),
			right + (len - hop),
			hop)
	  != hop)
	{
	  fprintf (stderr, "WaoN : end of file.\n");
	  break;
	}

      // set double table x[] for FFT
      for (i = 0; i < len; i ++)
	{
	  if (sfinfo.channels == 2) // stereo
	    {
	      x [i] = 0.5 * (left [i] + right [i]);
	    }
	  else // mono
	    {
	      x [i] = left [i];
	    }
	}

      /**
       * stage 1: calc power spectrum
       */
      windowing (len, x, flag_window, 1.0, x);

      /* FFTW library  */
#ifdef FFTW2
      rfftw_one (plan, x, y);
#else // FFTW3
      fftw_execute (plan); // x[] -> y[]
#endif

      if (flag_phase == 0)
	{
	  // no phase-vocoder correction
	  HC_to_amp2 (len, y, den, p);
	}
      else
	{
	  // with phase-vocoder correction
	  HC_to_polar2 (len, y, 0, den, p, ph1);

	  if (icnt == 0) // first step, so no ph0[] yet
	    {
	      for (i = 0; i < (len/2+1); ++i) // full span
		{
		  // no correction
		  dphi[i] = 0.0;

		  // backup the phase for the next step
		  p0  [i] = p   [i];
		  ph0 [i] = ph1 [i];
		}	  
	    }
	  else // icnt > 0
	    {
	      // freq correction by phase difference
	      for (i = 0; i < (len/2+1); ++i) // full span
		{
		  double twopi = 2.0 * M_PI;
		  //double dphi;
		  dphi[i] = ph1[i] - ph0[i]
		    - twopi * (double)i / (double)len * (double)hop;
		  for (; dphi[i] >= M_PI; dphi[i] -= twopi);
		  for (; dphi[i] < -M_PI; dphi[i] += twopi);

		  // frequency correction
		  // NOTE: freq is (i / len + dphi) * samplerate [Hz]
		  dphi[i] = dphi[i] / twopi / (double)hop;

		  // backup the phase for the next step
		  p0  [i] = p   [i];
		  ph0 [i] = ph1 [i];

		  // then, average the power for the analysis
		  p[i] = 0.5 *(sqrt (p[i]) + sqrt (p0[i]));
		  p[i] = p[i] * p[i];
		}
	    }
	}

      // drum-removal process
      if (psub_n != 0)
	{
	  power_subtract_ave (len, p, psub_n, psub_f);
	}

      // octave-removal process
      if (oct_f != 0.0)
	{
	  power_subtract_octave (len, p, oct_f);
	}

      /**
       * stage 2: pickup notes
       */
      /* new code
      if (flag_phase == 0)
	{
	  average_FFT_into_midi (len, (double)sfinfo.samplerate,
				 p, NULL,
				 pmidi);
	}
      else
	{
	  average_FFT_into_midi (len, (double)sfinfo.samplerate,
				 p, dphi,
				 pmidi);
	}
      pickup_notes (pmidi,
		    cut_ratio, rel_cut_ratio,
		    notelow, notetop,
		    vel);
      */

      /* old code */
      if (flag_phase == 0)
	{
	  // no phase-vocoder correction
	  note_intensity (p, NULL,
			  cut_ratio, rel_cut_ratio, i0, i1, t0, vel);
	}
      else
	{
	  // with phase-vocoder correction
	  // make corrected frequency (i / len + dphi) * samplerate [Hz]
	  for (i = 0; i < (len/2+1); ++i) // full span
	    {
	      dphi[i] = ((double)i / (double)len + dphi[i])
		* (double)sfinfo.samplerate;
	    }
	  note_intensity (p, dphi,
			  cut_ratio, rel_cut_ratio, i0, i1, t0, vel);
	}

      /**
       * stage 3: check previous time for note-on/off
       */
      WAON_notes_check (notes, icnt, vel, on_event,
			8, 0, peak_threshold);
    }


  // clean notes
  WAON_notes_regulate (notes);

  WAON_notes_remove_shortnotes (notes, 1, 64);
  WAON_notes_remove_shortnotes (notes, 2, 28);

  WAON_notes_remove_octaves (notes);


  /*
  pitch_shift /= (double) n_pitch;
  fprintf (stderr, "WaoN : difference of pitch = %f ( + %f )\n",
	   -(pitch_shift - 0.5),
	   adj_pitch);
  */

  /* div is the divisions for one beat (quater-note).
   * here we assume 120 BPM, that is, 1 beat is 0.5 sec.
   * note: (hop / ft->rate) = duration for 1 step (sec) */
  long div = (long)(0.5 * (double)sfinfo.samplerate / (double) hop);
  fprintf (stderr, "division = %ld\n", div);
  fprintf (stderr, "WaoN : # of events = %d\n", notes->n);

  WAON_notes_output_midi (notes, div, file_midi);


#ifdef FFTW2
  rfftw_destroy_plan (plan);
#else
  fftw_destroy_plan (plan);
#endif /* FFTW2 */


  WAON_notes_free (notes);
  free (left);
  free (right);
  free (x);
  free (y);
  free (p);
  if (p0 != NULL) free (p0);
  if (dphi != NULL) free (dphi);
  if (ph0 != NULL) free (ph0);
  if (ph1 != NULL) free (ph1);

  if (pmidi != NULL) free (pmidi);

  if (file_wav  != NULL) free (file_wav);
  if (file_midi != NULL) free (file_midi);

  sf_close (sf);

  return 0;
}
Пример #14
0
int
_fft_init( unsigned long points )
{
	long c;
#ifndef HAVE_FFTW

	unsigned int i = points, k = 1;
	float j;

	while( i > 2 ) {
		if( i & 0x0001 )
			return -1;
		i >>= 1;
		k++;
	}

	nn = points;
	lognn = k;

	if( iout != NULL )
		free( iout );
	if( rout != NULL )
		free( rout );
	if( sintable != NULL )
		free( sintable );
	if( costable != NULL )
		free( costable );
	if( bit_reverse != NULL )
		free( bit_reverse );

	bit_reverse = (int*) xmalloc( sizeof( int ) * nn );
	costable = (double*) xmalloc( sizeof( double ) * nn / 2 );
	sintable = (double*) xmalloc( sizeof( double ) * nn / 2 );

	rout = (double*) xmalloc ( sizeof( double ) * nn );
	iout = (double*) xmalloc ( sizeof( double ) * nn );

	for( i = 0; i < nn; i++ ) {
		bit_reverse[i] = _fft_reverse_bits( i );
	}
	
	for( i = 0; i < nn / 2; i++ ) {
		j = 2 * PI * i / nn;
		costable[i] = cos( j );
		sintable[i] = sin( j );
   	}

#else

	nn = points;

	if( rout )
		free( rout );
	if( rin )
		free( rin );
	if( have_plan )
		rfftw_destroy_plan( p );

	rin = (fftw_real*) xmalloc( sizeof( fftw_real ) * nn );
	rout = (fftw_real*) xmalloc( sizeof( fftw_real ) * nn );

	p = rfftw_create_plan( nn, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE );
	have_plan = 1;

#endif

	if( window )
		free( window );

	window = (double*) xmalloc( sizeof( double ) * nn );
	for ( c = 0; c < nn / 2; c++ )
		window[c] = window[nn - c - 1] = 0.54 - 0.46 * cos( 2 * PI * c / nn );

	return 0;
}
Пример #15
0
/*
 *  PADsynth-ize a WhySynth wavetable.
 */
int
padsynth_render(y_sample_t *sample)
{
    int N, i, fc0, nh, plimit_low, plimit_high, rndlim_low, rndlim_high;
    float bw, stretch, bwscale, damping;
    float f, max, samplerate, bw0_Hz, relf;
    float *inbuf = global.padsynth_inbuf;
    float *outfreqs, *smp;

    /* handle the special case where the sample key limit is 256 -- these
     * don't get rendered because they're usually just sine waves, and are
     * played at very high frequency */
    if (sample->max_key == 256) {
        sample->data = (signed short *)malloc((WAVETABLE_POINTS + 8) * sizeof(signed short));
        if (!sample->data)
            return 0;
        sample->data += 4; /* guard points */
        memcpy(sample->data - 4, sample->source - 4,
               (WAVETABLE_POINTS + 8) * sizeof(signed short)); /* including guard points */
        sample->length = WAVETABLE_POINTS;
        sample->period = (float)WAVETABLE_POINTS;
        return 1;
    }

    /* calculate the output table size */
    i = lrintf((float)global.sample_rate * 2.5f);  /* at least 2.5 seconds long -FIX- this should be configurable */
    N = WAVETABLE_POINTS * 2;
    while (N < i) {
        if (N * 5 / 4 >= i) { N = N * 5 / 4; break; }
        if (N * 3 / 2 >= i) { N = N * 3 / 2; break; }
        N <<= 1;
    }

    /* check temporary memory and IFFT plan, allocate if needed */
    if (global.padsynth_table_size != N) {
        padsynth_free_temp();
        if (global.padsynth_ifft_plan) {
#ifdef FFTW_VERSION_2
            rfftw_destroy_plan(global.padsynth_ifft_plan);
#else
            fftwf_destroy_plan(global.padsynth_ifft_plan);
#endif
            global.padsynth_ifft_plan = NULL;
        }
        global.padsynth_table_size = N;
    }
    if (!global.padsynth_outfreqs)
        global.padsynth_outfreqs = (float *)fftwf_malloc(N * sizeof(float));
    if (!global.padsynth_outsamples)
        global.padsynth_outsamples = (float *)fftwf_malloc(N * sizeof(float));
    if (!global.padsynth_outfreqs || !global.padsynth_outsamples)
        return 0;
    outfreqs = global.padsynth_outfreqs;
    smp = global.padsynth_outsamples;
    if (!global.padsynth_ifft_plan)
        global.padsynth_ifft_plan =
#ifdef FFTW_VERSION_2
            (void *)rfftw_create_plan(N, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE);
#else
            (void *)fftwf_plan_r2r_1d(N, global.padsynth_outfreqs,
                                      global.padsynth_outsamples,
                                      FFTW_HC2R, FFTW_ESTIMATE);
#endif
    if (!global.padsynth_ifft_plan)
        return 0;

    /* allocate sample memory */
    sample->data = (signed short *)malloc((N + 8) * sizeof(signed short));
    if (!sample->data)
        return 0;
    sample->data += 4; /* guard points */
    sample->length = N;

    /* condition parameters */
    bw = (sample->param1 ? (float)(sample->param1 * 2) : 1.0f); /* partial width: 1, or 2 to 100 cents by 2 */
    stretch = (float)(sample->param2 - 10) / 10.0f;
    stretch *= stretch * stretch / 10.0f;                       /* partial stretch: -10% to +10% */
    switch (sample->param3) {
      default:
      case  0:  bwscale = 1.0f;   break;                        /* width scale: 10% to 250% */
      case  2:  bwscale = 0.5f;   break;
      case  4:  bwscale = 0.25f;  break;
      case  6:  bwscale = 0.1f;   break;
      case  8:  bwscale = 1.5f;   break;
      case 10:  bwscale = 2.0f;   break;
      case 12:  bwscale = 2.5f;   break;
      case 14:  bwscale = 0.75f;  break;
    }
    damping = (float)sample->param4 / 20.0f;
    damping = damping * damping * -6.0f * logf(10.0f) / 20.0f;  /* damping: 0 to -6dB per partial */

    /* obtain spectrum of input wavetable */
    YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: analyzing input table\n");
    for (i = 0; i < WAVETABLE_POINTS; i++)
        inbuf[i] = (float)sample->source[i] / 32768.0f;
#ifdef FFTW_VERSION_2
    rfftw_one((rfftw_plan)global.padsynth_fft_plan, inbuf, inbuf);
#else
    fftwf_execute((const fftwf_plan)global.padsynth_fft_plan);  /* transform inbuf in-place */
#endif
    max = 0.0f;
    if (damping > -1e-3f) { /* no damping */
        for (i = 1; i < WAVETABLE_POINTS / 2; i++) {
            inbuf[i] = sqrtf(inbuf[i] * inbuf[i] +
                             inbuf[WAVETABLE_POINTS - i] * inbuf[WAVETABLE_POINTS - i]);
            if (fabsf(inbuf[i]) > max) max = fabsf(inbuf[i]);
        }
        if (fabsf(inbuf[WAVETABLE_POINTS / 2]) > max) max = fabsf(inbuf[WAVETABLE_POINTS / 2]);
    } else {  /* damping */
        for (i = 1; i < WAVETABLE_POINTS / 2; i++) {
            inbuf[i] = sqrtf(inbuf[i] * inbuf[i] +
                             inbuf[WAVETABLE_POINTS - i] * inbuf[WAVETABLE_POINTS - i]) *
                       expf((float)i * damping);
            if (fabsf(inbuf[i]) > max) max = fabsf(inbuf[i]);
        }
        inbuf[WAVETABLE_POINTS / 2] = 0.0f;  /* lazy */
    }
    if (max < 1e-5f) max = 1e-5f;
    for (i = 1; i <= WAVETABLE_POINTS / 2; i++)
        inbuf[i] /= max;

    /* create new frequency profile */
    YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: creating frequency profile\n");
    memset(outfreqs, 0, N * sizeof(float));

    /* render the fundamental at 4 semitones below the key limit */
    f = 440.0f * y_pitch[sample->max_key - 4];

    /* Find a nominal samplerate close to the real samplerate such that the
     * input partials fall exactly at integer output partials. This ensures
     * that especially the lower partials are not out of tune. Example:
     *    N = 131072
     *    global.samplerate = 44100
     *    f = 261.625565
     *    fi = f / global.samplerate = 0.00593255
     *    fc0 = int(fi * N) = int(777.592) = 778
     * so we find a new 'samplerate' that will result in fi * N being exactly 778:
     *    samplerate = f * N / fc = 44076.8
     */
    fc0 = lrintf(f / (float)global.sample_rate * (float)N);
    sample->period = (float)N / (float)fc0;  /* frames per period */
    samplerate = f * sample->period;
    /* YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: size = %d, f = %f, fc0 = %d, period = %f\n", N, f, fc0, sample->period); */

    bw0_Hz = (powf(2.0f, bw / 1200.0f) - 1.0f) * f;

    /* Find the limits of the harmonics to be used in the output table. These
     * are 20Hz and Nyquist, corrected for the nominal-to-actual sample rate
     * difference, with the latter also corrected  for the 4-semitone shift in
     * the fundamental frequency.
     * lower partial limit:
     *   (20Hz * samplerate / global.sample_rate) / samplerate * N
     * 4-semitone shift:
     *   (2 ^ -12) ^ 4
     * upper partial limit:
     *   ((global.sample_rate / 2) * samplerate / global.sample_rate) / samplerate * N / shift
     */
    plimit_low = lrintf(20.0f / (float)global.sample_rate * (float)N);
    /* plimit_high = lrintf(20000.0f / (float)global.sample_rate * (float)N / 1.25992f); */
    plimit_high = lrintf((float)N / 2 / 1.25992f);
    /* YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: nominal rate = %f, plimit low = %d, plimit high = %d\n", samplerate, plimit_low, plimit_high); */

    rndlim_low = N / 2;
    rndlim_high = 0;
    for (nh = 1; nh <= WAVETABLE_POINTS / 2; nh++) {
        int fc, contributed;
        float bw_Hz;  /* bandwidth of the current harmonic measured in Hz */
        float bwi;
        float fi;
        float plimit_amp;

        if (inbuf[nh] < 1e-5f)
            continue;

        relf = relF(nh, stretch);
        if (relf < 1e-10f)
            continue;

        bw_Hz = bw0_Hz * powf(relf, bwscale);
        
        bwi = bw_Hz / (2.0f * samplerate);
        fi = f * relf / samplerate;
        fc = lrintf(fi * (float)N);
        /* printf("...... kl = %d, nh = %d, fn = %f, fc = %d, bwi*N = %f\n", sample->max_key, nh, f * relf, fc, bwi * (float)N); */

        /* set plimit_amp such that we don't calculate harmonics -100dB or more
         * below the profile peak for this harmonic */
        plimit_amp = profile(0.0f, bwi) * 1e-5f / inbuf[nh];
        /* printf("...... (nh = %d, fc = %d, prof(0) = %e, plimit_amp = %e, amp = %e)\n", nh, fc, profile(0.0f, bwi), plimit_amp, inbuf[nh]); */

        /* scan profile and add partial's contribution to outfreqs */
        contributed = 0;
        for (i = (fc < plimit_high ? fc : plimit_high); i >= plimit_low; i--) {
            float hprofile = profile(((float)i / (float)N) - fi, bwi);
            if (hprofile < plimit_amp) {
                /* printf("...... (i = %d, profile = %e)\n", i, hprofile); */
                break;
            }
            outfreqs[i] += hprofile * inbuf[nh];
            contributed = 1;
        }
        if (contributed && rndlim_low > i + 1) rndlim_low = i + 1;
        contributed = 0;
        for (i = (fc + 1 > plimit_low ? fc + 1 : plimit_low); i <= plimit_high; i++) {
            float hprofile = profile(((float)i / (float)N) - fi, bwi);
            if (hprofile < plimit_amp) {
                /* printf("...... (i = %d, profile = %e)\n", i, hprofile); */
                break;
            }
            outfreqs[i] += hprofile * inbuf[nh];
            contributed = 1;
        }
        if (contributed && rndlim_high < i - 1) rndlim_high = i - 1;
    };
    if (rndlim_low > rndlim_high) {  /* somehow, outfreqs is still empty */
        YDB_MESSAGE(YDB_SAMPLE, " padsynth_render WARNING: empty output table (key limit = %d)\n", sample->max_key);
        rndlim_low = rndlim_high = fc0;
        outfreqs[fc0] = 1.0f;
    }

    /* randomize the phases */
    /* YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: randomizing phases (%d to %d, kl=%d)\n", rndlim_low, rndlim_high, sample->max_key); */
    YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: randomizing phases\n");
    if (rndlim_high >= N / 2) rndlim_high = N / 2 - 1;
    for (i = rndlim_low; i < rndlim_high; i++) {
        float phase = RND() * 2.0f * M_PI_F;
        outfreqs[N - i] = outfreqs[i] * cosf(phase);
        outfreqs[i]     = outfreqs[i] * sinf(phase);
    };

    /* inverse FFT back to time domain */
    YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: performing inverse FFT\n");
#ifdef FFTW_VERSION_2
    rfftw_one((rfftw_plan)global.padsynth_ifft_plan, outfreqs, smp);
#else
    /* remember restrictions on FFTW3 'guru' execute: buffers must be the same
     * sizes, same in-place-ness or out-of-place-ness, and same alignment as
     * when plan was created. */
    fftwf_execute_r2r((const fftwf_plan)global.padsynth_ifft_plan, outfreqs, smp);
#endif

    /* normalize and convert output data */
    YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: normalizing output\n");
    max = 0.0f;
    for (i = 0; i < N; i++) if (fabsf(smp[i]) > max) max = fabsf(smp[i]);
    if (max < 1e-5f) max = 1e-5f;
    max = 32767.0f / max;
    for (i = 0; i < N; i++)
         sample->data[i] = lrintf(smp[i] * max);

    /* copy guard points */
    for (i = -4; i < 0; i++)
        sample->data[i] = sample->data[i + N];
    for (i = 0; i < 4; i++)
        sample->data[N + i] = sample->data[i];

    YDB_MESSAGE(YDB_SAMPLE, " padsynth_render: done\n");

    return 1;
}
Пример #16
0
/* initialize patch
 * INPUT
 *   file_patch : filename
 *   plen : # of data in patch (wav)
 *   nwin : index of window
 * OUTPUT (extern values)
 *   pat[] : power of pat
 *   npat : # of data in pat[] ( = plen/2 +1 )
 *   p0 : maximun of power
 *   if0 : freq point of maximum
 */
void
init_patch (char *file_patch, int plen, int nwin)
{
  extern int patch_flg;
  extern double *pat;
  extern int npat; /* # of data in pat[]  */
  extern double p0; /* maximum power  */
  extern double if0; /* freq point of maximum  */
  
  int i;


  /* prepare patch  */
  if (file_patch == NULL)
    {
      patch_flg = 0;
      return;
    }
  else
    {
      /* allocate pat[]  */
      pat = (double *)malloc (sizeof (double) * (plen/2+1));
      if (pat == NULL)
	{
	  fprintf(stderr, "cannot allocate pat[%d]\n", (plen/2+1));
	  patch_flg = 0;
	  return;
	}

      double *x = NULL;
      double *xx = NULL;
      x  = (double *)malloc (sizeof (double) * plen);
      xx = (double *)malloc (sizeof (double) * plen);
      if (x == NULL || xx == NULL)
	{
	  fprintf(stderr, "cannot allocate x[%d]\n", plen);
	  patch_flg = 0;
	  return;
	}

      /* spectrum data for FFT */ 
      double *y = NULL;
      y = (double *)malloc (sizeof (double) * plen);
      if (y == NULL)
	{
	  fprintf(stderr, "cannot allocate y[%d]\n", plen);
	  patch_flg = 0;
	  free (x);
	  free (xx);
	  return;
	}

      /* open patch file  */
      SNDFILE *sf = NULL;
      SF_INFO sfinfo;
      sf = sf_open (file_patch, SFM_READ, &sfinfo);
      if (sf == NULL)
	{
	  fprintf (stderr, "Can't open patch file %s : %s\n",
		   file_patch, strerror (errno));
	  exit (1);
	}

      /* read patch wav  */
      if (sndfile_read (sf, sfinfo, x, xx, plen) != plen)
	{
	  fprintf (stderr, "No Patch Data!\n");
	  patch_flg = 0;
	  free (x);
	  free (xx);
	  free (y);
	  return;
	}
      if (sfinfo.channels == 2)
	{
	  for (i = 0; i < plen; i ++)
	    {
	      x[i] = 0.5 * (x[i] + xx[i]);
	    }
	}

      /* calc power of patch  */
      double den;
      den = init_den (plen, nwin);

#ifdef FFTW2
      rfftw_plan plan;
      plan = rfftw_create_plan (plen, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE);
#else
      fftw_plan plan;
      plan = fftw_plan_r2r_1d (plen, x, y, FFTW_R2HC, FFTW_ESTIMATE);
#endif /* FFTW2 */

      power_spectrum_fftw (plen, x, y, pat, den, nwin, plan);
      fftw_destroy_plan (plan);

      free (x);
      free (xx);
      free (y);
      sf_close (sf);

      /* search maximum  */
      p0 = 0.0;
      if0 = -1;
      for (i=0; i<plen/2; i++)
	{
	  if (pat[i] > p0)
	    {
	      p0 = pat[i];
	      if0 = i;
	    }
	}
      if (if0 == -1)
	patch_flg = 0;

      npat = plen/2;
      patch_flg = 1;
    }
}
Пример #17
0
/*
 * Create an fftwnd_plan specialized for specific arrays.  (These
 * arrays are ignored, however, if they are NULL or if the flags
 * do not include FFTW_MEASURE.)  The main advantage of being
 * provided arrays like this is that we can do runtime timing
 * measurements of our options, without worrying about allocating
 * excessive scratch space. 
 */
fftwnd_plan rfftwnd_create_plan_specific(int rank, const int *n,
					 fftw_direction dir, int flags,
					 fftw_real *in, int istride,
					 fftw_real *out, int ostride)
{
     fftwnd_plan p;
     int i;
     int rflags = flags & ~FFTW_IN_PLACE;
     /* note that we always do rfftw transforms out-of-place in rexec2.c */

     if (flags & FFTW_IN_PLACE) {
	  out = NULL;
	  ostride = istride;
     }
     istride = ostride = 1;	/* 
				 * strides don't work yet, since it is not 
				 * clear whether they apply to real 
				 * or complex data 
				 */

     if (!(p = fftwnd_create_plan_aux(rank, n, dir, flags)))
	  return 0;

     for (i = 0; i < rank - 1; ++i)
	  p->n_after[i] = (n[rank - 1]/2 + 1) * (p->n_after[i] / n[rank - 1]);
     if (rank > 0)
	  p->n[rank - 1] = n[rank - 1] / 2 + 1;

     p->plans = fftwnd_new_plan_array(rank);
     if (rank > 0 && !p->plans) {
	  rfftwnd_destroy_plan(p);
	  return 0;
     }
     if (rank > 0) {
	  p->plans[rank - 1] = rfftw_create_plan(n[rank - 1], dir, rflags);
	  if (!p->plans[rank - 1]) {
	       rfftwnd_destroy_plan(p);
	       return 0;
	  }
     }
     if (rank > 1) {
	  if (!(flags & FFTW_MEASURE) || in == 0
	      || (!p->is_in_place && out == 0)) {
	       if (!fftwnd_create_plans_generic(p->plans, rank - 1, n,
					   dir, flags | FFTW_IN_PLACE)) {
		    rfftwnd_destroy_plan(p);
		    return 0;
	       }
	  } else if (dir == FFTW_COMPLEX_TO_REAL || (flags & FFTW_IN_PLACE)) {
	       if (!fftwnd_create_plans_specific(p->plans, rank - 1, n,
						 p->n_after,
					      dir, flags | FFTW_IN_PLACE,
						 (fftw_complex *) in,
						 istride,
						 0, 0)) {
		    rfftwnd_destroy_plan(p);
		    return 0;
	       }
	  } else {
	       if (!fftwnd_create_plans_specific(p->plans, rank - 1, n,
						 p->n_after,
					      dir, flags | FFTW_IN_PLACE,
						 (fftw_complex *) out,
						 ostride,
						 0, 0)) {
		    rfftwnd_destroy_plan(p);
		    return 0;
	       }
	  }
     }
     p->nbuffers = 0;
     p->nwork = fftwnd_work_size(rank, p->n, flags | FFTW_IN_PLACE,
				 p->nbuffers + 1);
     if (p->nwork && !(flags & FFTW_THREADSAFE)) {
	  p->work = (fftw_complex *) fftw_malloc(p->nwork
						 * sizeof(fftw_complex));
	  if (!p->work) {
	       rfftwnd_destroy_plan(p);
	       return 0;
	  }
     }
     return p;
}
void test_in_place(int n, int istride,
		   int howmany, fftw_direction dir,
		   fftw_plan validated_plan, int specific)
{
     fftw_complex *in2, *out2;
     fftw_real *in1, *out1, *out3;
     fftw_plan plan;
     int i, j;
     int ostride = istride;
     int flags = measure_flag | wisdom_flag | FFTW_IN_PLACE;

     if (coinflip())
	  flags |= FFTW_THREADSAFE;

     in1 = (fftw_real *) fftw_malloc(istride * n * sizeof(fftw_real) * howmany);
     in2 = (fftw_complex *) fftw_malloc(n * sizeof(fftw_complex));
     out1 = in1;
     out2 = (fftw_complex *) fftw_malloc(n * sizeof(fftw_complex));
     out3 = (fftw_real *) fftw_malloc(n * sizeof(fftw_real));

     if (!specific)
	  plan = rfftw_create_plan(n, dir, flags);
     else
	  plan = rfftw_create_plan_specific(n, dir, flags,
					    in1, istride, out1, ostride);
     CHECK(plan != NULL, "can't create plan");

     /* generate random inputs */
     fill_random(in1, n, istride);
     for (j = 1; j < howmany; ++j)
	  for (i = 0; i < n; ++i)
	       in1[(j * n + i) * istride] = in1[i * istride];

     /* copy random inputs to complex array for comparison with fftw: */
     if (dir == FFTW_REAL_TO_COMPLEX)
	  for (i = 0; i < n; ++i) {
	       c_re(in2[i]) = in1[i * istride];
	       c_im(in2[i]) = 0.0;
     } else {
	  int n2 = (n + 1) / 2;
	  c_re(in2[0]) = in1[0];
	  c_im(in2[0]) = 0.0;
	  for (i = 1; i < n2; ++i) {
	       c_re(in2[i]) = in1[i * istride];
	       c_im(in2[i]) = in1[(n - i) * istride];
	  }
	  if (n2 * 2 == n) {
	       c_re(in2[n2]) = in1[n2 * istride];
	       c_im(in2[n2]) = 0.0;
	       ++i;
	  }
	  for (; i < n; ++i) {
	       c_re(in2[i]) = c_re(in2[n - i]);
	       c_im(in2[i]) = -c_im(in2[n - i]);
	  }
     }

     /* 
      * fill in other positions of the array, to make sure that
      * rfftw doesn't overwrite them 
      */
     for (j = 1; j < istride; ++j)
	  for (i = 0; i < n * howmany; ++i)
	       in1[i * istride + j] = i * istride + j;

     WHEN_VERBOSE(2, rfftw_print_plan(plan));

     /* fft-ize */
     if (howmany != 1 || istride != 1 || coinflip())
	  rfftw(plan, howmany, in1, istride, n * istride, 0, 0, 0);
     else
	  rfftw_one(plan, in1, NULL);

     rfftw_destroy_plan(plan);

     /* check for overwriting */
     for (j = 1; j < ostride; ++j)
	  for (i = 0; i < n * howmany; ++i)
	       CHECK(out1[i * ostride + j] == i * ostride + j,
		     "output has been overwritten");

     fftw(validated_plan, 1, in2, 1, n, out2, 1, n);

     if (dir == FFTW_REAL_TO_COMPLEX) {
	  int n2 = (n + 1) / 2;
	  out3[0] = c_re(out2[0]);
	  for (i = 1; i < n2; ++i) {
	       out3[i] = c_re(out2[i]);
	       out3[n - i] = c_im(out2[i]);
	  }
	  if (n2 * 2 == n)
	       out3[n2] = c_re(out2[n2]);
     } else {
	  for (i = 0; i < n; ++i)
	       out3[i] = c_re(out2[i]);
     }

     for (j = 0; j < howmany; ++j)
	  CHECK(compute_error(out1 + j * n * ostride, ostride, out3, 1, n)
		< TOLERANCE,
		"test_in_place: wrong answer");
     WHEN_VERBOSE(2, printf("OK\n"));

     fftw_free(in1);
     fftw_free(in2);
     fftw_free(out2);
     fftw_free(out3);
}
Пример #19
0
void CPlotDlg::OnMenu(UINT nID)
{
	static char fullfname[MAX_PATH];
	static CAxis *axSpec(NULL);
	CAxis *localax(gcf->ax[0]); // Following the convention
	CRect rt;
	CSize sz;
	CFont editFont;
	CPosition pos;
	double range, miin(1.e15), maax(-1.e15);
	double width, newmin, newmax;
	int i, len, id1, id2, iSel(-1);
	char errstr[256];
	CSignals signal;
	bool multi;
	static void  *playPoint;
	switch (nID)
	{
	case IDM_FULLVIEW:
		localax->setRange('x',localax->m_ln[0]->xdata[0], localax->m_ln[0]->xdata[localax->m_ln[0]->len-1]);
		localax->setTick('x', 0, localax->m_ln[0]->xdata[localax->m_ln[0]->len-1]/10, 1, 0, "%6.3f");
		// 2/3/2011, commented out by jhpark, because y axis is not affected by zooming.
		//localax->setRange('y', -1, 1);
		OnMenu(IDM_SPECTRUM_INTERNAL);
		return;

	case IDM_ZOOM_IN:
		width = localax->xlim[1] - localax->xlim[0];
		if (width<0.005) return;
		localax->setRange('x', localax->xlim[0] + width/4., localax->xlim[1] - width/4.);
		width = localax->xtick.a2 - localax->xtick.a1;
		localax->xtick.a2 -= width/4.;
		localax->xtick.a1 += width/4.;
		OnMenu(IDM_SPECTRUM_INTERNAL);
		return;

	case IDM_ZOOM_OUT:
		if (localax->xlim[1]==localax->xlimFull[1] && localax->xlim[0]==localax->xlimFull[0]) return;
		for (i=0; i<localax->nLines; i++)
			miin = min(miin, getMin(localax->m_ln[i]->len, localax->m_ln[i]->xdata));
		for (i=0; i<localax->nLines; i++)
			maax = max(maax, getMax(localax->m_ln[i]->len, localax->m_ln[i]->xdata));
		width = localax->xlim[1] - localax->xlim[0];
		localax->setRange('x', max(miin,localax->xlim[0] - width/2.), min(maax,localax->xlim[1] + width/2.));
		width = localax->xtick.a2 - localax->xtick.a1;
		//Oh, I just realized that a1 and a2 do not need to be within the range==> no need to check, it will still draw the ticks only within the range.
		localax->xtick.a2 += width/2.;
		localax->xtick.a1 -= width/2.;
		if (localax->xtick.a1<0) localax->xtick.a1=0;
		OnMenu(IDM_SPECTRUM_INTERNAL);
		return;
	case IDM_SCROLL_LEFT:
		for (i=0; i<localax->nLines; i++)
			miin = min(miin, getMin(localax->m_ln[i]->len, localax->m_ln[i]->xdata));
		range = localax->xlim[1] - localax->xlim[0];
		newmin = max(miin, localax->xlim[0]-range);
		localax->setRange('x', newmin, newmin+range);
		rt = localax->axRect;
		rt.InflateRect(5,0,5,30);
		InvalidateRect(&rt);
		OnMenu(IDM_SPECTRUM_INTERNAL);
		return;
	case IDM_SCROLL_RIGHT:
		for (i=0; i<localax->nLines; i++)
			maax = max(maax, getMax(localax->m_ln[i]->len, localax->m_ln[i]->xdata));
		range = localax->xlim[1] - localax->xlim[0];
		newmax = min(maax, localax->xlim[1]+range);
		localax->setRange('x', newmax-range, newmax);
		rt = localax->axRect;
		rt.InflateRect(5,0,5,30);
		InvalidateRect(&rt);
		OnMenu(IDM_SPECTRUM_INTERNAL);
		return;
	case IDM_LEFT_STEP:
		for (i=0; i<localax->nLines; i++)
			miin = min(miin, getMin(localax->m_ln[i]->len, localax->m_ln[i]->xdata));
		range = localax->xlim[1] - localax->xlim[0];
		newmin = max(miin, localax->xlim[0]-range/4.);
		localax->setRange('x', newmin, newmin+range);
		rt = localax->axRect;
		rt.InflateRect(5,0,5,30);
		InvalidateRect(&rt);
		OnMenu(IDM_SPECTRUM_INTERNAL);
		return;
	case IDM_RIGHT_STEP:
		for (i=0; i<localax->nLines; i++)
			maax = max(maax, getMax(localax->m_ln[i]->len, localax->m_ln[i]->xdata));
		range = localax->xlim[1] - localax->xlim[0];
		newmax = min(maax, localax->xlim[1]+range/4.);
		localax->setRange('x', newmax-range, newmax);
		rt = localax->axRect;
		rt.InflateRect(5,0,5,30);
		InvalidateRect(&rt);
		OnMenu(IDM_SPECTRUM_INTERNAL);
		return;
	case IDM_PLAY:
		errstr[0]=0;
		if (!playing)
			if(!GetSignalInRange(signal,1))		MessageBox (errStr);
			else 
			{
				playPoint = signal.PlayArray(devID, WM__SOUND_EVENT, hDlg, &block, errstr);
				playing = true;
			}
		else
		{
			PauseResumePlay(playPoint, paused);
			playing = paused;
			if (paused) paused = false;
		}
		return;
	case IDM_PAUSE:
		errstr[0]=0;
		if (playing)
		{
			PauseResumePlay(playPoint, false);
			paused = true;
		}
		return;
	case IDM_SPECTRUM:
		// To draw a spectrum, first re-adjust the aspect ratio of the client window 
		// so that the width is at least 1.5 times the height.
		if (!specView)
		{
			GetWindowRect(&rt);
			sz = rt.Size();
			if (sz.cx<3*sz.cy/2)
			{
				rt.InflateRect(0, 0, 3*sz.cy/2, 0);
				MoveWindow(&rt, 0);
			}
			//Again, //Assuming that the first axis is the waveform viewer, the second one is for spectrum viewing
			lastPos = gcf->ax[0]->pos;
			gcf->ax[0]->setPos(.08, .1, .62, .8);
			axSpec = gcf->axes(.75, .3, .22, .4);
			axSpec->colorBack = RGB(230, 230, 190);
			OnMenu(IDM_SPECTRUM_INTERNAL);
		}
		else
		{
			deleteObj(axSpec);
			axSpec=NULL;
			gcf->ax[0]->setPos(lastPos);
		}
		specView = !specView;
		break;
	case IDM_SPECTRUM_INTERNAL:
		rfftw_plan plan;
		double *freq, *fft, *mag, *fft2, *mag2, fs, maxx, maxmag, ylim;
		multi = localax->nLines>1 ? true : false;
		if (gcf->nAxes==1) break;
		fs = (double)sig.GetFs();
		for (; gcf->ax[1]->nLines>0;)	
			deleteObj(gcf->ax[1]->m_ln[0]);
		GetIndicesInRange(localax, id1, id2);
		len = id2-id1+1;
		freq = new double[len];
		fft = new double[len];
		mag = new double[len/2];
		for (i=0; i<len; i++)
			freq[i]=(double)i/(double)len*fs;
		plan = rfftw_create_plan(len, FFTW_FORWARD, FFTW_ESTIMATE|FFTW_OUT_OF_PLACE);
		rfftw_one(plan, &localax->m_ln[0]->ydata[id1], fft);
		if (multi) 
		{
			fft2 = new double[len];
			mag2 = new double[len/2];
			rfftw_one(plan, &localax->m_ln[1]->ydata[id1], fft2);
		}
		rfftw_destroy_plan(plan);
		for (i=0; i<len/2; i++)		mag[i] = 20.*log10(fabs(fft[len-i]));
		if (multi) for (i=0; i<len/2; i++)	mag2[i] = 20.*log10(fabs(fft2[len-i]));
		maxmag = getMax(len/2,mag);
		maxx = 5.*(maxmag/5.+1);
		for (int j=0; j<len/2; j++)	mag[j] -= maxx;
		if (multi) 
		{
			maxmag = getMax(len/2,mag2);
			maxx = 5.*(maxmag/5.+1);
			for (int j=0; j<len/2; j++)	mag2[j] -= maxx;
		}
		ylim = 10.*(maxmag/10.+1)-maxx;
		PlotDouble(gcf->ax[1], len/2, freq, mag);
		SetRange(gcf->ax[1], 'x', 0, fs/2);
		SetTick(gcf->ax[1], 'x', 0, 1000, 0, 0, "%2.0lfk", 0.001);
		SetRange(gcf->ax[1], 'y', getMean(len/2,mag)-40, ylim);
		SetTick(gcf->ax[1], 'y', 0, 10);
		gcf->ax[1]->m_ln[0]->color = gcf->ax[0]->m_ln[0]->color;
		if (multi) 
		{
			PlotDouble(gcf->ax[1], len/2, freq, mag2);
			gcf->ax[1]->m_ln[1]->color = gcf->ax[0]->m_ln[1]->color;
			delete[] fft2;
			delete[] mag2;
		}
		delete[] freq;
		delete[] fft;
		delete[] mag;
		break;
	case IDM_WAVWRITE:
		char fname[MAX_PATH];
		CFileDlg fileDlg;
		fileDlg.InitFileDlg(hDlg, hInst, "");
		errstr[0]=0;
		if(!GetSignalInRange(signal,1))
		{	MessageBox (errStr);	return;	}
		if (fileDlg.FileSaveDlg(fullfname, fname, "Wav file (*.WAV)\0*.wav\0", "wav"))
			if (!signal.Wavwrite(fullfname, errstr))	
			{MessageBox (errstr);}
		else
		{
			CStdString str;
			if (GetLastError()!=0) { GetLastErrorStr(str); MessageBox (str.c_str(), "Filesave error");}
		}
		return;
	}
	InvalidateRect(NULL);
}
void test_planner(int rank)
{
     /* 
      * create and destroy many plans, at random.  Check the
      * garbage-collecting allocator of twiddle factors 
      */
     int i, dim;
     int r, s;
     fftw_plan p[PLANNER_TEST_SIZE];
     fftwnd_plan pnd[PLANNER_TEST_SIZE];
     int *narr, maxdim;

     chk_mem_leak = 0;
     verbose--;

     please_wait();
     if (rank < 1)
	  rank = 1;

     narr = (int *) fftw_malloc(rank * sizeof(int));

     maxdim = (int) pow(8192.0, 1.0/rank);

     for (i = 0; i < PLANNER_TEST_SIZE; ++i) {
	  p[i] = (fftw_plan) 0;
	  pnd[i] = (fftwnd_plan) 0;
     }

     for (i = 0; i < PLANNER_TEST_SIZE * PLANNER_TEST_SIZE; ++i) {
	  r = rand();
	  if (r < 0)
	       r = -r;
	  r = r % PLANNER_TEST_SIZE;

	  for (dim = 0; dim < rank; ++dim) {
	       do {
		    s = rand();
		    if (s < 0)
			 s = -s;
		    s = s % maxdim + 1;
	       } while (s == 0);
	       narr[dim] = s;
	  }

	  if (rank == 1) {
	       if (p[r])
		    rfftw_destroy_plan(p[r]);

	       p[r] = rfftw_create_plan(narr[0], random_dir(), measure_flag |
					wisdom_flag);
	       if (paranoid && narr[0] < 200)
		    test_correctness(narr[0]);
	  }
	  if (pnd[r])
	       rfftwnd_destroy_plan(pnd[r]);

	  pnd[r] = rfftwnd_create_plan(rank, narr,
				       random_dir(), measure_flag |
				       wisdom_flag);

	  if (i % (PLANNER_TEST_SIZE * PLANNER_TEST_SIZE / 20) == 0) {
	       WHEN_VERBOSE(0, printf("test planner: so far so good\n"));
	       WHEN_VERBOSE(0, printf("test planner: iteration %d out of %d\n",
			      i, PLANNER_TEST_SIZE * PLANNER_TEST_SIZE));
	  }
     }

     for (i = 0; i < PLANNER_TEST_SIZE; ++i) {
	  if (p[i])
	       rfftw_destroy_plan(p[i]);
	  if (pnd[i])
	       rfftwnd_destroy_plan(pnd[i]);
     }

     fftw_free(narr);
     verbose++;
     chk_mem_leak = 1;
}