]> sigrok.org Git - libsigrok.git/blob - src/input/wav.c
output/csv: use intermediate time_t var, silence compiler warning
[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         GSList *prev_sr_channels;
55 };
56
57 static 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
128 static 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
152 static int init(struct sr_input *in, GHashTable *options)
153 {
154         (void)options;
155
156         in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
157         in->priv = g_malloc0(sizeof(struct context));
158
159         return SR_OK;
160 }
161
162 static int find_data_chunk(GString *buf, int initial_offset)
163 {
164         unsigned int offset, i;
165
166         offset = initial_offset;
167         while (offset < MIN(MAX_DATA_CHUNK_OFFSET, buf->len)) {
168                 if (!memcmp(buf->str + offset, "data", 4))
169                         /* Skip into the samples. */
170                         return offset + 8;
171                 for (i = 0; i < 4; i++) {
172                         if (!isalnum(buf->str[offset + i])
173                                         && !isblank(buf->str[offset + i]))
174                                 /* Doesn't look like a chunk ID. */
175                                 return -1;
176                 }
177                 /* Skip past this chunk. */
178                 offset += 8 + RL32(buf->str + offset + 4);
179         }
180
181         if (offset > MAX_DATA_CHUNK_OFFSET)
182                 return -1;
183
184         return offset;
185 }
186
187 static void send_chunk(const struct sr_input *in, int offset, int num_samples)
188 {
189         struct sr_datafeed_packet packet;
190         struct sr_datafeed_analog analog;
191         struct sr_analog_encoding encoding;
192         struct sr_analog_meaning meaning;
193         struct sr_analog_spec spec;
194         struct context *inc;
195         float *fdata;
196         int total_samples, samplenum;
197         char *s, *d;
198
199         inc = in->priv;
200
201         total_samples = num_samples * inc->num_channels;
202         fdata = g_malloc0(total_samples * sizeof(float));
203         s = in->buf->str + offset;
204         d = (char *)fdata;
205
206         for (samplenum = 0; samplenum < total_samples; samplenum++) {
207                 if (inc->fmt_code == WAVE_FORMAT_PCM_) {
208                         switch (inc->unitsize) {
209                         case 1:
210                                 /* 8-bit PCM samples are unsigned. */
211                                 fdata[samplenum] = *(uint8_t*)(s) / (float)255;
212                                 break;
213                         case 2:
214                                 fdata[samplenum] = RL16S(s) / (float)INT16_MAX;
215                                 break;
216                         case 4:
217                                 fdata[samplenum] = RL32S(s) / (float)INT32_MAX;
218                                 break;
219                         }
220                 } else {
221                         /* BINARY32 float */
222 #ifdef WORDS_BIGENDIAN
223                         int i;
224                         for (i = 0; i < inc->unitsize; i++)
225                                 d[i] = s[inc->unitsize - 1 - i];
226 #else
227                         memcpy(d, s, inc->unitsize);
228 #endif
229                 }
230                 s += inc->unitsize;
231                 d += inc->unitsize;
232         }
233
234         /* TODO: Use proper 'digits' value for this device (and its modes). */
235         sr_analog_init(&analog, &encoding, &meaning, &spec, 2);
236         packet.type = SR_DF_ANALOG;
237         packet.payload = &analog;
238         analog.num_samples = num_samples;
239         analog.data = fdata;
240         analog.meaning->channels = in->sdi->channels;
241         analog.meaning->mq = 0;
242         analog.meaning->mqflags = 0;
243         analog.meaning->unit = 0;
244         sr_session_send(in->sdi, &packet);
245         g_free(fdata);
246 }
247
248 static int process_buffer(struct sr_input *in)
249 {
250         struct context *inc;
251         int offset, chunk_samples, total_samples, processed, max_chunk_samples;
252         int num_samples, i;
253
254         inc = in->priv;
255         if (!inc->started) {
256                 std_session_send_df_header(in->sdi);
257                 (void)sr_session_send_meta(in->sdi, SR_CONF_SAMPLERATE,
258                         g_variant_new_uint64(inc->samplerate));
259                 inc->started = TRUE;
260         }
261
262         if (!inc->found_data) {
263                 /* Skip past size of 'fmt ' chunk. */
264                 i = 20 + RL32(in->buf->str + 16);
265                 offset = find_data_chunk(in->buf, i);
266                 if (offset < 0) {
267                         if (in->buf->len > MAX_DATA_CHUNK_OFFSET) {
268                                 sr_err("Couldn't find data chunk.");
269                                 return SR_ERR;
270                         }
271                 }
272                 inc->found_data = TRUE;
273         } else
274                 offset = 0;
275
276         /* Round off up to the last channels * unitsize boundary. */
277         chunk_samples = (in->buf->len - offset) / inc->samplesize;
278         max_chunk_samples = CHUNK_SIZE / inc->samplesize;
279         processed = 0;
280         total_samples = chunk_samples;
281         while (processed < total_samples) {
282                 if (chunk_samples > max_chunk_samples)
283                         num_samples = max_chunk_samples;
284                 else
285                         num_samples = chunk_samples;
286                 send_chunk(in, offset, num_samples);
287                 offset += num_samples * inc->samplesize;
288                 chunk_samples -= num_samples;
289                 processed += num_samples;
290         }
291
292         if ((unsigned int)offset < in->buf->len) {
293                 /*
294                  * The incoming buffer wasn't processed completely. Stash
295                  * the leftover data for next time.
296                  */
297                 g_string_erase(in->buf, 0, offset);
298         } else
299                 g_string_truncate(in->buf, 0);
300
301         return SR_OK;
302 }
303
304 /*
305  * Check the channel list for consistency across file re-import. See
306  * the VCD input module for more details and motivation.
307  */
308
309 static void keep_header_for_reread(const struct sr_input *in)
310 {
311         struct context *inc;
312
313         inc = in->priv;
314         g_slist_free_full(inc->prev_sr_channels, sr_channel_free_cb);
315         inc->prev_sr_channels = in->sdi->channels;
316         in->sdi->channels = NULL;
317 }
318
319 static int check_header_in_reread(const struct sr_input *in)
320 {
321         struct context *inc;
322
323         if (!in)
324                 return FALSE;
325         inc = in->priv;
326         if (!inc)
327                 return FALSE;
328         if (!inc->prev_sr_channels)
329                 return TRUE;
330
331         if (sr_channel_lists_differ(inc->prev_sr_channels, in->sdi->channels)) {
332                 sr_err("Channel list change not supported for file re-read.");
333                 return FALSE;
334         }
335         g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
336         in->sdi->channels = inc->prev_sr_channels;
337         inc->prev_sr_channels = NULL;
338
339         return TRUE;
340 }
341
342 static int receive(struct sr_input *in, GString *buf)
343 {
344         struct context *inc;
345         int ret;
346         char channelname[16];
347
348         g_string_append_len(in->buf, buf->str, buf->len);
349
350         if (in->buf->len < MIN_DATA_CHUNK_OFFSET) {
351                 /*
352                  * Don't even try until there's enough room
353                  * for the data segment to start.
354                  */
355                 return SR_OK;
356         }
357
358         inc = in->priv;
359         if (!in->sdi_ready) {
360                 if ((ret = parse_wav_header(in->buf, inc)) == SR_ERR_NA)
361                         /* Not enough data yet. */
362                         return SR_OK;
363                 else if (ret != SR_OK)
364                         return ret;
365
366                 for (int i = 0; i < inc->num_channels; i++) {
367                         snprintf(channelname, sizeof(channelname), "CH%d", i + 1);
368                         sr_channel_new(in->sdi, i, SR_CHANNEL_ANALOG, TRUE, channelname);
369                 }
370                 if (!check_header_in_reread(in))
371                         return SR_ERR_DATA;
372
373                 /* sdi is ready, notify frontend. */
374                 in->sdi_ready = TRUE;
375                 return SR_OK;
376         }
377
378         ret = process_buffer(in);
379
380         return ret;
381 }
382
383 static int end(struct sr_input *in)
384 {
385         struct context *inc;
386         int ret;
387
388         if (in->sdi_ready)
389                 ret = process_buffer(in);
390         else
391                 ret = SR_OK;
392
393         inc = in->priv;
394         if (inc->started)
395                 std_session_send_df_end(in->sdi);
396
397         return ret;
398 }
399
400 static int reset(struct sr_input *in)
401 {
402         struct context *inc;
403
404         inc = in->priv;
405         memset(inc, 0, sizeof(*inc));
406
407         /*
408          * Create, and re-create channels for every iteration of file
409          * import. Other logic will enforce a consistent set of channels
410          * across re-import, or an appropriate error message when file
411          * properties should change.
412          */
413         keep_header_for_reread(in);
414
415         g_string_truncate(in->buf, 0);
416
417         return SR_OK;
418 }
419
420 SR_PRIV struct sr_input_module input_wav = {
421         .id = "wav",
422         .name = "WAV",
423         .desc = "Microsoft WAV file format data",
424         .exts = (const char*[]){"wav", NULL},
425         .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
426         .format_match = format_match,
427         .init = init,
428         .receive = receive,
429         .end = end,
430         .reset = reset,
431 };