]> sigrok.org Git - libsigrok.git/blob - src/input/wav.c
4f36e8c45126aac8791a55ddef31563bab0db2cc
[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 <stdint.h>
27 #include "libsigrok.h"
28 #include "libsigrok-internal.h"
29
30 #define LOG_PREFIX "input/wav"
31
32 /* How many bytes at a time to process and send to the session bus. */
33 #define CHUNK_SIZE 4096
34
35 /* Minimum size of header + 1 8-bit mono PCM sample. */
36 #define MIN_DATA_CHUNK_OFFSET    45
37
38 /* Expect to find the "data" chunk within this offset from the start. */
39 #define MAX_DATA_CHUNK_OFFSET    256
40
41 #define WAVE_FORMAT_PCM_         0x0001
42 #define WAVE_FORMAT_IEEE_FLOAT_  0x0003
43 #define WAVE_FORMAT_EXTENSIBLE_  0xfffe
44
45 struct context {
46         gboolean started;
47         int fmt_code;
48         uint64_t samplerate;
49         int samplesize;
50         int num_channels;
51         int unitsize;
52         gboolean found_data;
53 };
54
55 static int parse_wav_header(GString *buf, struct context *inc)
56 {
57         uint64_t samplerate;
58         unsigned int fmt_code, samplesize, num_channels, unitsize;
59
60         if (buf->len < MIN_DATA_CHUNK_OFFSET)
61                 return SR_ERR_NA;
62
63         fmt_code = RL16(buf->str + 20);
64         samplerate = RL32(buf->str + 24);
65
66         samplesize = RL16(buf->str + 32);
67         num_channels = RL16(buf->str + 22);
68         if (num_channels == 0)
69                 return SR_ERR;
70         unitsize = samplesize / num_channels;
71         if (unitsize != 1 && unitsize != 2 && unitsize != 4) {
72                 sr_err("Only 8, 16 or 32 bits per sample supported.");
73                 return SR_ERR_DATA;
74         }
75
76         if (fmt_code == WAVE_FORMAT_PCM_) {
77         } else if (fmt_code == WAVE_FORMAT_IEEE_FLOAT_) {
78                 if (unitsize != 4) {
79                         sr_err("only 32-bit floats supported.");
80                         return SR_ERR_DATA;
81                 }
82         } else if (fmt_code == WAVE_FORMAT_EXTENSIBLE_) {
83                 if (buf->len < 70)
84                         /* Not enough for extensible header and next chunk. */
85                         return SR_ERR_NA;
86
87                 if (RL16(buf->str + 16) != 40) {
88                         sr_err("WAV extensible format chunk must be 40 bytes.");
89                         return SR_ERR;
90                 }
91                 if (RL16(buf->str + 36) != 22) {
92                         sr_err("WAV extension must be 22 bytes.");
93                         return SR_ERR;
94                 }
95                 if (RL16(buf->str + 34) != RL16(buf->str + 38)) {
96                         sr_err("Reduced valid bits per sample not supported.");
97                         return SR_ERR_DATA;
98                 }
99                 /* Real format code is the first two bytes of the GUID. */
100                 fmt_code = RL16(buf->str + 44);
101                 if (fmt_code != WAVE_FORMAT_PCM_ && fmt_code != WAVE_FORMAT_IEEE_FLOAT_) {
102                         sr_err("Only PCM and floating point samples are supported.");
103                         return SR_ERR_DATA;
104                 }
105                 if (fmt_code == WAVE_FORMAT_IEEE_FLOAT_ && unitsize != 4) {
106                         sr_err("only 32-bit floats supported.");
107                         return SR_ERR_DATA;
108                 }
109         } else {
110                 sr_err("Only PCM and floating point samples are supported.");
111                 return SR_ERR_DATA;
112         }
113
114         if (inc) {
115                 inc->fmt_code = fmt_code;
116                 inc->samplerate = samplerate;
117                 inc->samplesize = samplesize;
118                 inc->num_channels = num_channels;
119                 inc->unitsize = unitsize;
120                 inc->found_data = FALSE;
121         }
122
123         return SR_OK;
124 }
125
126 static int format_match(GHashTable *metadata)
127 {
128         GString *buf;
129         int ret;
130
131         buf = g_hash_table_lookup(metadata, GINT_TO_POINTER(SR_INPUT_META_HEADER));
132         if (strncmp(buf->str, "RIFF", 4))
133                 return SR_ERR;
134         if (strncmp(buf->str + 8, "WAVE", 4))
135                 return SR_ERR;
136         if (strncmp(buf->str + 12, "fmt ", 4))
137                 return SR_ERR;
138         /*
139          * Only gets called when we already know this is a WAV file, so
140          * this parser can log error messages.
141          */
142         if ((ret = parse_wav_header(buf, NULL)) != SR_OK)
143                 return ret;
144
145         return SR_OK;
146 }
147
148 static int init(struct sr_input *in, GHashTable *options)
149 {
150         (void)options;
151
152         in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
153         in->priv = g_malloc0(sizeof(struct context));
154
155         return SR_OK;
156 }
157
158 static int find_data_chunk(GString *buf, int initial_offset)
159 {
160         unsigned int offset, i;
161
162         offset = initial_offset;
163         while (offset < MIN(MAX_DATA_CHUNK_OFFSET, buf->len)) {
164                 if (!memcmp(buf->str + offset, "data", 4))
165                         /* Skip into the samples. */
166                         return offset + 8;
167                 for (i = 0; i < 4; i++) {
168                         if (!isalnum(buf->str[offset + i])
169                                         && !isblank(buf->str[offset + i]))
170                                 /* Doesn't look like a chunk ID. */
171                                 return -1;
172                 }
173                 /* Skip past this chunk. */
174                 offset += 8 + RL32(buf->str + offset + 4);
175         }
176
177         return offset;
178 }
179
180 static void send_chunk(const struct sr_input *in, int offset, int num_samples)
181 {
182         struct sr_datafeed_packet packet;
183         struct sr_datafeed_analog analog;
184         struct context *inc;
185         float fdata[CHUNK_SIZE];
186         uint64_t sample;
187         int total_samples, samplenum;
188         char *s, *d;
189
190         inc = in->priv;
191
192         s = in->buf->str + offset;
193         d = (char *)fdata;
194         memset(fdata, 0, CHUNK_SIZE);
195         total_samples = num_samples * inc->num_channels;
196         for (samplenum = 0; samplenum < total_samples; samplenum++) {
197                 if (inc->fmt_code == WAVE_FORMAT_PCM_) {
198                         sample = 0;
199                         memcpy(&sample, s, inc->unitsize);
200                         switch (inc->samplesize) {
201                         case 1:
202                                 /* 8-bit PCM samples are unsigned. */
203                                 fdata[samplenum] = (uint8_t)sample / (float)255;
204                                 break;
205                         case 2:
206                                 fdata[samplenum] = RL16S(&sample) / (float)INT16_MAX;
207                                 break;
208                         case 4:
209                                 fdata[samplenum] = RL32S(&sample) / (float)INT32_MAX;
210                                 break;
211                         }
212                 } else {
213                         /* BINARY32 float */
214 #ifdef WORDS_BIGENDIAN
215                         int i;
216                         for (i = 0; i < inc->unitsize; i++)
217                                 d[i] = s[inc->unitsize - 1 - i];
218 #else
219                         memcpy(d, s, inc->unitsize);
220 #endif
221                 }
222                 s += inc->unitsize;
223                 d += inc->unitsize;
224         }
225         packet.type = SR_DF_ANALOG;
226         packet.payload = &analog;
227         analog.channels = in->sdi->channels;
228         analog.num_samples = num_samples;
229         analog.mq = 0;
230         analog.mqflags = 0;
231         analog.unit = 0;
232         analog.data = fdata;
233         sr_session_send(in->sdi, &packet);
234 }
235
236 static int process_buffer(struct sr_input *in)
237 {
238         struct context *inc;
239         struct sr_datafeed_packet packet;
240         struct sr_datafeed_meta meta;
241         struct sr_config *src;
242         int offset, chunk_samples, total_samples, processed, max_chunk_samples;
243         int num_samples, i;
244         char channelname[8];
245
246         inc = in->priv;
247         if (!inc->started) {
248                 for (i = 0; i < inc->num_channels; i++) {
249                         snprintf(channelname, 8, "CH%d", i + 1);
250                         sr_channel_new(in->sdi, i, SR_CHANNEL_ANALOG, TRUE, channelname);
251                 }
252
253                 std_session_send_df_header(in->sdi, LOG_PREFIX);
254
255                 packet.type = SR_DF_META;
256                 packet.payload = &meta;
257                 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(inc->samplerate));
258                 meta.config = g_slist_append(NULL, src);
259                 sr_session_send(in->sdi, &packet);
260                 sr_config_free(src);
261
262                 inc->started = TRUE;
263         }
264
265         if (!inc->found_data) {
266                 /* Skip past size of 'fmt ' chunk. */
267                 i = 20 + RL32(in->buf->str + 16);
268                 offset = find_data_chunk(in->buf, i);
269                 if (offset < 0) {
270                         if (in->buf->len > MAX_DATA_CHUNK_OFFSET) {
271                                 sr_err("Couldn't find data chunk.");
272                                 return SR_ERR;
273                         }
274                 }
275                 inc->found_data = TRUE;
276         } else
277                 offset = 0;
278
279         /* Round off up to the last channels * unitsize boundary. */
280         chunk_samples = (in->buf->len - offset) / inc->num_channels / inc->unitsize;
281         max_chunk_samples = CHUNK_SIZE / inc->num_channels / inc->unitsize;
282         processed = 0;
283         total_samples = chunk_samples;
284         while (processed < total_samples) {
285                 if (chunk_samples > max_chunk_samples)
286                         num_samples = max_chunk_samples;
287                 else
288                         num_samples = chunk_samples;
289                 send_chunk(in, offset, num_samples);
290                 offset += num_samples * inc->unitsize;
291                 chunk_samples -= num_samples;
292                 processed += num_samples;
293         }
294
295         if ((unsigned int)offset < in->buf->len) {
296                 /*
297                  * The incoming buffer wasn't processed completely. Stash
298                  * the leftover data for next time.
299                  */
300                 g_string_erase(in->buf, 0, offset);
301         } else
302                 g_string_truncate(in->buf, 0);
303
304         return SR_OK;
305 }
306
307 static int receive(struct sr_input *in, GString *buf)
308 {
309         struct context *inc;
310         int ret;
311
312         g_string_append_len(in->buf, buf->str, buf->len);
313
314         if (in->buf->len < MIN_DATA_CHUNK_OFFSET) {
315                 /*
316                  * Don't even try until there's enough room
317                  * for the data segment to start.
318                  */
319                 return SR_OK;
320         }
321
322         inc = in->priv;
323         if (!in->sdi_ready) {
324                 if ((ret = parse_wav_header(in->buf, inc)) == SR_ERR_NA)
325                         /* Not enough data yet. */
326                         return SR_OK;
327                 else if (ret != SR_OK)
328                         return ret;
329
330                 /* sdi is ready, notify frontend. */
331                 in->sdi_ready = TRUE;
332                 return SR_OK;
333         }
334
335         ret = process_buffer(in);
336
337         return ret;
338 }
339
340 static int end(struct sr_input *in)
341 {
342         struct sr_datafeed_packet packet;
343         struct context *inc;
344         int ret;
345
346         if (in->sdi_ready)
347                 ret = process_buffer(in);
348         else
349                 ret = SR_OK;
350
351         inc = in->priv;
352         if (inc->started) {
353                 packet.type = SR_DF_END;
354                 sr_session_send(in->sdi, &packet);
355         }
356
357         return ret;
358 }
359
360 SR_PRIV struct sr_input_module input_wav = {
361         .id = "wav",
362         .name = "WAV",
363         .desc = "WAV file",
364         .exts = (const char*[]){"wav", NULL},
365         .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
366         .format_match = format_match,
367         .init = init,
368         .receive = receive,
369         .end = end,
370 };