Esempio n. 1
0
int main()
{
	double *buffer = (double *)malloc(N*CHANNELS*sizeof(double));
	global_estimate = (double *)calloc(N*CHANNELS,sizeof(double));
	
	unsigned int ctr = 0;
	int fd;

	fd = open(DEVICE_FILE_NAME, 0);
	
	if (fd < 0) {
		printf("Can't open device\n");
		exit(-1);
	}

	if (signal(SIGINT, handler) == SIG_ERR) {
		return 0;
	}

	init_fft();

	while (appRunning) {
		for (ctr = 0; ctr < N; ctr++) {
			get_data(fd,buffer + ctr*CHANNELS);
		}
		
		process(buffer);
		buffer = (double *)malloc(N*CHANNELS*sizeof(double));
	}

	gpu_fft_release(fft);	
	free(global_estimate);
	close(fd);
	return 0;
}
bool ChannelizerBase::initFFT()
{
	int len;
	int flags = CXVEC_FLG_FFT_ALIGN;

	if (fftInput || fftOutput || fftHandle)
		return false;

	len = chunkLen * mChanM;
	fftInput = cxvec_alloc(len, 0, NULL, flags);

	len = (chunkLen + mFiltLen) * mChanM;
	fftOutput = cxvec_alloc(len, 0, NULL, flags);

	if (!fftInput | !fftOutput) {
		LOG(ERR) << "Memory allocation error";
		return false;
	}

	cxvec_reset(fftInput);
	cxvec_reset(fftOutput);

	fftHandle = init_fft(0, mChanM, chunkLen, chunkLen + mFiltLen,
			     fftInput, fftOutput, mFiltLen);

	return true;
}
Esempio n. 3
0
File: func.c Progetto: atoun/xoscope
void
init_math()
{
  static int i;
  static int once = 0;

  for (i = 0 ; i < 26 ; i++) {
    if (once==1 && mem[i].data != NULL) {
      free(mem[i].data);
    }
    mem[i].data = NULL;
    mem[i].num = mem[i].frame = mem[i].volts = 0;
    mem[i].listeners = 0;
    sprintf(mem[i].name, "Memory %c", 'a' + i);
    mem[i].savestr[0] = 'a' + i;
    mem[i].savestr[1] = '\0';
  }
  for (i = 0; i < funccount; i++) {
    strcpy(funcarray[i].signal.name, funcarray[i].name);
    funcarray[i].signal.savestr[0] = '0' + i;
    funcarray[i].signal.savestr[1] = '\0';
  }
  init_fft();
  once=1;
}
Esempio n. 4
0
fftcorr::fftcorr(int len) : flen(len), flen2(len>>1)
{
    init_fft();
}

fftcorr::~fftcorr()
{
    delete fftA;
    delete fftB;
    delete[] dataA;
    delete[] dataB;
    delete[] dataBj;
    delete[] dataP;
}

int fftcorr::run(const cmplx& inA, const cmplx* inB, cmplx **out)
{
    dataA[inptrA++] = inA;

    if (inB) {
        dataB[inptrB++] = *inB;
    }

    if (inptrA < flen2) {
        return 0;
    }

    fftA->ComplexFFT(dataA);

    if (inB) {
        fftB->ComplexFFT(dataB);
    }

    if (inB) {
        std::transform(dataB, dataB+flen, dataBj, [](const cmplx& c) -> cmplx { return std::conj(c); });
    } else {
        std::transform(dataA, dataA+flen, dataBj, [](const cmplx& c) -> cmplx { return std::conj(c); });
    }

    std::transform(dataA, dataA+flen, dataBj, dataP, [](const cmplx& a, const cmplx& b) -> cmplx { return a*b; });

    fftA->InverseComplexFFT(dataP);

    std::fill(dataA, dataA+flen, 0);
    inptrA = 0;

    if (inB)
    {
        std::fill(dataB, dataB+flen, 0);
        inptrB = 0;
    }

    *out = dataP;
    return flen2;
}
Esempio n. 5
0
int main(int argc, char **argv)
{
  int i, n, numruns = NUMRUNS;
  clock_t start, finish;
  double gflop, duration, runtime;
  _Complex double *x, *y;
  fft_func *fft;

  printf("Spiral 5.0 Chapel FFT example -- C99 version, %s\n", COMPILER);

  for (n = MIN_SIZE; n <= MAX_SIZE; n *= 2, numruns *=0.6) {
    //  initialization
    x = (_Complex double *) malloc(n * sizeof(_Complex double));
    y = (_Complex double *) malloc(n * sizeof(_Complex double));
   
    x[0] = 1 + __I__;	
    for (i = 1; i < n; i++)
      x[i] = 0; 
    fft = init_fft(n);

    //  check computation
    fft(y, x);

    for (i = 0; i < n; i++)
      if (cabs(y[i] - (1 + __I__)) > EPS) {
        printf("Error: result incorrect.\n\n");
        exit(1);
      }

    if (!(fft)) {
      printf("Error: unsupported FFT size.\n\n");
      exit(1);
    }

    //  benchmark computation
    start = clock();
    for (i=0; i< numruns; i++) 
      fft(y, x);
    finish = clock();
    duration = (double)(finish - start) / CLOCKS_PER_SEC;
    runtime = 1E9 * duration /numruns;

    gflop = (5.0 * n * log((double)n) / (log(2.0) * runtime));
    printf("fft_%d: %d ns = %.3f Gflop/s\n", n, (int)runtime, gflop);

    free(x);
    free(y);
  }   
}
Esempio n. 6
0
int main( int argc, char **argv )
{
    if ( use_gui )
    {
        printf("init_sdl()\n");
        if ( init_sdl() ) return 1;

        printf("init_gl()\n");
        init_gl();
    }

    printf("init_fft()\n");
    if ( init_fft() ) return 1;

    if ( use_serial )
    {
        printf("init_serial()\n");
        if ( init_serial() ) use_serial = FALSE;
    }

    init_lights();
    init_table();

    while ( !done )
    {
        get_samples_do_fft();

        detect_beats();

        assign_lights();

        assign_cells();

        if ( use_gui )
        {
            if (handle_sdl_events()) return 1;
            draw_all();
        }

        if ( use_serial ) send_serial();

        usleep(5000);
    }

    return 0;
}
Esempio n. 7
0
int init_modules()
{
  init_cudacomp();
  init_AOloopControl();
  init_AOloopControl_DM();
  init_ZernikePolyn();
  init_WFpropagate();
  init_image_basic();
  init_image_filter();
  init_kdtree();
  init_image_gen();
  init_linopt_imtools();
  init_statistic();
  init_fft();
  init_info();
  init_COREMOD_arith();
  init_COREMOD_iofits();
  init_COREMOD_memory();
  init_COREMOD_tools();
  init_00CORE();

return 0;
}
// static
void SdSoundCaptureAL::StartCapture( BtBool isToFile, BtBool isFFT )
{
	// http://stackoverflow.com/questions/3056113/recording-audio-with-openal
	// http://stackoverflow.com/questions/9785447/simultaneous-record-playing-with-openal-using-threads
    
	pCaptureDevice = alcCaptureOpenDevice( NULL, 22050, AL_FORMAT_MONO16, FFTBufferSize);
    
	if( !pCaptureDevice  )
	{
		ErrorLog::Fatal_Printf( "Could not find EXT capture\r\n" );
		return;
	}
    
	ALCdevice		*pDevice;
	ALCcontext		*pContext;
	ALint			iDataSize = 0;
    
	// Check for Capture Extension support
	pContext = alcGetCurrentContext();
	pDevice = alcGetContextsDevice(pContext);
	if (alcIsExtensionPresent(pDevice, "ALC_EXT_CAPTURE") == AL_FALSE)
	{
		ErrorLog::Fatal_Printf( "Could not find EXT capture\r\n" );
		return;
	}
    
	// Create / open a file for the captured data
	audioFile = fopen( "C:\\temp\\sample.wav", "wb");
    
	if ( audioFile == NULL )
	{
		//ErrorLog::Fatal_Printf( "Could not find EXT capture\r\n" );
		//return;
	}
    
	audioFile = NULL;
    
	iDataSize = 0;
    
	// Prepare a WAVE file header for the captured data
	sprintf(sWaveHeader.szRIFF, "RIFF");
	sWaveHeader.lRIFFSize = 0;
	sprintf(sWaveHeader.szWave, "WAVE");
	sprintf(sWaveHeader.szFmt, "fmt ");
	sWaveHeader.lFmtSize = sizeof(WAVEFORMATEX);
	sWaveHeader.wfex.nChannels = 1;
	sWaveHeader.wfex.wBitsPerSample = 16;
	sWaveHeader.wfex.wFormatTag = 1; //WAVE_FORMAT_PCM;
	sWaveHeader.wfex.nSamplesPerSec = 22050;
	sWaveHeader.wfex.nBlockAlign = sWaveHeader.wfex.nChannels * sWaveHeader.wfex.wBitsPerSample / 8;
	sWaveHeader.wfex.nAvgBytesPerSec = sWaveHeader.wfex.nSamplesPerSec * sWaveHeader.wfex.nBlockAlign;
	sWaveHeader.wfex.cbSize = 0;
	sprintf(sWaveHeader.szData, "data");
	sWaveHeader.lDataSize = 0;
    
	if( audioFile )
	{
		fwrite(&sWaveHeader, sizeof(WAVEHEADER), 1, audioFile);
	}
    
	// Start audio capture
	alcCaptureStart(pCaptureDevice);
    
	m_isFFT= isFFT;
    
	init_fft( FFTBufferSize, 22050);
}
int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

     int bytesToNextHeader = 5;  // total amount of space (header+data)
    int samplesToNextFFT = 3;   // Num samples to the start of the next FFT
    int ptsPerFFT = 256;         // number of points per FFT 
    int sampFreq = 4;
    int endTrans = -1;
    init_fft(bytesToNextHeader, samplesToNextFFT, ptsPerFFT, sampFreq, endTrans);
    int header_len = sizeof(struct fft_header);

    fftw_complex *in, *out;
    fftw_plan p;

    in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * ptsPerFFT);
    out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * ptsPerFFT);
    p = fftw_plan_dft_1d(ptsPerFFT, in, out, FFTW_FORWARD, FFTW_MEASURE);

    // char buffer[256];
    //~ if (argc < 3) {
       //~ fprintf(stderr,"usage %s hostname port\n", argv[0]);
       //~ exit(0);
    //~ }
    //~ portno = atoi(argv[2]);
    if (argc < 2)
    {
     fprintf(stderr,"ERROR, no host provided\n");
     exit(1);
    }
    portno = 51717;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
        error1("ERROR opening socket");
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(-1);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
        fprintf(stderr, "Error on connect(): %s\n", strerror(errno));
        exit(-1);
    }

    
    
    /*
    n = write(sockfd, (char *) hdr, header_len);
    if (n < 0) 
         error1("ERROR writing to socket");
    */

	// FILE * f =fopen("data.txt","w");
	// fwrite(fft_data, 1, 255, f);
	// fclose(f);
	
	float fbuffer[ptsPerFFT];
    // float* fbuffer;
	int i, j;
	//~ for(i = 0; i < 256; i++){
		//~ fbuffer[i] = 0.3*i;
	//~ }
	/*
	n = write(sockfd, fbuffer, 256 * sizeof(float));
    if (n < 0) 
         error1("ERROR writing to socket");
    */

    // printf("header_len is %d\n", header_len);

    int k = 0;
    long dur;

    // while(k < 5){
    while(1){
        fprintf(stderr, "Sending header... ");

        n = write(sockfd, (char *) hdr, header_len);
        fprintf(stderr, "Sent header, n = %d\n", n);
        if (n < 0) 
             error1("ERROR writing to socket");
        
        // Generate random numbers to be sent each time.
        // srand(time(NULL));
        // for(i = 0; i < 256; i++){
        //     fbuffer[i] = (float) rand() / (float) RAND_MAX;
        // }

        dur = time(NULL);
        genfft(fbuffer, ptsPerFFT, p, in, out);
        dur -= time(NULL);
        // printf("genfft took %l s to run", dur);
        
        printf("Sending fbuffer\n");
        fprintf(stderr, "Sending data... ");
        n = write(sockfd, fbuffer, ptsPerFFT * sizeof(float));
        fprintf(stderr, "Sent data, n = %d\n", n);
        if (n < 0) 
             error1("ERROR writing to socket");

        usleep(500 * 1000);
        k++;
    }
    /*
    for(i = 0; i < 3; i++){
        
        //~ init_fft(bytesToNextHeader++, samplesToNextFFT+=2, ptsPerFFT, sampFreq, 
                    //~ endTrans);
        n = write(sockfd, (char *) hdr, header_len);
        if (n < 0) 
             error1("ERROR writing to socket");
        
        for(j = 0; j < 256; j++){
           fbuffer[j] = 0.25*i;
        }
        n = write(sockfd, fbuffer, ptsPerFFT * sizeof(float));
        if (n < 0) 
             error1("ERROR writing to socket");

		printf("This is iteration %d\n", i+1);

        //~ if(i == 2) endTrans = 1;
        //~ printf("endTrans is %d\n", endTrans);
    }
    */
	///////////////////////////////////////////////////////////////////////////////////////////
    
    fftw_destroy_plan(p);
    fftw_free(in); fftw_free(out);
    close(sockfd);
    return 0;
}
Esempio n. 10
0
int main(int argc, char **argv) {

    char c;

    int i,aa,aarx;
    double sigma2, sigma2_dB=0,SNR,snr0=10.0,snr1=10.2;
    int snr1set=0;
    uint32_t *txdata,*rxdata[2];
    double *s_re[2],*s_im[2],*r_re[2],*r_im[2];
    double iqim=0.0;
    int trial, ntrials=1;
    int n_rx=1;

    int awgn_flag=0;
    int n_frames=1;
    channel_desc_t *ch;
    uint32_t tx_lev,tx_lev_dB;
    int interf1=-19,interf2=-19;
    SCM_t channel_model=AWGN;
    uint32_t sdu_length_samples;
    TX_VECTOR_t tx_vector;
    int errors=0,misdetected_errors=0,signal_errors=0;
    int symbols=0;
    int tx_offset = 0,rx_offset;
    RX_VECTOR_t *rxv;
    uint8_t *data_ind,*data_ind_rx;
    int no_detection=1;
    int missed_packets=0;
    uint8_t rxp;
    int off,off2;
    double txg,txg_dB;
    int log2_maxh;
    double  snr_array[100];
    int  errors_array[100];
    int  trials_array[100];
    int  misdetected_errors_array[100];
    int  signal_errors_array[100];
    int  missed_packets_array[100];
    int  cnt=0;
    char fname[100],vname[100];
    int stop=0;

    data_ind    = (uint8_t*)malloc(4095+2+1);
    data_ind_rx = (uint8_t*)malloc(4095+2+1);

    tx_vector.rate=1;
    tx_vector.sdu_length=256;
    tx_vector.service=0;

    logInit();

    randominit(0);
    set_taus_seed(0);

    // Basic initializations
    init_fft(64,6,rev64);
    init_interleavers();
    ccodedot11_init();
    ccodedot11_init_inv();
    phy_generate_viterbi_tables();

    init_crc32();

    data_ind[0] = 0;
    data_ind[1] = 0;

    tx_offset = taus()%(FRAME_LENGTH_SAMPLES_MAX/2);

    while ((c = getopt (argc, argv, "hag:n:s:S:z:r:p:d:")) != -1) {
        switch (c) {
        case 'a':
            printf("Running AWGN simulation\n");
            awgn_flag = 1;
            ntrials=1;
            break;
        case 'g':
            switch((char)*optarg) {
            case 'A':
                channel_model=SCM_A;
                break;
            case 'B':
                channel_model=SCM_B;
                break;
            case 'C':
                channel_model=SCM_C;
                break;
            case 'D':
                channel_model=SCM_D;
                break;
            case 'E':
                channel_model=EPA;
                break;
            case 'F':
                channel_model=EVA;
                break;
            case 'G':
                channel_model=ETU;
                break;
            case 'H':
                channel_model=Rayleigh8;
            case 'I':
                channel_model=Rayleigh1;
            case 'J':
                channel_model=Rayleigh1_corr;
            case 'K':
                channel_model=Rayleigh1_anticorr;
            case 'L':
                channel_model=Rice8;
            case 'M':
                channel_model=Rice1;
                break;
            default:
                printf("Unsupported channel model!\n");
                exit(-1);
            }
            break;
        case 'd':
            tx_offset = atoi(optarg);
            break;
        case 'p':
            tx_vector.sdu_length = atoi(optarg);
            if (atoi(optarg)>4095) {
                printf("Illegal sdu_length %d\n",tx_vector.sdu_length);
                exit(-1);
            }
            break;
        case 'r':
            tx_vector.rate = atoi(optarg);
            if (atoi(optarg)>7) {
                printf("Illegal rate %d\n",tx_vector.rate);
                exit(-1);
            }
            break;
        case 'n':
            n_frames = atoi(optarg);
            break;
        case 's':
            snr0 = atof(optarg);
            printf("Setting SNR0 to %f\n",snr0);
            break;
        case 'S':
            snr1 = atof(optarg);
            snr1set=1;
            printf("Setting SNR1 to %f\n",snr1);
            break;
        case 'z':
            n_rx=atoi(optarg);
            if ((n_rx==0) || (n_rx>2)) {
                printf("Unsupported number of rx antennas %d\n",n_rx);
                exit(-1);
            }
            break;
        default:
        case 'h':
            printf("%s -h(elp) -a(wgn on) -p(extended_prefix) -N cell_id -f output_filename -F input_filename -g channel_model -n n_frames -t Delayspread -r Ricean_FactordB -s snr0 -S snr1 -x transmission_mode -y TXant -z RXant -i Intefrence0 -j Interference1 -A interpolation_file -C(alibration offset dB) -N CellId\n",argv[0]);
            printf("-h This message\n");
            printf("-a Use AWGN channel and not multipath\n");
            printf("-n Number of frames to simulate\n");
            printf("-s Starting SNR, runs from SNR0 to SNR0 + 5 dB.  If n_frames is 1 then just SNR is simulated\n");
            printf("-S Ending SNR, runs from SNR0 to SNR1\n");
            printf("-g [A,B,C,D,E,F,G] Use 3GPP SCM (A,B,C,D) or 36-101 (E-EPA,F-EVA,G-ETU) models (ignores delay spread and Ricean factor)\n");
            printf("-z Number of RX antennas used\n");
            printf("-F Input filename (.txt format) for RX conformance testing\n");
            exit (-1);
            break;
        }
    }

    if (n_frames==1)
        snr1 = snr0+.2;
    else
        snr1 = snr0+5;
    for (i=0; i<tx_vector.sdu_length; i++)
        data_ind[i+2] = i;//taus();  // randomize packet
    data_ind[tx_vector.sdu_length+2+4]=0;  // Tail byte

    // compute number of OFDM symbols in DATA period
    symbols = ((4+2+1+tx_vector.sdu_length)<<1) / nibbles_per_symbol[tx_vector.rate];
    if ((((4+2+1+tx_vector.sdu_length)<<1) % nibbles_per_symbol[tx_vector.rate]) > 0)
        symbols++;

    sdu_length_samples = (symbols + 5) * 80;

    printf("Number of symbols for sdu : %d, samples %d\n",symbols,sdu_length_samples);

    txdata = (uint32_t*)memalign(16,sdu_length_samples*sizeof(uint32_t));
    for (i=0; i<n_rx; i++) {
        rxdata[i] = (uint32_t*)memalign(16,(FRAME_LENGTH_SAMPLES_MAX+1280)*sizeof(uint32_t));
        bzero(rxdata[i],(FRAME_LENGTH_SAMPLES_MAX+1280)*sizeof(uint32_t));
    }
    s_re[0] = (double *)malloc(sdu_length_samples*sizeof(double));
    bzero(s_re[0],sdu_length_samples*sizeof(double));
    s_im[0] = (double *)malloc(sdu_length_samples*sizeof(double));
    bzero(s_im[0],sdu_length_samples*sizeof(double));
    for (i=0; i<n_rx; i++) {
        r_re[i] = (double *)malloc((sdu_length_samples+100)*sizeof(double));
        bzero(r_re[i],(sdu_length_samples+100)*sizeof(double));
        r_im[i] = (double *)malloc((sdu_length_samples+100)*sizeof(double));
        bzero(r_im[i],(sdu_length_samples+100)*sizeof(double));
    }

    ch = new_channel_desc_scm(1,
                              n_rx,
                              channel_model,
                              BW,
                              0.0,
                              0,
                              0);


    if (ch==NULL) {
        printf("Problem generating channel model. Exiting.\n");
        exit(-1);
    }


    phy_tx_start(&tx_vector,txdata,0,FRAME_LENGTH_SAMPLES_MAX,data_ind);

    tx_lev = signal_energy((int32_t*)txdata,320);
    tx_lev_dB = (unsigned int) dB_fixed(tx_lev);

    write_output("txsig0.m","txs", txdata,sdu_length_samples,1,1);

    // multipath channel

    for (i=0; i<sdu_length_samples; i++) {
        s_re[0][i] = (double)(((short *)txdata)[(i<<1)]);
        s_im[0][i] = (double)(((short *)txdata)[(i<<1)+1]);
    }

    for (SNR=snr0; SNR<snr1; SNR+=.2) {

        printf("n_frames %d SNR %f sdu_length %d rate %d\n",n_frames,SNR,tx_vector.sdu_length,tx_vector.rate);
        errors=0;
        misdetected_errors=0;
        signal_errors=0;
        missed_packets=0;
        stop=0;
        for (trial=0; trial<n_frames; trial++) {
            //      printf("Trial %d (errors %d), sdu_length_samples %d\n",trial,errors,sdu_length_samples);
            sigma2_dB = 25; //10*log10((double)tx_lev) - SNR;
            txg_dB = 10*log10((double)tx_lev) - (SNR + sigma2_dB);
            txg = pow(10.0,-.05*txg_dB);
            if (n_frames==1)
                printf("sigma2_dB %f (SNR %f dB) tx_lev_dB %f, txg %f\n",sigma2_dB,SNR,10*log10((double)tx_lev)-txg_dB,txg_dB);
            //AWGN
            sigma2 = pow(10,sigma2_dB/10);
            //      printf("Sigma2 %f (sigma2_dB %f)\n",sigma2,sigma2_dB);

            //          sigma2 = 0;

            multipath_channel(ch,s_re,s_im,r_re,r_im,
                              sdu_length_samples,0);

            if (n_frames==1) {
                printf("rx_level data symbol %f, tx_lev %f\n",
                       10*log10(signal_energy_fp(r_re,r_im,1,80,0)),
                       10*log10(tx_lev));
            }

            for (aa=0; aa<n_rx; aa++) {
                for (i=0; i<(sdu_length_samples+100); i++) {


                    ((short*)&rxdata[aa][tx_offset])[(i<<1)]   = (short) (((txg*r_re[aa][i]) + sqrt(sigma2/2)*gaussdouble(0.0,1.0)));
                    ((short*)&rxdata[aa][tx_offset])[1+(i<<1)] = (short) (((txg*r_im[aa][i]) + (iqim*r_re[aa][i]*txg) + sqrt(sigma2/2)*gaussdouble(0.0,1.0)));

                    //	  if (i<128)
                    //	    printf("i%d : rxdata %d, txdata %d\n",i,((short *)rxdata[aa])[rx_offset+(i<<1)],((short *)txdata)[i<<1]);
                }

                for (i=0; i<tx_offset; i++) {
                    ((short*) rxdata[aa])[(i<<1)]   = (short) (sqrt(sigma2/2)*gaussdouble(0.0,1.0));
                    ((short*) rxdata[aa])[1+(i<<1)] = (short) (sqrt(sigma2/2)*gaussdouble(0.0,1.0));
                }
                for (i=(tx_offset+sdu_length_samples+100); i<FRAME_LENGTH_SAMPLES_MAX; i++) {
                    ((short*) rxdata[aa])[(i<<1)]   = (short) (sqrt(sigma2/2)*gaussdouble(0.0,1.0));
                    ((short*) rxdata[aa])[1+(i<<1)] = (short) (sqrt(sigma2/2)*gaussdouble(0.0,1.0));
                }

            }
            if (n_frames==1) {
                write_output("rxsig0.m","rxs", &rxdata[0][0],FRAME_LENGTH_SAMPLES_MAX,1,1);
            }
            no_detection=1;
            off = 0;
            while(off<FRAME_LENGTH_SAMPLES_MAX) {

                rxp = dB_fixed(signal_energy(rxdata[0]+off,512));
                if (n_frames==1)
                    printf("off %d: rxp %d (%d)\n",off,rxp,signal_energy(rxdata[0]+off,104));

                if (rxp>RX_THRES_dB) {
                    if (off<105)
                        off2 = FRAME_LENGTH_SAMPLES_MAX-105;
                    else
                        off2=off;
                    if ((initial_sync(&rxv,&rx_offset,&log2_maxh,(uint32_t*)rxdata[0],FRAME_LENGTH_SAMPLES_MAX,off2,1) == BUSY)) {
                        if (n_frames==1)
                            printf("Channel is busy, rxv %p, offset %d\n",(void*)rxv,rx_offset);
                        no_detection=0;
                        if (rxv) {
                            if (n_frames==1)
                                printf("Rate %d, SDU_LENGTH %d\n",rxv->rate,rxv->sdu_length);
                            if ( (rxv->rate != tx_vector.rate)||(rxv->sdu_length != tx_vector.sdu_length)) {
                                signal_errors++;
                                if ((signal_errors > (n_frames/10)) && (trial>=100)) {
                                    stop=1;
                                }
                                if (n_frames == 1)
                                    printf("SIGNAL error: rx_offset %d, tx_offset %d (off2 %d)\n",rx_offset,tx_offset,off2);
                                break;
                            }
                            else {
                                memset(data_ind_rx,0,rxv->sdu_length+4+2+1);
                                if (data_detection(rxv,data_ind_rx,(uint32_t*)rxdata[0],FRAME_LENGTH_SAMPLES_MAX,rx_offset,log2_maxh,NULL)) {
                                    for (i=0; i<rxv->sdu_length+6; i++) {
                                        if (data_ind[i]!=data_ind_rx[i]) {
                                            //printf("error position %d : %x,%x\n",i,data_ind[i],data_ind_rx[i]);
                                            misdetected_errors++;
                                            errors++;
                                        }
                                    }
                                    if ((errors > (n_frames/10)) && (trial>100)) {
                                        stop=1;
                                        break;
                                    }
                                } // initial_synch returns IDLE
                                else {
                                    errors++;
                                    if (n_frames == 1) {
                                        printf("Running data_detection fails\n");

                                        for (i=0; i<rxv->sdu_length+6; i++) {
                                            if (data_ind[i]!=data_ind_rx[i]) {
                                                printf("error position %d : %x,%x\n",i,data_ind[i],data_ind_rx[i]);
                                            }
                                        }
                                    }
                                    if ((errors > (n_frames/10)) && (trial>=100)) {
                                        stop=1;
                                        break;
                                    }

                                }
                                break;
                            }
                        }
                    }
                }

                off+=105;
            }
            if (no_detection==1)
                missed_packets++;
            if (stop==1)
                break;
        }

        printf("\nSNR %f dB: errors %d/%d, misdetected errors %d/%d,signal_errors %d/%d, missed_packets %d/%d\n",SNR,errors,trial-signal_errors,misdetected_errors,trial-signal_errors,signal_errors,trial,missed_packets,trial);
        snr_array[cnt] = SNR;
        errors_array[cnt] = errors;
        trials_array[cnt] = trial;
        misdetected_errors_array[cnt] = misdetected_errors;
        signal_errors_array[cnt] = signal_errors;
        missed_packets_array[cnt] = missed_packets;
        cnt++;
        if (cnt>99) {
            printf("too many SNR points, exiting ...\n");
            break;
        }
        if (errors == 0)
            break;
#ifdef EXECTIME
        print_is_stats();
        print_dd_stats();
#endif
    }


    sprintf(fname,"SNR_%d_%d.m",tx_vector.rate,tx_vector.sdu_length);
    sprintf(vname,"SNR_%d_%d_v",tx_vector.rate,tx_vector.sdu_length);
    write_output(fname,vname,snr_array,cnt,1,7);
    sprintf(fname,"errors_%d_%d.m",tx_vector.rate,tx_vector.sdu_length);
    sprintf(vname,"errors_%d_%d_v",tx_vector.rate,tx_vector.sdu_length);
    write_output(fname,vname,errors_array,cnt,1,2);
    sprintf(fname,"trials_%d_%d.m",tx_vector.rate,tx_vector.sdu_length);
    sprintf(vname,"trials_%d_%d_v",tx_vector.rate,tx_vector.sdu_length);
    write_output(fname,vname,trials_array,cnt,1,2);
    sprintf(fname,"signal_errors_%d_%d.m",tx_vector.rate,tx_vector.sdu_length);
    sprintf(vname,"signal_errors_%d_%d_v",tx_vector.rate,tx_vector.sdu_length);
    write_output(fname,vname,signal_errors_array,cnt,1,2);
    free(data_ind);
    free(data_ind_rx);
    //  free_channel_desc_scm(ch);

    free(txdata);
    for (i=0; i<n_rx; i++) {
        free(rxdata[i]);
    }

    free(s_re[0]);
    free(s_im[0]);

    for (i=0; i<n_rx; i++) {
        free(r_re[i]);
        free(r_im[i]);
    }

    return(0);

}
Esempio n. 11
0
int main( int argc, char **argv )
{
    if ( use_gui )
    {
        printf("init_sdl()\n");
        if ( init_sdl() ) return 1;

        printf("init_gl()\n");
        init_gl();
    }

    printf("init_fft()\n");
    init_fft();

#ifdef USE_FIFO
    printf("init_mpd()\n");
    if ( init_mpd() ) return 1;
#endif
#ifdef USE_ALSA
    printf("init_alsa()\n");
    if ( init_alsa() ) return 1;
#endif

    if ( use_serial )
    {
        printf("init_serial()\n");
        if ( init_serial() ) use_serial = FALSE;
    }

    init_lights();
    init_table();

    pthread_t sample_thread;

    pthread_create(&sample_thread, NULL, &get_samples, NULL);

    while ( !done )
    {

        // check to see if we have a new sample
        if (new_sample == 1)
        {
            // we are going to process this sample, it is no longer new
            pthread_mutex_lock(&sample_mutex);
            new_sample = 0;
            pthread_mutex_unlock(&sample_mutex);

            do_fft();

            detect_beats();

            assign_lights();

            //assign_cells();

            if ( use_gui )
            {
                if (handle_sdl_events()) return 1;
                draw_all();
            }

            if ( use_serial ) send_serial_fpga();
        }

        usleep(5000);
    }

    return 0;
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    int c;
    struct pa_fft *ctx = calloc(1, sizeof(struct pa_fft));
    ctx->cont = 1;

    if (argc < 2 || !strcmp(argv[1], "-h")) {
        print_help();
        return 1;
    }

    ctx->width = 1200;
    ctx->height = 500;
    ctx->buffer_samples = 1024;
    ctx->dev = NULL;
    ctx->log_graph = 1;
    ctx->no_refresh = 0;
    ctx->overlap = 0;
    ctx->frame_avg = 2;
    ctx->start_low = 1;
    ctx->win_type = WINDOW_BLACKMAN_HARRIS;
    ctx->fft_flags = FFTW_PATIENT | FFTW_DESTROY_INPUT;

    const char *opt_str = "lonhd:a:c:s:w:";
    while ((c = getopt (argc, argv, opt_str)) != -1) {
        switch (c) {
            case 'l':
                ctx->log_graph = 0;
                break;
            case 'o':
                ctx->overlap = 1;
                break;
            case 'n':
                ctx->no_refresh = 1;
                break;
            case 'd':
                ctx->dev = strdup(optarg);
                break;
            case 'h':
                print_help();
                return 0;
                break;
            case 'a':
                sscanf(optarg, "%u", &ctx->frame_avg);
                break;
            case 'c':
                sscanf(optarg, "%u", &ctx->start_low);
                break;
            case 's':
                sscanf(optarg, "%u", &ctx->buffer_samples);
                break;
            case 'w':
                if (!strcmp(optarg, "triangle"))
                    ctx->win_type = WINDOW_TRIANGLE;
                else if (!strcmp(optarg, "hanning"))
                    ctx->win_type = WINDOW_HANNING;
                else if (!strcmp(optarg, "hamming"))
                    ctx->win_type = WINDOW_HAMMING;
                else if (!strcmp(optarg, "blackman"))
                    ctx->win_type = WINDOW_BLACKMAN;
                else if (!strcmp(optarg, "blackman-harris"))
                    ctx->win_type = WINDOW_BLACKMAN_HARRIS;
                else if (!strcmp(optarg, "welch"))
                    ctx->win_type = WINDOW_WELCH;
                else if (!strcmp(optarg, "flat"))
                    ctx->win_type = WINDOW_FLAT;
                else
                    fprintf(stderr, "Unknown window \"%s\"\n", optarg);
                break;
            case '?':
                for (int i = 0; i < sizeof(opt_str); i++) {
                    if (opt_str[i] == optopt) {
                        fprintf (stderr, "Option -%c requires an argument.\n", optopt);
                    }
                }
            default:
                abort();
        }
    }

    init_pulse(ctx);
    init_buffers(ctx);
    init_fft(ctx);

    if (!ctx->cont) {
        ctx->cont = 2;
        deinit_fft(ctx);
        return 1;
    }

    pthread_create(&ctx->thread, NULL, pa_fft_thread, ctx);

    while(ctx->cont) {
        sleep(1);
    }

    return 0;
}
Esempio n. 13
0
int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;


    if (argc < 2)
    {
     fprintf(stderr,"ERROR, no host provided\n");
     exit(1);
    }
    portno = 51717;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error1("ERROR opening socket");
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(-1);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
        fprintf(stderr, "Error on connect(): %s\n", strerror(errno));
        exit(-1);
    }
    

    ///////////////////////////////////////////////////////////////////////////////////////////

    int bytesToNextHeader = 5; // total amount of space (header+data)
    int samplesToNextFFT = 3; // Num samples to the start of the next FFT
    int ptsPerFFT = 256; // number of points per FFT
    int sampFreq = 4;
    int endTrans = -1;
    
    init_fft(bytesToNextHeader, samplesToNextFFT, ptsPerFFT, sampFreq, endTrans);
    int header_len = sizeof(struct fft_header);
    
        
        float fbuffer[ptsPerFFT/2+1];	///changesssss
        int i, j;

    int k = 0;
    while(1){
    //while(k < 5){
        fprintf(stderr, "Sending header... ");

        n = write(sockfd, (char *) hdr, header_len);
        fprintf(stderr, "Sent header, n = %d\n", n);
        if (n < 0)
             error1("ERROR writing to socket");

        genfft(fbuffer, ptsPerFFT);
        
        printf("Sending fbuffer\n");
        fprintf(stderr, "Sending data... ");
        n = write(sockfd, fbuffer, (ptsPerFFT/2+1) * sizeof(float));	///changesssss
        fprintf(stderr, "Sent data, n = %d\n", n);
        if (n < 0)
             error1("ERROR writing to socket");

       // usleep(500 * 1000);
        k++;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////
    

    close(sockfd);
    return 0;
}
Esempio n. 14
0
/*INIT PROCESSING -Set up the environment for the signal processing*/
void init_processing(){
    size_of_sendarray = init_fft(SAMPLES_PER_PULSE);
    start = calloc(DATA_BUFFER_SIZE, sizeof(char));
    ifft_array = calloc(size_of_sendarray, sizeof(rdata_t));

}
Esempio n. 15
0
void L3psycho_anal( lame_global_flags *gfp,
                    short int *buffer[2],int gr_out , 
                    FLOAT8 *ms_ratio,
                    FLOAT8 *ms_ratio_next,
		    FLOAT8 *ms_ener_ratio,
		    III_psy_ratio masking_ratio[2][2],
		    III_psy_ratio masking_MS_ratio[2][2],
		    FLOAT8 percep_entropy[2],FLOAT8 percep_MS_entropy[2], 
                    int blocktype_d[2])
{

/* to get a good cache performance, one has to think about
 * the sequence, in which the variables are used
 */
  
/* The static variables "r", "phi_sav", "new", "old" and "oldest" have    */
/* to be remembered for the unpredictability measure.  For "r" and        */
/* "phi_sav", the first index from the left is the channel select and     */
/* the second index is the "age" of the data.                             */
  static FLOAT8	minval[CBANDS],qthr_l[CBANDS];
  static FLOAT8	qthr_s[CBANDS];
  static FLOAT8	nb_1[4][CBANDS], nb_2[4][CBANDS];
  static FLOAT8 s3_s[CBANDS + 1][CBANDS + 1];
  static FLOAT8 s3_l[CBANDS + 1][CBANDS + 1];

  static III_psy_xmin thm[4];
  static III_psy_xmin en[4];
  
  /* unpredictability calculation
   */
  static int cw_upper_index;
  static int cw_lower_index;
  static FLOAT ax_sav[4][2][HBLKSIZE];
  static FLOAT bx_sav[4][2][HBLKSIZE];
  static FLOAT rx_sav[4][2][HBLKSIZE];
  static FLOAT cw[HBLKSIZE];

  /* fft and energy calculation
   */
  FLOAT (*wsamp_l)[BLKSIZE];
  FLOAT (*wsamp_s)[3][BLKSIZE_s];
  FLOAT tot_ener[4];
  static FLOAT wsamp_L[2][BLKSIZE];
  static FLOAT energy[HBLKSIZE];
  static FLOAT wsamp_S[2][3][BLKSIZE_s];
  static FLOAT energy_s[3][HBLKSIZE_s];

  /* convolution
   */
  static FLOAT8 eb[CBANDS];
  static FLOAT8 cb[CBANDS];
  static FLOAT8 thr[CBANDS];
  
  /* Scale Factor Bands
   */
  static FLOAT8	w1_l[SBPSY_l], w2_l[SBPSY_l];
  static FLOAT8	w1_s[SBPSY_s], w2_s[SBPSY_s];
  static FLOAT8 mld_l[SBPSY_l],mld_s[SBPSY_s];
  static int	bu_l[SBPSY_l],bo_l[SBPSY_l] ;
  static int	bu_s[SBPSY_s],bo_s[SBPSY_s] ;
  static int	npart_l,npart_s;
  static int	npart_l_orig,npart_s_orig;
  
  static int	s3ind[CBANDS][2];
  static int	s3ind_s[CBANDS][2];

  static int	numlines_s[CBANDS] ;
  static int	numlines_l[CBANDS];
  static int	partition_l[HBLKSIZE];
  
  /* frame analyzer 
   */
#ifdef HAVEGTK
  static FLOAT energy_save[4][HBLKSIZE];
  static FLOAT8 pe_save[4];
  static FLOAT8 ers_save[4];
#endif

  /* ratios 
   */
  static FLOAT8 pe[4]={0,0,0,0};
  static FLOAT8 ms_ratio_s_old=0,ms_ratio_l_old=0;
  static FLOAT8 ms_ener_ratio_old=.25;
  FLOAT8 ms_ratio_l=0,ms_ratio_s=0;

  /* block type 
   */
  static int	blocktype_old[2];
  int blocktype[2],uselongblock[2];
  
  /* usual variables like loop indices, etc..
   */
  int numchn, chn;
  int   b, i, j, k;
  int	sb,sblock;
  FLOAT cwlimit;


  /* initialization of static variables
   */
  if((gfp->frameNum==0) && (gr_out==0)){
    FLOAT8	SNR_s[CBANDS];
    
    blocktype_old[0]=STOP_TYPE;
    blocktype_old[1]=STOP_TYPE;
    i = gfp->out_samplerate;
    switch(i){
    case 32000: break;
    case 44100: break;
    case 48000: break;
    case 16000: break;
    case 22050: break;
    case 24000: break;
    default:    fprintf(stderr,"error, invalid sampling frequency: %d Hz\n",i);
      exit(-1);
    }
    
    /* reset states used in unpredictability measure */
    memset (rx_sav,0, sizeof(rx_sav));
    memset (ax_sav,0, sizeof(ax_sav));
    memset (bx_sav,0, sizeof(bx_sav));
    memset (en,0, sizeof(en));
    memset (thm,0, sizeof(thm));
    

    /*  gfp->cwlimit = sfreq*j/1024.0;  */
    cw_lower_index=6;
    if (gfp->cwlimit>0) 
      cwlimit=gfp->cwlimit;
    else
      cwlimit=8.8717;
    cw_upper_index = cwlimit*1000.0*1024.0/((FLOAT8) gfp->out_samplerate);
    cw_upper_index=Min(HBLKSIZE-4,cw_upper_index);      /* j+3 < HBLKSIZE-1 */
    cw_upper_index=Max(6,cw_upper_index);

    for ( j = 0; j < HBLKSIZE; j++ )
      cw[j] = 0.4;
    
    /* setup stereo demasking thresholds */
    /* formula reverse enginerred from plot in paper */
    for ( sb = 0; sb < SBPSY_s; sb++ ) {
      FLOAT8 mld = 1.25*(1-cos(PI*sb/SBPSY_s))-2.5;
      mld_s[sb] = pow(10.0,mld);
    }
    for ( sb = 0; sb < SBPSY_l; sb++ ) {
      FLOAT8 mld = 1.25*(1-cos(PI*sb/SBPSY_l))-2.5;
      mld_l[sb] = pow(10.0,mld);
    }
    
    for (i=0;i<HBLKSIZE;i++) partition_l[i]=-1;

    L3para_read( (FLOAT8) gfp->out_samplerate,numlines_l,numlines_s,partition_l,minval,qthr_l,s3_l,s3_s,
		 qthr_s,SNR_s,
		 bu_l,bo_l,w1_l,w2_l, bu_s,bo_s,w1_s,w2_s );
    
    
    /* npart_l_orig   = number of partition bands before convolution */
    /* npart_l  = number of partition bands after convolution */
    npart_l_orig=0; npart_s_orig=0;
    for (i=0;i<HBLKSIZE;i++) 
      if (partition_l[i]>npart_l_orig) npart_l_orig=partition_l[i];
    npart_l_orig++;

    for (i=0;numlines_s[i]>=0;i++)
      ;
    npart_s_orig = i;
    
    npart_l=bo_l[SBPSY_l-1]+1;
    npart_s=bo_s[SBPSY_s-1]+1;

    /* MPEG2 tables are screwed up 
     * the mapping from paritition bands to scalefactor bands will use
     * more paritition bands than we have.  
     * So we will not compute these fictitious partition bands by reducing
     * npart_l below.  */
    if (npart_l > npart_l_orig) {
      npart_l=npart_l_orig;
      bo_l[SBPSY_l-1]=npart_l-1;
      w2_l[SBPSY_l-1]=1.0;
    }
    if (npart_s > npart_s_orig) {
      npart_s=npart_s_orig;
      bo_s[SBPSY_s-1]=npart_s-1;
      w2_s[SBPSY_s-1]=1.0;
    }
    
    
    
    for (i=0; i<npart_l; i++) {
      for (j = 0; j < npart_l_orig; j++) {
	if (s3_l[i][j] != 0.0)
	  break;
      }
      s3ind[i][0] = j;
      
      for (j = npart_l_orig - 1; j > 0; j--) {
	if (s3_l[i][j] != 0.0)
	  break;
      }
      s3ind[i][1] = j;
    }


    for (i=0; i<npart_s; i++) {
      for (j = 0; j < npart_s_orig; j++) {
	if (s3_s[i][j] != 0.0)
	  break;
      }
      s3ind_s[i][0] = j;
      
      for (j = npart_s_orig - 1; j > 0; j--) {
	if (s3_s[i][j] != 0.0)
	  break;
      }
      s3ind_s[i][1] = j;
    }
    
    
    /*  
      #include "debugscalefac.c"
    */
    

#define AACS3
#define NEWS3XX

#ifdef AACS3
    /* AAC values, results in more masking over MP3 values */
# define TMN 18
# define NMT 6
#else
    /* MP3 values */
# define TMN 29
# define NMT 6
#endif

#define rpelev 2
#define rpelev2 16

    /* compute norm_l, norm_s instead of relying on table data */
    for ( b = 0;b < npart_l; b++ ) {
      FLOAT8 norm=0;
      for ( k = s3ind[b][0]; k <= s3ind[b][1]; k++ ) {
	norm += s3_l[b][k];
      }
      for ( k = s3ind[b][0]; k <= s3ind[b][1]; k++ ) {
	s3_l[b][k] *= exp(-LN_TO_LOG10 * NMT) / norm;
      }
      /*printf("%i  norm=%f  norm_l=%f \n",b,1/norm,norm_l[b]);*/
    }

    /* MPEG1 SNR_s data is given in db, convert to energy */
    if (gfp->version == 1) {
      for ( b = 0;b < npart_s; b++ ) {
	SNR_s[b]=exp( (FLOAT8) SNR_s[b] * LN_TO_LOG10 );
      }
    }

    for ( b = 0;b < npart_s; b++ ) {
      FLOAT8 norm=0;
      for ( k = s3ind_s[b][0]; k <= s3ind_s[b][1]; k++ ) {
	norm += s3_s[b][k];
      }
      for ( k = s3ind_s[b][0]; k <= s3ind_s[b][1]; k++ ) {
	s3_s[b][k] *= SNR_s[b] / norm;
      }
      /*printf("%i  norm=%f  norm_s=%f \n",b,1/norm,norm_l[b]);*/
    }
    
    init_fft();
  }
  /************************* End of Initialization *****************************/
  


  
  
  numchn = gfp->stereo;
  /* chn=2 and 3 = Mid and Side channels */
  if (gfp->mode == MPG_MD_JOINT_STEREO) numchn=4;
  for (chn=0; chn<numchn; chn++) {
  
    wsamp_s = wsamp_S+(chn & 1);
    wsamp_l = wsamp_L+(chn & 1);


    if (chn<2) {    
      /**********************************************************************
       *  compute FFTs
       **********************************************************************/
      fft_long ( *wsamp_l, chn, buffer);
      fft_short( *wsamp_s, chn, buffer); 
      
      /* LR maskings  */
      percep_entropy[chn] = pe[chn]; 
      masking_ratio[gr_out][chn].thm = thm[chn];
      masking_ratio[gr_out][chn].en = en[chn];
    }else{
      /* MS maskings  */
      percep_MS_entropy[chn-2] = pe[chn]; 
      masking_MS_ratio[gr_out][chn-2].en = en[chn];
      masking_MS_ratio[gr_out][chn-2].thm = thm[chn];
      
      if (chn == 2)
      {
        for (j = BLKSIZE-1; j >=0 ; --j)
        {
          FLOAT l = wsamp_L[0][j];
          FLOAT r = wsamp_L[1][j];
          wsamp_L[0][j] = (l+r)*(FLOAT)(SQRT2*0.5);
          wsamp_L[1][j] = (l-r)*(FLOAT)(SQRT2*0.5);
        }
        for (b = 2; b >= 0; --b)
        {
          for (j = BLKSIZE_s-1; j >= 0 ; --j)
          {
            FLOAT l = wsamp_S[0][b][j];
            FLOAT r = wsamp_S[1][b][j];
            wsamp_S[0][b][j] = (l+r)*(FLOAT)(SQRT2*0.5);
            wsamp_S[1][b][j] = (l-r)*(FLOAT)(SQRT2*0.5);
          }
        }
      }
    }

    /**********************************************************************
     *  compute energies
     **********************************************************************/
    
    
    
    energy[0]  = (*wsamp_l)[0];
    energy[0] *= energy[0];
    
    tot_ener[chn] = energy[0]; /* sum total energy at nearly no extra cost */
    
    for (j=BLKSIZE/2-1; j >= 0; --j)
    {
      FLOAT re = (*wsamp_l)[BLKSIZE/2-j];
      FLOAT im = (*wsamp_l)[BLKSIZE/2+j];
      energy[BLKSIZE/2-j] = (re * re + im * im) * (FLOAT)0.5;
      
      tot_ener[chn] += energy[BLKSIZE/2-j];
    }
    for (b = 2; b >= 0; --b)
    {
      energy_s[b][0]  = (*wsamp_s)[b][0];
      energy_s[b][0] *=  energy_s [b][0];
      for (j=BLKSIZE_s/2-1; j >= 0; --j)
      {
        FLOAT re = (*wsamp_s)[b][BLKSIZE_s/2-j];
        FLOAT im = (*wsamp_s)[b][BLKSIZE_s/2+j];
        energy_s[b][BLKSIZE_s/2-j] = (re * re + im * im) * (FLOAT)0.5;
      }
    }


#ifdef HAVEGTK
  if(gfp->gtkflag) {
    for (j=0; j<HBLKSIZE ; j++) {
      pinfo->energy[gr_out][chn][j]=energy_save[chn][j];
      energy_save[chn][j]=energy[j];
    }
  }
#endif
    
    /**********************************************************************
     *    compute unpredicatability of first six spectral lines            * 
     **********************************************************************/
    for ( j = 0; j < cw_lower_index; j++ )
      {	 /* calculate unpredictability measure cw */
	FLOAT an, a1, a2;
	FLOAT bn, b1, b2;
	FLOAT rn, r1, r2;
	FLOAT numre, numim, den;

	a2 = ax_sav[chn][1][j];
	b2 = bx_sav[chn][1][j];
	r2 = rx_sav[chn][1][j];
	a1 = ax_sav[chn][1][j] = ax_sav[chn][0][j];
	b1 = bx_sav[chn][1][j] = bx_sav[chn][0][j];
	r1 = rx_sav[chn][1][j] = rx_sav[chn][0][j];
	an = ax_sav[chn][0][j] = (*wsamp_l)[j];
	bn = bx_sav[chn][0][j] = j==0 ? (*wsamp_l)[0] : (*wsamp_l)[BLKSIZE-j];  
	rn = rx_sav[chn][0][j] = sqrt(energy[j]);

	{ /* square (x1,y1) */
	  if( r1 != 0 ) {
	    numre = (a1*b1);
	    numim = (a1*a1-b1*b1)*(FLOAT)0.5;
	    den = r1*r1;
	  } else {
	    numre = 1;
	    numim = 0;
	    den = 1;
	  }
	}
	
	{ /* multiply by (x2,-y2) */
	  if( r2 != 0 ) {
	    FLOAT tmp2 = (numim+numre)*(a2+b2)*(FLOAT)0.5;
	    FLOAT tmp1 = -a2*numre+tmp2;
	    numre =       -b2*numim+tmp2;
	    numim = tmp1;
	    den *= r2;
	  } else {
	    /* do nothing */
	  }
	}
	
	{ /* r-prime factor */
	  FLOAT tmp = (2*r1-r2)/den;
	  numre *= tmp;
	  numim *= tmp;
	}
	den=rn+fabs(2*r1-r2);
	if( den != 0 ) {
	  numre = (an+bn)*(FLOAT)0.5-numre;
	  numim = (an-bn)*(FLOAT)0.5-numim;
	  den = sqrt(numre*numre+numim*numim)/den;
	}
	cw[j] = den;
      }



    /**********************************************************************
     *     compute unpredicatibility of next 200 spectral lines            *
     **********************************************************************/ 
    for ( j = cw_lower_index; j < cw_upper_index; j += 4 )
      {/* calculate unpredictability measure cw */
	FLOAT rn, r1, r2;
	FLOAT numre, numim, den;
	
	k = (j+2) / 4; 
	
	{ /* square (x1,y1) */
	  r1 = energy_s[0][k];
	  if( r1 != 0 ) {
	    FLOAT a1 = (*wsamp_s)[0][k]; 
	    FLOAT b1 = (*wsamp_s)[0][BLKSIZE_s-k]; /* k is never 0 */
	    numre = (a1*b1);
	    numim = (a1*a1-b1*b1)*(FLOAT)0.5;
	    den = r1;
	    r1 = sqrt(r1);
	  } else {
	    numre = 1;
	    numim = 0;
	    den = 1;
	  }
	}
	
	
	{ /* multiply by (x2,-y2) */
	  r2 = energy_s[2][k];
	  if( r2 != 0 ) {
	    FLOAT a2 = (*wsamp_s)[2][k]; 
	    FLOAT b2 = (*wsamp_s)[2][BLKSIZE_s-k];
	    
	    
	    FLOAT tmp2 = (numim+numre)*(a2+b2)*(FLOAT)0.5;
	    FLOAT tmp1 = -a2*numre+tmp2;
	    numre =       -b2*numim+tmp2;
	    numim = tmp1;
	    
	    r2 = sqrt(r2);
	    den *= r2;
	  } else {
	    /* do nothing */
	  }
	}
	
	{ /* r-prime factor */
	  FLOAT tmp = (2*r1-r2)/den;
	  numre *= tmp;
	  numim *= tmp;
	}
	
	rn = sqrt(energy_s[1][k]);
	den=rn+fabs(2*r1-r2);
	if( den != 0 ) {
	  FLOAT an = (*wsamp_s)[1][k]; 
	  FLOAT bn = (*wsamp_s)[1][BLKSIZE_s-k];
	  numre = (an+bn)*(FLOAT)0.5-numre;
	  numim = (an-bn)*(FLOAT)0.5-numim;
	  den = sqrt(numre*numre+numim*numim)/den;
	}
	
	cw[j+1] = cw[j+2] = cw[j+3] = cw[j] = den;
      }
    
#if 0
    for ( j = 14; j < HBLKSIZE-4; j += 4 )
      {/* calculate energy from short ffts */
	FLOAT8 tot,ave;
	k = (j+2) / 4; 
	for (tot=0, sblock=0; sblock < 3; sblock++)
	  tot+=energy_s[sblock][k];
	ave = energy[j+1]+ energy[j+2]+ energy[j+3]+ energy[j];
	ave /= 4.;
	/*
	  printf("energy / tot %i %5.2f   %e  %e\n",j,ave/(tot*16./3.),
	  ave,tot*16./3.);
	*/
	energy[j+1] = energy[j+2] = energy[j+3] =  energy[j]=tot;
      }
#endif
    
    
    
    
    
    
    
    
    /**********************************************************************
     *    Calculate the energy and the unpredictability in the threshold   *
     *    calculation partitions                                           *
     **********************************************************************/
#if 0
    for ( b = 0; b < CBANDS; b++ )
      {
	eb[b] = 0;
	cb[b] = 0;
      }
    for ( j = 0; j < HBLKSIZE; j++ )
      {
	int tp = partition_l[j];
	
	if ( tp >= 0 )
	  {
	    eb[tp] += energy[j];
	    cb[tp] += cw[j] * energy[j];
	  }
	assert(tp<npart_l_orig);
      }
#else
    b = 0;
    for (j = 0; j < cw_upper_index;)
      {
	FLOAT8 ebb, cbb;
	int i;

	ebb = energy[j];
	cbb = energy[j] * cw[j];
	j++;

	for (i = numlines_l[b] - 1; i > 0; i--)
	  {
	    ebb += energy[j];
	    cbb += energy[j] * cw[j];
	    j++;
	  }
	eb[b] = ebb;
	cb[b] = cbb;
	b++;
      }

    for (; b < npart_l_orig; b++ )
      {
	int i;
	FLOAT8 ebb = energy[j++];

	for (i = numlines_l[b] - 1; i > 0; i--)
	  {
	    ebb += energy[j++];
	  }
	eb[b] = ebb;
	cb[b] = ebb * 0.4;
      }
#endif

    /**********************************************************************
     *      convolve the partitioned energy and unpredictability           *
     *      with the spreading function, s3_l[b][k]                        *
     ******************************************************************** */
    pe[chn] = 0;		/*  calculate percetual entropy */
    for ( b = 0;b < npart_l; b++ )
      {
	FLOAT8 tbb,ecb,ctb;
	FLOAT8 temp_1; /* BUG of IS */

	ecb = 0;
	ctb = 0;
	for ( k = s3ind[b][0]; k <= s3ind[b][1]; k++ )
	  {
	    ecb += s3_l[b][k] * eb[k];	/* sprdngf for Layer III */
	    ctb += s3_l[b][k] * cb[k];
	  }

	/* calculate the tonality of each threshold calculation partition */
	/* calculate the SNR in each threshhold calculation partition */

	tbb = ecb;
	if (tbb != 0)
	  {
	    tbb = ctb / tbb;
	    if (tbb <= 0.04875584301)
	      {
		tbb = exp(-LN_TO_LOG10 * (TMN - NMT));
	      }
	    else if (tbb > 0.4989003827)
	      {
		tbb = 1;
	      }
	    else
	      {
		tbb = log(tbb);
		tbb = exp(((TMN - NMT)*(LN_TO_LOG10*0.299))
			+ ((TMN - NMT)*(LN_TO_LOG10*0.43 ))*tbb);  /* conv1=-0.299, conv2=-0.43 */
	      }
	  }

	tbb = Min(minval[b], tbb);
	ecb *= tbb;

	/* pre-echo control */
	/* rpelev=2.0, rpelev2=16.0 */
	temp_1 = Min(ecb, Min(rpelev*nb_1[chn][b],rpelev2*nb_2[chn][b]) );
	thr[b] = Max( qthr_l[b], temp_1 ); 
	nb_2[chn][b] = nb_1[chn][b];
	nb_1[chn][b] = ecb;

	/* note: all surges in PE are because of the above pre-echo formula
	 * for temp_1.  it this is not used, PE is always around 600
	 */

	if (thr[b] < eb[b])
	  {
	    /* there's no non sound portition, because thr[b] is
	     maximum of qthr_l and temp_1 */
	    pe[chn] -= numlines_l[b] * log(thr[b] / eb[b]);
	  }
      }


#ifdef HAVEGTK
    if (gfp->gtkflag) {
      FLOAT mn,mx,ma=0,mb=0,mc=0;

      for ( j = HBLKSIZE_s/2; j < HBLKSIZE_s; j ++)
      {
        ma += energy_s[0][j];
        mb += energy_s[1][j];
        mc += energy_s[2][j];
      }
      mn = Min(ma,mb);
      mn = Min(mn,mc);
      mx = Max(ma,mb);
      mx = Max(mx,mc);

      pinfo->ers[gr_out][chn]=ers_save[chn];
      ers_save[chn]=mx/(1e-12+mn);
      pinfo->pe[gr_out][chn]=pe_save[chn];
      pe_save[chn]=pe[chn];
    }
#endif
    
    /*************************************************************** 
     * determine the block type (window type) based on L & R channels
     * 
     ***************************************************************/
    if (chn<2) {
      if (gfp->no_short_blocks){
	uselongblock[chn]=1;
      } else {
	/* tuned for t1.wav.  doesnt effect most other samples */
	if (pe[chn] > 3000) {
	  uselongblock[chn]=0;
	} else { 
	  FLOAT mn,mx,ma=0,mb=0,mc=0;
	
	  for ( j = HBLKSIZE_s/2; j < HBLKSIZE_s; j ++)
	  {
	      ma += energy_s[0][j];
	      mb += energy_s[1][j];
	      mc += energy_s[2][j];
	  }
	  mn = Min(ma,mb);
	  mn = Min(mn,mc);
	  mx = Max(ma,mb);
	  mx = Max(mx,mc);

	  uselongblock[chn] = 1;
	  
	  if ( mx > 30*mn ) 
	  {/* big surge of energy - always use short blocks */
	    uselongblock[chn] = 0;
	  } 
	  else if ((mx > 10*mn) && (pe[chn] > 1000))
	  {/* medium surge, medium pe - use short blocks */
	    uselongblock[chn] = 0;
	  }
	} 
      }
    }



    /*************************************************************** 
     * compute masking thresholds for both short and long blocks
     ***************************************************************/
    /* longblock threshold calculation (part 2) */
    for ( sb = 0; sb < SBPSY_l; sb++ )
      {
	FLOAT8 enn = w1_l[sb] * eb[bu_l[sb]] + w2_l[sb] * eb[bo_l[sb]];
	FLOAT8 thmm = w1_l[sb] *thr[bu_l[sb]] + w2_l[sb] * thr[bo_l[sb]];
	for ( b = bu_l[sb]+1; b < bo_l[sb]; b++ )
	  {
	    enn  += eb[b];
	    thmm += thr[b];
	  }
	en[chn].l[sb] = enn;
	thm[chn].l[sb] = thmm;
      }
    
    
    /* threshold calculation for short blocks */
    for ( sblock = 0; sblock < 3; sblock++ )
      {
	j = 0;
	for ( b = 0; b < npart_s_orig; b++ )
	  {
	    int i;
	    FLOAT ecb = energy_s[sblock][j++];
	    for (i = numlines_s[b]; i > 0; i--)
	      {
		ecb += energy_s[sblock][j++];
	      }
	    eb[b] = ecb;
	  }

	for ( b = 0; b < npart_s; b++ )
	  {
	    FLOAT8 ecb = 0;
	    for ( k = s3ind_s[b][0]; k <= s3ind_s[b][1]; k++ )
	      {
		ecb += s3_s[b][k] * eb[k];
	      }
	    thr[b] = Max (qthr_s[b], ecb);
	  }

	for ( sb = 0; sb < SBPSY_s; sb++ )
	  {
	    FLOAT8 enn  = w1_s[sb] * eb[bu_s[sb]] + w2_s[sb] * eb[bo_s[sb]];
	    FLOAT8 thmm = w1_s[sb] *thr[bu_s[sb]] + w2_s[sb] * thr[bo_s[sb]];
	    for ( b = bu_s[sb]+1; b < bo_s[sb]; b++ )
	      {
		enn  += eb[b];
		thmm += thr[b];
	      }
	    en[chn].s[sb][sblock] = enn;
	    thm[chn].s[sb][sblock] = thmm;
	  }
      }
  } /* end loop over chn */


  /* compute M/S thresholds from Johnston & Ferreira 1992 ICASSP paper */
  if ( numchn==4 /* mid/side and r/l */) {
    FLOAT8 rside,rmid,mld;
    int chmid=2,chside=3; 
    
    for ( sb = 0; sb < SBPSY_l; sb++ ) {
      /* use this fix if L & R masking differs by 2db or less */
      /* if db = 10*log10(x2/x1) < 2 */
      /* if (x2 < 1.58*x1) { */
      if (thm[0].l[sb] <= 1.58*thm[1].l[sb]
	  && thm[1].l[sb] <= 1.58*thm[0].l[sb]) {

	mld = mld_l[sb]*en[chside].l[sb];
	rmid = Max(thm[chmid].l[sb], Min(thm[chside].l[sb],mld));

	mld = mld_l[sb]*en[chmid].l[sb];
	rside = Max(thm[chside].l[sb],Min(thm[chmid].l[sb],mld));

	thm[chmid].l[sb]=rmid;
	thm[chside].l[sb]=rside;
      }
    }
    for ( sb = 0; sb < SBPSY_s; sb++ ) {
      for ( sblock = 0; sblock < 3; sblock++ ) {
	if (thm[0].s[sb][sblock] <= 1.58*thm[1].s[sb][sblock]
	    && thm[1].s[sb][sblock] <= 1.58*thm[0].s[sb][sblock]) {

	  mld = mld_s[sb]*en[chside].s[sb][sblock];
	  rmid = Max(thm[chmid].s[sb][sblock],Min(thm[chside].s[sb][sblock],mld));

	  mld = mld_s[sb]*en[chmid].s[sb][sblock];
	  rside = Max(thm[chside].s[sb][sblock],Min(thm[chmid].s[sb][sblock],mld));

	  thm[chmid].s[sb][sblock]=rmid;
	  thm[chside].s[sb][sblock]=rside;
	}
      }
    }
  }


  

  
  
  if (gfp->mode == MPG_MD_JOINT_STEREO)  {
    /* determin ms_ratio from masking thresholds*/
    /* use ms_stereo (ms_ratio < .35) if average thresh. diff < 5 db */
    FLOAT8 db,x1,x2,sidetot=0,tot=0;
    for (sb= SBPSY_l/4 ; sb< SBPSY_l; sb ++ ) {
      x1 = Min(thm[0].l[sb],thm[1].l[sb]);
      x2 = Max(thm[0].l[sb],thm[1].l[sb]);
      /* thresholds difference in db */
      if (x2 >= 1000*x1)  db=3;
      else db = log10(x2/x1);  
      /*  printf("db = %f %e %e  \n",db,thm[0].l[sb],thm[1].l[sb]);*/
      sidetot += db;
      tot++;
    }
    ms_ratio_l= (sidetot/tot)*0.7; /* was .35*(sidetot/tot)/5.0*10 */
    ms_ratio_l = Min(ms_ratio_l,0.5);
    
    sidetot=0; tot=0;
    for ( sblock = 0; sblock < 3; sblock++ )
      for ( sb = SBPSY_s/4; sb < SBPSY_s; sb++ ) {
	x1 = Min(thm[0].s[sb][sblock],thm[1].s[sb][sblock]);
	x2 = Max(thm[0].s[sb][sblock],thm[1].s[sb][sblock]);
	/* thresholds difference in db */
	if (x2 >= 1000*x1)  db=3;
	else db = log10(x2/x1);  
	sidetot += db;
	tot++;
      }
    ms_ratio_s = (sidetot/tot)*0.7; /* was .35*(sidetot/tot)/5.0*10 */
    ms_ratio_s = Min(ms_ratio_s,.5);
  }

  /*************************************************************** 
   * determin final block type
   ***************************************************************/

  for (chn=0; chn<gfp->stereo; chn++) {
    blocktype[chn] = NORM_TYPE;
  }


  if (gfp->stereo==2) {
    if (!gfp->allow_diff_short || gfp->mode==MPG_MD_JOINT_STEREO) {
      /* force both channels to use the same block type */
      /* this is necessary if the frame is to be encoded in ms_stereo.  */
      /* But even without ms_stereo, FhG  does this */
      int bothlong= (uselongblock[0] && uselongblock[1]);
      if (!bothlong) {
	uselongblock[0]=0;
	uselongblock[1]=0;
      }
    }
  }

  
  
  /* update the blocktype of the previous granule, since it depends on what
   * happend in this granule */
  for (chn=0; chn<gfp->stereo; chn++) {
    if ( uselongblock[chn])
      {				/* no attack : use long blocks */
	switch( blocktype_old[chn] ) 
	  {
	  case NORM_TYPE:
	  case STOP_TYPE:
	    blocktype[chn] = NORM_TYPE;
	    break;
	  case SHORT_TYPE:
	    blocktype[chn] = STOP_TYPE; 
	    break;
	  case START_TYPE:
	    fprintf( stderr, "Error in block selecting\n" );
	    abort();
	    break; /* problem */
	  }
      } else   {
	/* attack : use short blocks */
	blocktype[chn] = SHORT_TYPE;
	if ( blocktype_old[chn] == NORM_TYPE ) {
	  blocktype_old[chn] = START_TYPE;
	}
	if ( blocktype_old[chn] == STOP_TYPE ) {
	  blocktype_old[chn] = SHORT_TYPE ;
	}
      }
    
    blocktype_d[chn] = blocktype_old[chn];  /* value returned to calling program */
    blocktype_old[chn] = blocktype[chn];    /* save for next call to l3psy_anal */
  }
  
  if (blocktype_d[0]==2) 
    *ms_ratio = ms_ratio_s_old;
  else
    *ms_ratio = ms_ratio_l_old;

  ms_ratio_s_old = ms_ratio_s;
  ms_ratio_l_old = ms_ratio_l;

  /* we dont know the block type of this frame yet - assume long */
  *ms_ratio_next = ms_ratio_l;



  /*********************************************************************/
  /* compute side_energy / (side+mid)_energy */
  /* 0 = no energy in side channel */
  /* .5 = half of total energy in side channel */
  /*********************************************************************/
  if (numchn==4)  {
    FLOAT tmp = tot_ener[3]+tot_ener[2];
    *ms_ener_ratio = ms_ener_ratio_old;
    ms_ener_ratio_old=0;
    if (tmp>0) ms_ener_ratio_old=tot_ener[3]/tmp;
  } else
    /* we didn't compute ms_ener_ratios */
    *ms_ener_ratio = 0;
 
}