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