]> sigrok.org Git - libsigrok.git/blob - hardware/alsa/alsa.c
device.c: Fix memory leak in sr_serial_dev_inst_free
[libsigrok.git] / hardware / alsa / alsa.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2011 Daniel Ribeiro <drwyrm@gmail.com>
5  * Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
20  */
21
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <alsa/asoundlib.h>
26 #include "libsigrok.h"
27 #include "libsigrok-internal.h"
28
29 /* Message logging helpers with driver-specific prefix string. */
30 #define DRIVER_LOG_DOMAIN "alsa: "
31 #define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
32 #define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
33 #define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
34 #define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
35 #define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
36 #define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
37
38 #define NUM_PROBES              2
39 #define SAMPLE_WIDTH            16
40 #define DEFAULT_SAMPLERATE      44100
41 // #define AUDIO_DEV            "plughw:0,0"
42 #define AUDIO_DEV               "default"
43
44 static const int hwcaps[] = {
45         SR_HWCAP_SAMPLERATE,
46         SR_HWCAP_LIMIT_SAMPLES,
47         SR_HWCAP_CONTINUOUS,
48         0,
49 };
50
51 static const char *probe_names[] = {
52         "Channel 0",
53         "Channel 1",
54         NULL,
55 };
56
57 SR_PRIV struct sr_dev_driver alsa_driver_info;
58 static struct sr_dev_driver *di = &alsa_driver_info;
59
60 /** Private, per-device-instance driver context. */
61 struct dev_context {
62         uint64_t cur_samplerate;
63         uint64_t limit_samples;
64         uint64_t num_samples;
65         snd_pcm_t *capture_handle;
66         snd_pcm_hw_params_t *hw_params;
67         struct pollfd *ufds;
68         void *cb_data;
69 };
70
71 static int clear_instances(void)
72 {
73         /* TODO */
74
75         return SR_OK;
76 }
77
78 static int hw_init(struct sr_context *sr_ctx)
79 {
80         struct drv_context *drvc;
81
82         if (!(drvc = g_try_malloc0(sizeof(struct drv_context)))) {
83                 sr_err("Driver context malloc failed.");
84                 return SR_ERR_MALLOC;
85         }
86
87         drvc->sr_ctx = sr_ctx;
88         di->priv = drvc;
89
90         return SR_OK;
91 }
92
93 static GSList *hw_scan(GSList *options)
94 {
95         struct drv_context *drvc;
96         struct dev_context *devc;
97         struct sr_dev_inst *sdi;
98         struct sr_probe *probe;
99         GSList *devices;
100         int i;
101
102         (void)options;
103
104         drvc = di->priv;
105         drvc->instances = NULL;
106
107         devices = NULL;
108
109         if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
110                 sr_err("Device context malloc failed.");
111                 return NULL;
112         }
113
114         if (!(sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, "alsa", NULL, NULL))) {
115                 sr_err("Failed to create device instance.");
116                 return NULL;
117         }
118
119         /* Set the samplerate to a default value for now. */
120         devc->cur_samplerate = DEFAULT_SAMPLERATE;
121
122         sdi->priv = devc;
123         sdi->driver = di;
124
125         for (i = 0; probe_names[i]; i++) {
126                 if (!(probe = sr_probe_new(i, SR_PROBE_ANALOG, TRUE,
127                                            probe_names[i]))) {
128                         sr_err("Failed to create probe.");
129                         return NULL;
130                 }
131                 sdi->probes = g_slist_append(sdi->probes, probe);
132         }
133
134         drvc->instances = g_slist_append(drvc->instances, sdi);
135         devices = g_slist_append(devices, sdi);
136
137         return devices;
138 }
139
140 static GSList *hw_dev_list(void)
141 {
142         struct drv_context *drvc;
143
144         drvc = di->priv;
145
146         return drvc->instances;
147 }
148
149 static int hw_dev_open(struct sr_dev_inst *sdi)
150 {
151         struct dev_context *devc;
152         int ret;
153
154         devc = sdi->priv;
155
156         sr_dbg("Opening audio device '%s' for stream capture.", AUDIO_DEV);
157         ret = snd_pcm_open(&devc->capture_handle, AUDIO_DEV,
158                            SND_PCM_STREAM_CAPTURE, 0);
159         if (ret < 0) {
160                 sr_err("Can't open audio device: %s.", snd_strerror(ret));
161                 return SR_ERR;
162         }
163
164         sr_dbg("Allocating hardware parameter structure.");
165         ret = snd_pcm_hw_params_malloc(&devc->hw_params);
166         if (ret < 0) {
167                 sr_err("Can't allocate hardware parameter structure: %s.",
168                        snd_strerror(ret));
169                 return SR_ERR_MALLOC;
170         }
171
172         sr_dbg("Initializing hardware parameter structure.");
173         ret = snd_pcm_hw_params_any(devc->capture_handle, devc->hw_params);
174         if (ret < 0) {
175                 sr_err("Can't initialize hardware parameter structure: %s.",
176                        snd_strerror(ret));
177                 return SR_ERR;
178         }
179
180         return SR_OK;
181 }
182
183 static int hw_dev_close(struct sr_dev_inst *sdi)
184 {
185         int ret;
186         struct dev_context *devc;
187
188         devc = sdi->priv;
189
190         sr_dbg("Closing device.");
191
192         if (devc->hw_params) {
193                 sr_dbg("Freeing hardware parameters.");
194                 snd_pcm_hw_params_free(devc->hw_params);
195         } else {
196                 sr_dbg("No hardware parameters, no need to free.");
197         }
198
199         if (devc->capture_handle) {
200                 sr_dbg("Closing PCM device.");
201                 if ((ret = snd_pcm_close(devc->capture_handle)) < 0) {
202                         sr_err("Failed to close device: %s.",
203                                snd_strerror(ret));
204                 }
205         } else {
206                 sr_dbg("No capture handle, no need to close audio device.");
207         }
208
209         return SR_OK;
210 }
211
212 static int hw_cleanup(void)
213 {
214         clear_instances();
215
216         return SR_OK;
217 }
218
219 static int hw_info_get(int info_id, const void **data,
220                        const struct sr_dev_inst *sdi)
221 {
222         struct dev_context *devc;
223
224         if (info_id != SR_DI_HWCAPS) /* For SR_DI_HWCAPS sdi will be NULL. */
225                 devc = sdi->priv;
226
227         switch (info_id) {
228         case SR_DI_HWCAPS:
229                 *data = hwcaps;
230                 break;
231         case SR_DI_NUM_PROBES:
232                 *data = GINT_TO_POINTER(NUM_PROBES);
233                 break;
234         case SR_DI_PROBE_NAMES:
235                 *data = probe_names;
236                 break;
237         case SR_DI_CUR_SAMPLERATE:
238                 *data = &devc->cur_samplerate;
239                 break;
240         default:
241                 sr_err("Invalid info_id: %d.", info_id);
242                 return SR_ERR_ARG;
243         }
244
245         return SR_OK;
246 }
247
248 static int hw_dev_config_set(const struct sr_dev_inst *sdi, int hwcap,
249                              const void *value)
250 {
251         struct dev_context *devc;
252
253         devc = sdi->priv;
254
255         switch (hwcap) {
256         case SR_HWCAP_SAMPLERATE:
257                 devc->cur_samplerate = *(const uint64_t *)value;
258                 break;
259         case SR_HWCAP_LIMIT_SAMPLES:
260                 devc->limit_samples = *(const uint64_t *)value;
261                 break;
262         default:
263                 sr_err("Unknown capability: %d.", hwcap);
264                 return SR_ERR;
265         }
266
267         return SR_OK;
268 }
269
270 static int receive_data(int fd, int revents, void *cb_data)
271 {
272         struct sr_dev_inst *sdi;
273         struct dev_context *devc;
274         struct sr_datafeed_packet packet;
275         struct sr_datafeed_analog analog;
276         char inbuf[4096];
277         int i, x, count, offset, samples_to_get;
278         uint16_t tmp16;
279
280         (void)fd;
281         (void)revents;
282
283         sdi = cb_data;
284         devc = sdi->priv;
285
286         memset(&analog, 0, sizeof(struct sr_datafeed_analog));
287         memset(inbuf, 0, sizeof(inbuf));
288
289         samples_to_get = MIN(4096 / 4, devc->limit_samples);
290
291         sr_spew("Getting %d samples from audio device.", samples_to_get);
292         count = snd_pcm_readi(devc->capture_handle, inbuf, samples_to_get);
293
294         if (count < 0) {
295                 sr_err("Failed to read samples: %s.", snd_strerror(count));
296                 return FALSE;
297         } else if (count != samples_to_get) {
298                 sr_spew("Only got %d/%d samples.", count, samples_to_get);
299         }
300
301         analog.data = g_try_malloc0(count * sizeof(float) * NUM_PROBES);
302         if (!analog.data) {
303                 sr_err("Failed to malloc sample buffer.");
304                 return FALSE;
305         }
306
307         offset = 0;
308
309         for (i = 0; i < count; i++) {
310                 for (x = 0; x < NUM_PROBES; x++) {
311                         tmp16 = *(uint16_t *)(inbuf + (i * 4) + (x * 2));
312                         analog.data[offset++] = (float)tmp16;
313                 }
314         }
315
316         /* Send a sample packet with the analog values. */
317         analog.num_samples = count;
318         analog.mq = SR_MQ_VOLTAGE; /* FIXME */
319         analog.unit = SR_UNIT_VOLT; /* FIXME */
320         packet.type = SR_DF_ANALOG;
321         packet.payload = &analog;
322         sr_session_send(devc->cb_data, &packet);
323
324         g_free(analog.data);
325
326         devc->num_samples += count;
327
328         /* Stop acquisition if we acquired enough samples. */
329         if (devc->limit_samples > 0) {
330                 if (devc->num_samples >= devc->limit_samples) {
331                         sr_info("Requested number of samples reached.");
332                         sdi->driver->dev_acquisition_stop(sdi, cb_data);
333                 }
334         }
335
336         return TRUE;
337 }
338
339 static int hw_dev_acquisition_start(const struct sr_dev_inst *sdi,
340                                     void *cb_data)
341 {
342         struct sr_datafeed_packet packet;
343         struct sr_datafeed_header header;
344         struct sr_datafeed_meta_analog meta;
345         struct dev_context *devc;
346         int count, ret;
347
348         devc = sdi->priv;
349         devc->cb_data = cb_data;
350
351         sr_dbg("Setting audio access type to RW/interleaved.");
352         ret = snd_pcm_hw_params_set_access(devc->capture_handle,
353                         devc->hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
354         if (ret < 0) {
355                 sr_err("Can't set audio access type: %s.", snd_strerror(ret));
356                 return SR_ERR;
357         }
358
359         /* FIXME: Hardcoded for 16bits. */
360         sr_dbg("Setting audio sample format to signed 16bit (little endian).");
361         ret = snd_pcm_hw_params_set_format(devc->capture_handle,
362                         devc->hw_params, SND_PCM_FORMAT_S16_LE);
363         if (ret < 0) {
364                 sr_err("Can't set audio sample format: %s.", snd_strerror(ret));
365                 return SR_ERR;
366         }
367
368         sr_dbg("Setting audio samplerate to %" PRIu64 "Hz.",
369                devc->cur_samplerate);
370         ret = snd_pcm_hw_params_set_rate_near(devc->capture_handle,
371                 devc->hw_params, (unsigned int *)&devc->cur_samplerate, 0);
372         if (ret < 0) {
373                 sr_err("Can't set audio sample rate: %s.", snd_strerror(ret));
374                 return SR_ERR;
375         }
376
377         sr_dbg("Setting audio channel count to %d.", NUM_PROBES);
378         ret = snd_pcm_hw_params_set_channels(devc->capture_handle,
379                                              devc->hw_params, NUM_PROBES);
380         if (ret < 0) {
381                 sr_err("Can't set channel count: %s.", snd_strerror(ret));
382                 return SR_ERR;
383         }
384
385         sr_dbg("Setting audio parameters.");
386         ret = snd_pcm_hw_params(devc->capture_handle, devc->hw_params);
387         if (ret < 0) {
388                 sr_err("Can't set parameters: %s.", snd_strerror(ret));
389                 return SR_ERR;
390         }
391
392         sr_dbg("Preparing audio interface for use.");
393         ret = snd_pcm_prepare(devc->capture_handle);
394         if (ret < 0) {
395                 sr_err("Can't prepare audio interface for use: %s.",
396                        snd_strerror(ret));
397                 return SR_ERR;
398         }
399
400         count = snd_pcm_poll_descriptors_count(devc->capture_handle);
401         if (count < 1) {
402                 sr_err("Unable to obtain poll descriptors count.");
403                 return SR_ERR;
404         }
405         sr_spew("Obtained poll descriptor count: %d.", count);
406
407         if (!(devc->ufds = g_try_malloc(count * sizeof(struct pollfd)))) {
408                 sr_err("Failed to malloc ufds.");
409                 return SR_ERR_MALLOC;
410         }
411
412         sr_err("Getting %d poll descriptors.", count);
413         ret = snd_pcm_poll_descriptors(devc->capture_handle, devc->ufds, count);
414         if (ret < 0) {
415                 sr_err("Unable to obtain poll descriptors: %s.",
416                        snd_strerror(ret));
417                 g_free(devc->ufds);
418                 return SR_ERR;
419         }
420
421         /* Send header packet to the session bus. */
422         sr_dbg("Sending SR_DF_HEADER packet.");
423         packet.type = SR_DF_HEADER;
424         packet.payload = (uint8_t *)&header;
425         header.feed_version = 1;
426         gettimeofday(&header.starttime, NULL);
427         sr_session_send(devc->cb_data, &packet);
428
429         /* Send metadata about the SR_DF_ANALOG packets to come. */
430         sr_dbg("Sending SR_DF_META_ANALOG packet.");
431         packet.type = SR_DF_META_ANALOG;
432         packet.payload = &meta;
433         meta.num_probes = NUM_PROBES;
434         sr_session_send(devc->cb_data, &packet);
435
436         /* Poll every 10ms, or whenever some data comes in. */
437         sr_source_add(devc->ufds[0].fd, devc->ufds[0].events, 10,
438                       receive_data, (void *)sdi);
439
440         // g_free(devc->ufds); /* FIXME */
441
442         return SR_OK;
443 }
444
445 static int hw_dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
446 {
447         struct sr_datafeed_packet packet;
448         struct dev_context *devc;
449
450         devc = sdi->priv;
451         devc->cb_data = cb_data;
452
453         sr_source_remove(devc->ufds[0].fd);
454
455         /* Send end packet to the session bus. */
456         sr_dbg("Sending SR_DF_END packet.");
457         packet.type = SR_DF_END;
458         sr_session_send(cb_data, &packet);
459
460         return SR_OK;
461 }
462
463 SR_PRIV struct sr_dev_driver alsa_driver_info = {
464         .name = "alsa",
465         .longname = "ALSA driver",
466         .api_version = 1,
467         .init = hw_init,
468         .cleanup = hw_cleanup,
469         .scan = hw_scan,
470         .dev_list = hw_dev_list,
471         .dev_clear = clear_instances,
472         .dev_open = hw_dev_open,
473         .dev_close = hw_dev_close,
474         .info_get = hw_info_get,
475         .dev_config_set = hw_dev_config_set,
476         .dev_acquisition_start = hw_dev_acquisition_start,
477         .dev_acquisition_stop = hw_dev_acquisition_stop,
478         .priv = NULL,
479 };