]> sigrok.org Git - libsigrok.git/blob - src/input/wav.c
input: Fixes and VCD.
[libsigrok.git] / src / input / wav.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include "libsigrok.h"
27 #include "libsigrok-internal.h"
28
29 #define LOG_PREFIX "input/wav"
30
31 /* How many bytes at a time to process and send to the session bus. */
32 #define CHUNK_SIZE 4096
33
34 /* Minimum size of header + 1 8-bit mono PCM sample. */
35 #define MIN_DATA_CHUNK_OFFSET    45
36
37 /* Expect to find the "data" chunk within this offset from the start. */
38 #define MAX_DATA_CHUNK_OFFSET    256
39
40 #define WAVE_FORMAT_PCM          1
41 #define WAVE_FORMAT_IEEE_FLOAT   3
42
43 struct context {
44         int fmt_code;
45         uint64_t samplerate;
46         int samplesize;
47         int num_channels;
48         int unitsize;
49         gboolean found_data;
50 };
51
52 static int parse_wav_header(GString *buf, struct context *inc)
53 {
54         uint64_t samplerate;
55         int fmt_code, samplesize, num_channels, unitsize;
56
57         if (buf->len < MIN_DATA_CHUNK_OFFSET) {
58                 return SR_ERR;
59         }
60
61         fmt_code = GUINT16_FROM_LE(*(uint16_t *)(buf->str + 20));
62         samplerate = GUINT32_FROM_LE(*(uint32_t *)(buf->str + 24));
63         samplesize = GUINT16_FROM_LE(*(uint16_t *)(buf->str + 32));
64         num_channels = GUINT16_FROM_LE(*(uint16_t *)(buf->str + 22));
65         /* TODO div0 */
66         unitsize = samplesize / num_channels;
67
68         if (fmt_code == WAVE_FORMAT_PCM) {
69                 if (samplesize != 1 && samplesize != 2 && samplesize != 4) {
70                         sr_err("only 8, 16 or 32 bits per sample supported.");
71                         return SR_ERR;
72                 }
73         } else if (fmt_code == WAVE_FORMAT_IEEE_FLOAT) {
74                 if (unitsize != 4) {
75                         sr_err("only 32-bit floats supported.");
76                         return SR_ERR;
77                 }
78         } else {
79                 sr_err("Only PCM and floating point samples are supported.");
80                 return SR_ERR;
81         }
82
83         if (inc) {
84                 inc->fmt_code = fmt_code;
85                 inc->samplerate = samplerate;
86                 inc->samplesize = samplesize;
87                 inc->num_channels = num_channels;
88                 inc->unitsize = unitsize;
89                 inc->found_data = FALSE;
90         }
91
92         return SR_OK;
93 }
94
95 static int format_match(GHashTable *metadata)
96 {
97         GString *buf;
98
99         buf = g_hash_table_lookup(metadata, GINT_TO_POINTER(SR_INPUT_META_HEADER));
100         if (strncmp(buf->str, "RIFF", 4))
101                 return FALSE;
102         if (strncmp(buf->str + 8, "WAVE", 4))
103                 return FALSE;
104         if (strncmp(buf->str + 12, "fmt ", 4))
105                 return FALSE;
106         /*
107          * Only gets called when we already know this is a WAV file, so
108          * this parser can log error messages.
109          */
110         if (parse_wav_header(buf, NULL) != SR_OK)
111                 return FALSE;
112
113         return TRUE;
114 }
115
116 static int init(struct sr_input *in, GHashTable *options)
117 {
118         (void)options;
119
120         in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
121
122         return SR_OK;
123 }
124
125 static int find_data_chunk(GString *buf, int initial_offset)
126 {
127         unsigned int offset, i;
128
129         offset = initial_offset;
130         while(offset < MIN(MAX_DATA_CHUNK_OFFSET, buf->len)) {
131                 if (!memcmp(buf->str + offset, "data", 4))
132                         /* Skip into the samples. */
133                         return offset + 8;
134                 for (i = 0; i < 4; i++) {
135                         if (!isalpha(buf->str[offset + i])
136                                         && !isascii(buf->str[offset + i])
137                                         && !isblank(buf->str[offset + i]))
138                                 /* Doesn't look like a chunk ID. */
139                                 return -1;
140                 }
141                 /* Skip past this chunk. */
142                 offset += 8 + GUINT32_FROM_LE(*(uint32_t *)(buf->str + offset + 4));
143         }
144
145         return offset;
146 }
147
148 static int initial_receive(struct sr_input *in)
149 {
150         struct sr_datafeed_packet packet;
151         struct sr_datafeed_meta meta;
152         struct sr_channel *ch;
153         struct sr_config *src;
154         struct context *inc;
155         int i;
156         char channelname[8];
157
158         if (!in->buf)
159                 /* Shouldn't happen. */
160                 return SR_ERR;
161
162         inc = in->priv = g_malloc(sizeof(struct context));
163         if (parse_wav_header(in->buf, inc) != SR_OK)
164                 return SR_ERR;
165
166         for (i = 0; i < inc->num_channels; i++) {
167                 snprintf(channelname, 8, "CH%d", i + 1);
168                 ch = sr_channel_new(i, SR_CHANNEL_ANALOG, TRUE, channelname);
169                 in->sdi->channels = g_slist_append(in->sdi->channels, ch);
170         }
171
172         std_session_send_df_header(in->sdi, LOG_PREFIX);
173
174         packet.type = SR_DF_META;
175         packet.payload = &meta;
176         src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(inc->samplerate));
177         meta.config = g_slist_append(NULL, src);
178         sr_session_send(in->sdi, &packet);
179         sr_config_free(src);
180
181         return SR_OK;
182 }
183
184 static void send_chunk(const struct sr_input *in, int offset, int num_samples)
185 {
186         struct sr_datafeed_packet packet;
187         struct sr_datafeed_analog analog;
188         struct context *inc;
189         float fdata[CHUNK_SIZE];
190         uint64_t sample;
191         int total_samples, samplenum;
192         char *s, *d;
193
194         inc = in->priv;
195
196         s = in->buf->str + offset;
197         d = (char *)fdata;
198         memset(fdata, 0, CHUNK_SIZE);
199         total_samples = num_samples * inc->num_channels;
200         for (samplenum = 0; samplenum < total_samples; samplenum++) {
201                 if (inc->fmt_code == WAVE_FORMAT_PCM) {
202                         sample = 0;
203                         memcpy(&sample, s, inc->unitsize);
204                         switch (inc->samplesize) {
205                         case 1:
206                                 /* 8-bit PCM samples are unsigned. */
207                                 fdata[samplenum] = (uint8_t)sample / 255.0;
208                                 break;
209                         case 2:
210                                 fdata[samplenum] = GINT16_FROM_LE(sample) / 32767.0;
211                                 break;
212                         case 4:
213                                 fdata[samplenum] = GINT32_FROM_LE(sample) / 65535.0;
214                                 break;
215                         }
216                 } else {
217                         /* BINARY32 float */
218 #ifdef WORDS_BIGENDIAN
219                         for (i = 0; i < inc->unitsize; i++)
220                                 d[i] = s[inc->unitsize - i];
221 #else
222                         memcpy(d, s, inc->unitsize);
223 #endif
224                 }
225                 s += inc->unitsize;
226                 d += inc->unitsize;
227         }
228         packet.type = SR_DF_ANALOG;
229         packet.payload = &analog;
230         analog.channels = in->sdi->channels;
231         analog.num_samples = num_samples;
232         analog.mq = 0;
233         analog.mqflags = 0;
234         analog.unit = 0;
235         analog.data = fdata;
236         sr_session_send(in->sdi, &packet);
237 }
238
239 static int receive(const struct sr_input *in, GString *buf)
240 {
241         struct sr_datafeed_packet packet;
242         struct context *inc;
243         int offset, chunk_samples, total_samples, processed, max_chunk_samples, num_samples, i;
244
245         if (buf->len == 0) {
246                 /* End of stream. */
247                 packet.type = SR_DF_END;
248                 sr_session_send(in->sdi, &packet);
249                 return SR_OK;
250         }
251
252         g_string_append_len(in->buf, buf->str, buf->len);
253
254         if (!in->priv) {
255                 if (initial_receive((struct sr_input *)in) != SR_OK)
256                         return SR_ERR;
257                 if (in->buf->len < MIN_DATA_CHUNK_OFFSET) {
258                         /*
259                          * Don't even get started until there's enough room
260                          * for the data segment to start.
261                          */
262                         return SR_OK;
263                 }
264         }
265         inc = in->priv;
266
267         if (!inc->found_data) {
268                 /* Skip past size of 'fmt ' chunk. */
269                 i = 20 + GUINT32_FROM_LE(*(uint32_t *)(in->buf->str + 16));
270                 offset = find_data_chunk(in->buf, i);
271                 if (offset < 0) {
272                         if (in->buf->len > MAX_DATA_CHUNK_OFFSET) {
273                                 sr_err("Couldn't find data chunk.");
274                                 return SR_ERR;
275                         }
276                 }
277                 inc->found_data = TRUE;
278         } else
279                 offset = 0;
280
281         /* Round off up to the last channels * unitsize boundary. */
282         chunk_samples = (in->buf->len - offset) / inc->num_channels / inc->unitsize;
283         max_chunk_samples = CHUNK_SIZE / inc->num_channels / inc->unitsize;
284         processed = 0;
285         total_samples = chunk_samples;
286         while (processed < total_samples) {
287                 if (chunk_samples > max_chunk_samples)
288                         num_samples = max_chunk_samples;
289                 else
290                         num_samples = chunk_samples;
291                 send_chunk(in, offset, num_samples);
292                 offset += num_samples * inc->unitsize;
293                 chunk_samples -= num_samples;
294                 processed += num_samples;
295         }
296
297         if ((unsigned int)offset < in->buf->len) {
298                 /*
299                  * The incoming buffer wasn't processed completely. Stash
300                  * the leftover data for next time.
301                  */
302                 g_string_erase(in->buf, 0, offset);
303         } else
304                 g_string_truncate(in->buf, 0);
305
306         return SR_OK;
307 }
308
309 static int cleanup(struct sr_input *in)
310 {
311         g_free(in->priv);
312         in->priv = NULL;
313
314         return SR_OK;
315 }
316
317 SR_PRIV struct sr_input_module input_wav = {
318         .id = "wav",
319         .name = "WAV",
320         .desc = "WAV file",
321         .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
322         .format_match = format_match,
323         .init = init,
324         .receive = receive,
325         .cleanup = cleanup,
326 };
327