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