git stults online alsa-signals / master sinusoid.c
master

Tree @master (Download .tar.gz)

sinusoid.c @masterraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <errno.h>
#include <getopt.h>
#include <sys/time.h>
#include <math.h>
#include <alsa/asoundlib.h>
#include "transfer.h"

typedef struct params_t
{
  unsigned int      rate;        ///< stream rate
  unsigned int      channels;    ///< number of channels
  unsigned int      buffer_time; ///< ring buffer length in usecs
  unsigned int      period_time; ///< perdiod time in usecs
  unsigned int      period_event;///< produce poll event after each period?
  unsigned int      resample;    ///< enable alsa-lib resampling
  snd_pcm_format_t  format;      ///< sample format
  snd_pcm_sframes_t buffer_size; ///< size of buffer
  snd_pcm_sframes_t period_size; ///< time between buffer pull(?)
} params_t;

typedef struct sinusoid_t
{
  double freq;
  double phase;
  double max_phase;
  double step;
} sinusoid_t;

/**
sets params struct fields
*/
int params_init (params_t *params, unsigned int rate, 
		 unsigned int channels, unsigned int buffer_time,
		 unsigned int period_time, unsigned int period_event,
		 unsigned int resample, snd_pcm_format_t format, 
		 snd_pcm_sframes_t buffer_size, snd_pcm_sframes_t period_size)
{
  snd_pcm_format_t curr_format;

  if (params == NULL)
    return 1;

  rate = rate < 4000 ? 4000 : rate;
  rate = rate > 196000 ? 196000 : rate;
  params->rate = rate;

  channels = channels > 1024 ? 1024 : channels;
  params->channels = channels;

  buffer_time = buffer_time < 1000 ? 1000 : buffer_time;
  buffer_time = buffer_time > 1000000 ? 1000000 : buffer_time;
  params->buffer_time = buffer_time;

  period_time = period_time < 1000 ? 1000 : period_time;
  period_time = period_time > 1000000 ? 1000000 : period_time;
  params->period_time = period_time;

  params->resample = resample ? 1 : 0;

  /* make sure requested format is a supported format */
  for (curr_format = 0; curr_format < SND_PCM_FORMAT_LAST; ++curr_format)
    if (curr_format == format)
      break;
  if (curr_format == SND_PCM_FORMAT_LAST)
    curr_format = SND_PCM_FORMAT_S16; /* TODO set from default */
  if (!snd_pcm_format_linear(curr_format) &&
      !(curr_format == SND_PCM_FORMAT_FLOAT_LE ||
	curr_format == SND_PCM_FORMAT_FLOAT_BE))
    {
      return 1;
    }
  params->format = curr_format;

  params->period_event = period_event ? 1 : 0;
  params->buffer_size  = buffer_size;
  params->period_size  = period_size;

  return 0;
}

static void generate_sine(const snd_pcm_channel_area_t *areas,
			  snd_pcm_uframes_t offset,
			  int count, double *_phase)
{
  static double max_phase = 2. * M_PI;
  double phase = *_phase;
  double step = max_phase*freq/(double)rate;
  unsigned char *samples[channels];
  int steps[channels];
  unsigned int chn;
  int format_bits = snd_pcm_format_width(format);
  unsigned int maxval = (1 << (format_bits - 1)) - 1;
  int bps = format_bits / 8; /* bytes per sample */
  int phys_bps = snd_pcm_format_physical_width(format) / 8;
  int big_endian = snd_pcm_format_big_endian(format) == 1;
  int to_unsigned = snd_pcm_format_unsigned(format) == 1;
  int is_float = (format == SND_PCM_FORMAT_FLOAT_LE ||
		  format == SND_PCM_FORMAT_FLOAT_BE);
  /* verify and prepare the contents of areas */
  for (chn = 0; chn < channels; chn++) {
    if ((areas[chn].first % 8) != 0) {
      printf("areas[%i].first == %i, aborting...\n", chn, areas[chn].first);
      exit(EXIT_FAILURE);
    }
    samples[chn] = /*(signed short *)*/(((unsigned char *)areas[chn].addr) + (areas[chn].first / 8));
    if ((areas[chn].step % 16) != 0) {
      printf("areas[%i].step == %i, aborting...\n", chn, areas[chn].step);
      exit(EXIT_FAILURE);
    }
    steps[chn] = areas[chn].step / 8;
    samples[chn] += offset * steps[chn];
  }
  /* fill the channel areas */
  while (count-- > 0) {
    union {
      float f;
      int i;
    } fval;
    int res, i;
    if (is_float) {
      fval.f = sin(phase) * maxval;
      res = fval.i;
    } else
      res = sin(phase) * maxval;
    if (to_unsigned)
      res ^= 1U << (format_bits - 1);
    for (chn = 0; chn < channels; chn++) {
      /* Generate data in native endian format */
      if (big_endian) {
	for (i = 0; i < bps; i++)
	  *(samples[chn] + phys_bps - 1 - i) = (res >> i * 8) & 0xff;
      } else {
	for (i = 0; i < bps; i++)
	  *(samples[chn] + i) = (res >> i * 8) & 0xff;
      }
      samples[chn] += steps[chn];
    }
    phase += step;
    if (phase >= max_phase)
      phase -= max_phase;
  }
  *_phase = phase;
}

static int set_hwparams(snd_pcm_t *handle,
			snd_pcm_hw_params_t *params,
			snd_pcm_access_t access,
			params_t *extra)
{
  int err, dir;
  unsigned int rrate;
  snd_pcm_uframes_t size;

  /* choose all parameters */
  err = snd_pcm_hw_params_any(handle, params);
  if (err < 0) {
    printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
    return err;
  }
  /* set hardware resampling */
  err = snd_pcm_hw_params_set_rate_resample(handle, params, extra->resample);
  if (err < 0) {
    printf("Resampling setup failed for playback: %s\n", snd_strerror(err));
    return err;
  }
  /* set the interleaved read/write format */
  err = snd_pcm_hw_params_set_access(handle, params, access);
  if (err < 0) {
    printf("Access type not available for playback: %s\n", snd_strerror(err));
    return err;
  }
  /* set the sample format */
  err = snd_pcm_hw_params_set_format(handle, params, extra->format);
  if (err < 0) {
    printf("Sample format not available for playback: %s\n", snd_strerror(err));
    return err;
  }
  /* set the count of channels */
  err = snd_pcm_hw_params_set_channels(handle, params, extra->channels);
  if (err < 0) {
    printf("Channels count (%i) not available for playbacks: %s\n", extra->channels, snd_strerror(err));
    return err;
  }
  /* set the stream rate */
  rrate = extra->rate;
  err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
  if (err < 0) {
    printf("Rate %iHz not available for playback: %s\n", extra->rate, snd_strerror(err));
    return err;
  }
  if (rrate != extra->rate) {
    printf("Rate doesn't match (requested %iHz, get %iHz)\n", extra->rate, err);
    return -EINVAL;
  }
  /* set the buffer time */
  err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &extra->buffer_time, &dir);
  if (err < 0) {
    printf("Unable to set buffer time %i for playback: %s\n", extra->buffer_time, snd_strerror(err));
    return err;
  }
  err = snd_pcm_hw_params_get_buffer_size(params, &size);
  if (err < 0) {
    printf("Unable to get buffer size for playback: %s\n", snd_strerror(err));
    return err;
  }
  extra->buffer_size = size;
  /* set the period time */
  err = snd_pcm_hw_params_set_period_time_near(handle, params, &extra->period_time, &dir);
  if (err < 0) {
    printf("Unable to set period time %i for playback: %s\n", extra->period_time, snd_strerror(err));
    return err;
  }
  err = snd_pcm_hw_params_get_period_size(params, &size, &dir);
  if (err < 0) {
    printf("Unable to get period size for playback: %s\n", snd_strerror(err));
    return err;
  }
  extra->period_size = size;
  /* write the parameters to device */
  err = snd_pcm_hw_params(handle, params);
  if (err < 0) {
    printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
    return err;
  }
  return 0;
}

static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams,
			params_t *extra)
{
  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, (extra->buffer_size / extra->period_size) * extra->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, extra->period_event ? extra->buffer_size : extra->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 (extra->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;
}

/* Underrun and suspend recovery */
static int xrun_recovery(snd_pcm_t *handle, int err)
{
  if (err == -EPIPE) { /* under-run */
    err = snd_pcm_prepare(handle);
    if (err < 0)
      printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
    return 0;
  } else if (err == -ESTRPIPE) {
    while ((err = snd_pcm_resume(handle)) == -EAGAIN)
      sleep(1); /* wait until the suspend flag is released */
    if (err < 0) {
      err = snd_pcm_prepare(handle);
      if (err < 0)
	printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
    }
    return 0;
  }
  return err;
}


/************************ MAIN ***************************/

int main(int argc, char *argv[])
{
  char                   *device = "default"; /* playback device */
		         
  snd_pcm_format_t        format = SND_PCM_FORMAT_S16; /* sample format */
  unsigned int            rate = 44100; /* stream rate */
  unsigned int            channels = 1; /* count of channels */
  unsigned int            buffer_time = 500000; /* ring buffer len in usec */
  unsigned int            period_time = 100000; /* period time in usec */
  double                  freq = 440; /* sinusoidal wave frequency in Hz */
  int                     verbose = 0; /* verbose flag */
  int                     resample = 1; /* enable alsa-lib resampling */
  int                     period_event = 0; /* poll after each period */
  snd_pcm_sframes_t       buffer_size;
  snd_pcm_sframes_t       period_size;
  params_t                extra;

  snd_pcm_t              *handle;
  snd_pcm_hw_params_t    *hwparams;
  snd_pcm_sw_params_t    *swparams;
  transfer_method_t      *tm;
  snd_pcm_channel_area_t *areas;

  snd_output_t           *output = NULL;
  const char             *method = "write";
  signed short           *samples;
  unsigned int            chn;
  int                     err;

  /* bind output to a (standard) file pointer -- this is for snd info
     dump commands */
  err = snd_output_stdio_attach(&output, stdout, 0);
  if (err < 0) {
    printf("Output failed: %s\n", snd_strerror(err));
    return 1;
  }

  /* create transfer method */
  if ((tm = transfer_method_create (method)) == NULL)
    {
      printf ("Transfer method creation failed\n");
      return 1;
    }

  printf("Playback device is %s\n", device);
  printf("Stream parameters are %iHz, %s, %i channels\n", rate, snd_pcm_format_name(format), channels);
  printf("Sine wave rate is %.4fHz\n", freq);
  printf("Using transfer method: %s\n", tm->name);

  /* allocate hardware and software param structures */
  snd_pcm_hw_params_malloc (&hwparams);
  snd_pcm_sw_params_malloc (&swparams);

  /* populate (extra) params structure */
  params_init (&extra, rate, channels, buffer_time, period_time, 
	       period_event, resample, format, buffer_size, period_size);


  /* open pcm */
  if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
    printf("Playback open error: %s\n", snd_strerror(err));
    return 1;
  }

  /* set hardware params */
  if ((err = set_hwparams(handle, hwparams, tm->access, &extra)) < 0) {
    printf("Setting of hwparams failed: %s\n", snd_strerror(err));
    exit(EXIT_FAILURE);
  }

  /* set software params */
  if ((err = set_swparams(handle, swparams, &extra)) < 0) {
    printf("Setting of swparams failed: %s\n", snd_strerror(err));
    exit(EXIT_FAILURE);
  }
  
  /* allocate samples buffer */
  samples = malloc((extra.period_size * extra.channels * snd_pcm_format_physical_width(extra.format)) / 8);
  if (samples == NULL) {
    printf("Not enough memory\n");
    exit(EXIT_FAILURE);
  }

  /* allocate memory areas */
  areas = calloc(channels, sizeof(snd_pcm_channel_area_t));
  if (areas == NULL) {
    printf("Not enough memory\n");
    exit(EXIT_FAILURE);
  }
  for (chn = 0; chn < extra.channels; chn++) {
    areas[chn].addr = samples;
    areas[chn].first = chn * snd_pcm_format_physical_width(extra.format);
    areas[chn].step = extra.channels * snd_pcm_format_physical_width(extra.format);
  }
  /* do data transfer to the card */
  err = tm->transfer(handle, samples, areas);
  if (err < 0)
    printf("Transfer failed: %s\n", snd_strerror(err));

  snd_pcm_hw_params_free (hwparams);
  snd_pcm_sw_params_free (swparams);

  free(areas);
  free(samples);

  snd_pcm_close(handle);

  transfer_method_destroy (tm);

  return 0;
}