8magsvn – Rev 36

Subversion Repositories:
Rev:
///////////////////////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <errno.h>
#include <getopt.h>
#include <alsa/asoundlib.h>
#include <sys/time.h>
#include <math.h>
#include <fftw3.h>
#include <signal.h>

static char *device = "plughw:0,0";                     /* playback device */
static snd_pcm_format_t format = SND_PCM_FORMAT_S16;    /* sample format */
static unsigned int rate = 98000;                       /* stream rate */
static int resample = 1;                                /* enable alsa-lib resampling */
static int period_event = 0;                            /* produce poll event after each period */

static snd_pcm_uframes_t buffer_size = 20004;   //samples per frame
static snd_pcm_uframes_t period_size = 4000;
static snd_output_t *output = NULL;
snd_pcm_t *playback_handle, *capture_handle;
 
FILE *out;

double df;      //frequency resolution 
unsigned int frequency_bins; // number of output frequency bins 

double *inl, *inr;
fftw_complex *outl, *outr;
fftw_plan fft_plan_left, fft_plan_right;

double *spect_avg_left, *spect_avg_right;
unsigned int period;

#define PERIODS 100     // number of periods to average 

void leave(int sig);

static int set_hwparams(snd_pcm_t *handle, snd_pcm_hw_params_t *params, unsigned int channels)
{
        unsigned int rrate;
        int err, dir;

        /* choose all parameters */
        err = snd_pcm_hw_params_any(handle, params);
        if (err < 0) {
                printf("Broken configuration for capture: no configurations available: %s\n", snd_strerror(err));
                return err;
        }
        /* set hardware resampling */
        err = snd_pcm_hw_params_set_rate_resample(handle, params, resample);
        if (err < 0) {
                printf("Resampling setup failed for capture: %s\n", snd_strerror(err));
                return err;
        }
        /* set the interleaved read/write format */
        err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
        if (err < 0) {
                printf("Access type not available for capture: %s\n", snd_strerror(err));
                return err;
        }
        /* set the sample format */
        err = snd_pcm_hw_params_set_format(handle, params, format);
        if (err < 0) {
                printf("Sample format not available for capture: %s\n", snd_strerror(err));
                return err;
        }
        /* set the count of channels */
        err = snd_pcm_hw_params_set_channels(handle, params, channels);
        if (err < 0) {
                printf("Channels count (%i) not available for capture: %s\n", channels, snd_strerror(err));
                return err;
        }
        /* set the stream rate */
        rrate = rate;
        err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
        if (err < 0) {
                printf("Rate %iHz not available for capture: %s\n", rate, snd_strerror(err));
                return err;
        }
        if (rrate != rate) {
                printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
                return -EINVAL;
        }
        else printf("Sampling rate set to %i Hz\n", rate, err);
 
        /* set the buffer size */
        err = snd_pcm_hw_params_set_buffer_size_near(handle, params, &buffer_size);
        if (err < 0) {
                printf("Unable to set maximal buffer size for capture: %s\n", snd_strerror(err));
                return err;
        }
        else printf("Size of capture buffer set to %i\n", (int) buffer_size);

        snd_pcm_hw_params_set_period_size_near(handle, params, &period_size, &dir);
        if (err < 0) {
                printf("Unable to set maximal period size %i for capture: %s\n", (int) period_size, snd_strerror(err));
                return err;
        }
        else printf("Size of capture period (FFT width) set to %i\n", (int) period_size);

        /* write the parameters to device */
        err = snd_pcm_hw_params(handle, params);
        if (err < 0) {
                printf("Unable to set hw params for capture: %s\n", snd_strerror(err));
                return err;
        }
        return 0;
}

static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams)
{
        int err;

        /* get the current swparams */
        err = snd_pcm_sw_params_current(handle, swparams);
        if (err < 0) {
                printf("Unable to determine current swparams for playback: %s\n", snd_strerror(err));
                return err;
        }
        /* start the transfer when the buffer is almost full: */
        /* (buffer_size / avail_min) * avail_min */
        err = snd_pcm_sw_params_set_start_threshold(handle, swparams, (buffer_size / period_size) * period_size);
        if (err < 0) {
                printf("Unable to set start threshold mode for playback: %s\n", snd_strerror(err));
                return err;
        }
        /* allow the transfer when at least period_size samples can be processed */
        /* or disable this mechanism when period event is enabled (aka interrupt like style processing) */
        err = snd_pcm_sw_params_set_avail_min(handle, swparams, period_event ? buffer_size : period_size);
        if (err < 0) {
                printf("Unable to set avail min for playback: %s\n", snd_strerror(err));
                return err;
        }
        /* enable period events when requested */
        if (period_event) {
                err = snd_pcm_sw_params_set_period_event(handle, swparams, 1);
                if (err < 0) {
                        printf("Unable to set period event: %s\n", snd_strerror(err));
                        return err;
                }
        }
        /* write the parameters to the playback device */
        err = snd_pcm_sw_params(handle, swparams);
        if (err < 0) {
                printf("Unable to set sw params for playback: %s\n", snd_strerror(err));
                return err;
        }
        return 0;
}

struct async_private_data {
        signed short *samples;
        snd_pcm_channel_area_t *areas;
        unsigned int period;
};

/////////// CALL BACK STUFF ///////////////////

static void async_capture_callback(snd_async_handler_t *ahandler)
{
        snd_pcm_t *handle = snd_async_handler_get_pcm(ahandler);
        int err;
        unsigned int i, n;
        short signal[100000];

        /*signal = calloc( (unsigned int) period_size, sizeof(short) );
        if (signal = NULL) printf("memory allocation failed");*/

        while (snd_pcm_avail_update(handle) >= period_size) {  // read until data is ready in buffer

                err = snd_pcm_readi(handle, signal, period_size);
                if (err < 0) {
                        printf("Read error: %s\n", snd_strerror(err));
                        exit(EXIT_FAILURE);
                }
                if (err != period_size) {
                        printf("Read error: red %i expected %li\n", err, period_size);
                        exit(EXIT_FAILURE);
                }

        n=0;
        i=0;
        do {
          inl[n]= signal[i]/32768.0;
          inr[n]= signal[i+1]/32768.0;
          n++;
          i+=2;
        } while (n < period_size);

        fftw_execute(fft_plan_left);
        fftw_execute(fft_plan_right);

        for(i=0; i < frequency_bins; i++) spect_avg_left[i] += sqrt( (outl[i][0] * outl[i][0]) + (outl[i][1] * outl[i][1]) ); //acumulate average spectrum
        for(i=0; i < frequency_bins; i++) spect_avg_right[i] += sqrt( (outr[i][0] * outr[i][0]) + (outr[i][1] * outr[i][1]) ); //acumulate average spectrum
        period++;
        }

        if (period > PERIODS)
        {
          for(i=0; i < frequency_bins; i++) spect_avg_left[i] = spect_avg_left[i]/PERIODS;  // finally average spectrum data
          for(i=0; i < frequency_bins; i++) spect_avg_right[i] = spect_avg_right[i]/PERIODS;

          out=fopen("/tmp/sidspec","w");

          for(i=0; i < frequency_bins; i++)             //write spectrum to file
          {
             fprintf(out,"%.5e %.5e %.5e\n",(i+0.5)*df, spect_avg_left[i], spect_avg_right[i]);
             spect_avg_left[i]=0;
             spect_avg_right[i]=0;
          }
          fclose(out);
          period=0;
        }
//      free(signal);
}

int main(int argc, char *argv[])
{
        int err;
        snd_pcm_hw_params_t *hwparams;
        snd_pcm_sw_params_t *swparams;
        signed short *frame;  // pointer to array of samples
        unsigned int chn;
        snd_pcm_channel_area_t *areas;

        struct async_private_data data;
        snd_async_handler_t *chandler;

        snd_pcm_hw_params_alloca(&hwparams);
        snd_pcm_sw_params_alloca(&swparams);

        printf("SID monitor 2.0 starting work.. \n");
        (void) signal(SIGINT,leave);

//open and set capture device
        if ((err = snd_pcm_open(&capture_handle, device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
                printf("Playback open error: %s\n", snd_strerror(err));
                return 0;
        }
        else printf("Using audio device:  %s\n", device);
        
        if ((err = set_hwparams(capture_handle, hwparams, 2)) < 0) {
                printf("Setting of hwparams failed: %s\n", snd_strerror(err));
                exit(EXIT_FAILURE);
        }
        if ((err = set_swparams(capture_handle, swparams)) < 0) {
                printf("Setting of swparams failed: %s\n", snd_strerror(err));
                exit(EXIT_FAILURE);
        }

        frequency_bins = period_size/2 + 1;

        spect_avg_left = calloc(frequency_bins, sizeof (double));               //allocate space for frrequency spectrum
        spect_avg_right = calloc(frequency_bins, sizeof (double));


// register capture callback 
        err = snd_async_add_pcm_handler(&chandler, capture_handle, async_capture_callback, &data); // fill by dummy &data
        if (err < 0) {
                printf("Unable to register async handler\n");
                exit(EXIT_FAILURE);
        }

// setup fft 

        df = (double) rate/ (double) period_size;

        inl = fftw_malloc(sizeof(double) * period_size); // period_size);
        outl = fftw_malloc(sizeof(fftw_complex) * frequency_bins);

        inr = fftw_malloc(sizeof(double) * period_size); // period_size);
        outr = fftw_malloc(sizeof(fftw_complex) * frequency_bins);


        fft_plan_left = fftw_plan_dft_r2c_1d(period_size, inl, outl, FFTW_ESTIMATE);
        fft_plan_right = fftw_plan_dft_r2c_1d(period_size, inr, outr, FFTW_ESTIMATE);
        period=0;

//start capture
        if ((err = snd_pcm_prepare (capture_handle)) < 0) {
                fprintf (stderr, "cannot prepare audio interface for use (%s)\n",
                         snd_strerror (err));
                exit (1);
        }

        err = snd_pcm_start(capture_handle);
        if (err < 0) {
                        printf("Start error: %s\n", snd_strerror(err));
                        exit(EXIT_FAILURE);
        }
        
// wait for interrupt
        printf("processing audio input.. \n");

        while(1) usleep(1000);

        snd_pcm_close(capture_handle); 
        return 0;
}

void leave(int sig) 
{
  printf("\nTerminating.. \n");
  snd_pcm_close(capture_handle);
// fclose(out);
  free(spect_avg_left); 
  free(spect_avg_right); 
  free(inl);
  free(inr);
  free(outl);
  free(outr);
  exit(sig);
}