]> sigrok.org Git - libsigrok.git/blob - src/input/wav.c
input/wav: Support for WAVE_FORMAT_EXTENSIBLE.
[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         int fmt_code;
47         uint64_t samplerate;
48         int samplesize;
49         int num_channels;
50         int unitsize;
51         gboolean found_data;
52 };
53
54 static int parse_wav_header(GString *buf, struct context *inc)
55 {
56         uint64_t samplerate;
57         unsigned int fmt_code, samplesize, num_channels, unitsize;
58
59         if (buf->len < MIN_DATA_CHUNK_OFFSET)
60                 return SR_ERR;
61
62         fmt_code = RL16(buf->str + 20);
63         samplerate = RL32(buf->str + 24);
64
65         samplesize = RL16(buf->str + 32);
66         if (samplesize != 1 && samplesize != 2 && samplesize != 4) {
67                 sr_err("Only 8, 16 or 32 bits per sample supported.");
68                 return SR_ERR;
69         }
70
71         num_channels = RL16(buf->str + 22);
72         if (num_channels == 0)
73                 return SR_ERR;
74         unitsize = samplesize / num_channels;
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;
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_OK_CONTINUE;
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;
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;
104                 }
105         } else {
106                 sr_err("Only PCM and floating point samples are supported.");
107                 return SR_ERR;
108         }
109
110         if (inc) {
111                 inc->fmt_code = fmt_code;
112                 inc->samplerate = samplerate;
113                 inc->samplesize = samplesize;
114                 inc->num_channels = num_channels;
115                 inc->unitsize = unitsize;
116                 inc->found_data = FALSE;
117         }
118
119         return SR_OK;
120 }
121
122 static int format_match(GHashTable *metadata)
123 {
124         GString *buf;
125
126         buf = g_hash_table_lookup(metadata, GINT_TO_POINTER(SR_INPUT_META_HEADER));
127         if (strncmp(buf->str, "RIFF", 4))
128                 return FALSE;
129         if (strncmp(buf->str + 8, "WAVE", 4))
130                 return FALSE;
131         if (strncmp(buf->str + 12, "fmt ", 4))
132                 return FALSE;
133         /*
134          * Only gets called when we already know this is a WAV file, so
135          * this parser can log error messages.
136          */
137         if (parse_wav_header(buf, NULL) != SR_OK)
138                 return FALSE;
139
140         return TRUE;
141 }
142
143 static int init(struct sr_input *in, GHashTable *options)
144 {
145         (void)options;
146
147         in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
148
149         return SR_OK;
150 }
151
152 static int find_data_chunk(GString *buf, int initial_offset)
153 {
154         unsigned int offset, i;
155
156         offset = initial_offset;
157         while(offset < MIN(MAX_DATA_CHUNK_OFFSET, buf->len)) {
158                 if (!memcmp(buf->str + offset, "data", 4))
159                         /* Skip into the samples. */
160                         return offset + 8;
161                 for (i = 0; i < 4; i++) {
162                         if (!isalpha(buf->str[offset + i])
163                                         && !isascii(buf->str[offset + i])
164                                         && !isblank(buf->str[offset + i]))
165                                 /* Doesn't look like a chunk ID. */
166                                 return -1;
167                 }
168                 /* Skip past this chunk. */
169                 offset += 8 + RL32(buf->str + offset + 4);
170         }
171
172         return offset;
173 }
174
175 static int initial_receive(struct sr_input *in)
176 {
177         struct sr_datafeed_packet packet;
178         struct sr_datafeed_meta meta;
179         struct sr_channel *ch;
180         struct sr_config *src;
181         struct context *inc;
182         int i;
183         char channelname[8];
184
185         if (!in->buf)
186                 /* Shouldn't happen. */
187                 return SR_ERR;
188
189         inc = in->priv = g_malloc(sizeof(struct context));
190         if (parse_wav_header(in->buf, inc) != SR_OK)
191                 return SR_ERR;
192
193         for (i = 0; i < inc->num_channels; i++) {
194                 snprintf(channelname, 8, "CH%d", i + 1);
195                 ch = sr_channel_new(i, SR_CHANNEL_ANALOG, TRUE, channelname);
196                 in->sdi->channels = g_slist_append(in->sdi->channels, ch);
197         }
198
199         std_session_send_df_header(in->sdi, LOG_PREFIX);
200
201         packet.type = SR_DF_META;
202         packet.payload = &meta;
203         src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(inc->samplerate));
204         meta.config = g_slist_append(NULL, src);
205         sr_session_send(in->sdi, &packet);
206         sr_config_free(src);
207
208         return SR_OK;
209 }
210
211 static void send_chunk(const struct sr_input *in, int offset, int num_samples)
212 {
213         struct sr_datafeed_packet packet;
214         struct sr_datafeed_analog analog;
215         struct context *inc;
216         float fdata[CHUNK_SIZE];
217         uint64_t sample;
218         int total_samples, samplenum;
219         char *s, *d;
220
221         inc = in->priv;
222
223         s = in->buf->str + offset;
224         d = (char *)fdata;
225         memset(fdata, 0, CHUNK_SIZE);
226         total_samples = num_samples * inc->num_channels;
227         for (samplenum = 0; samplenum < total_samples; samplenum++) {
228                 if (inc->fmt_code == WAVE_FORMAT_PCM) {
229                         sample = 0;
230                         memcpy(&sample, s, inc->unitsize);
231                         switch (inc->samplesize) {
232                         case 1:
233                                 /* 8-bit PCM samples are unsigned. */
234                                 fdata[samplenum] = (uint8_t)sample / (float)255;
235                                 break;
236                         case 2:
237                                 fdata[samplenum] = RL16S(&sample) / (float)INT16_MAX;
238                                 break;
239                         case 4:
240                                 fdata[samplenum] = RL32S(&sample) / (float)INT32_MAX;
241                                 break;
242                         }
243                 } else {
244                         /* BINARY32 float */
245 #ifdef WORDS_BIGENDIAN
246                         for (i = 0; i < inc->unitsize; i++)
247                                 d[i] = s[inc->unitsize - i];
248 #else
249                         memcpy(d, s, inc->unitsize);
250 #endif
251                 }
252                 s += inc->unitsize;
253                 d += inc->unitsize;
254         }
255         packet.type = SR_DF_ANALOG;
256         packet.payload = &analog;
257         analog.channels = in->sdi->channels;
258         analog.num_samples = num_samples;
259         analog.mq = 0;
260         analog.mqflags = 0;
261         analog.unit = 0;
262         analog.data = fdata;
263         sr_session_send(in->sdi, &packet);
264 }
265
266 static int receive(const struct sr_input *in, GString *buf)
267 {
268         struct context *inc;
269         int offset, chunk_samples, total_samples, processed, max_chunk_samples, num_samples, i;
270
271         g_string_append_len(in->buf, buf->str, buf->len);
272
273         if (!in->priv) {
274                 if (initial_receive((struct sr_input *)in) != SR_OK)
275                         return SR_ERR;
276                 if (in->buf->len < MIN_DATA_CHUNK_OFFSET) {
277                         /*
278                          * Don't even get started until there's enough room
279                          * for the data segment to start.
280                          */
281                         return SR_OK;
282                 }
283         }
284         inc = in->priv;
285
286         if (!inc->found_data) {
287                 /* Skip past size of 'fmt ' chunk. */
288                 i = 20 + RL32(in->buf->str + 16);
289                 offset = find_data_chunk(in->buf, i);
290                 if (offset < 0) {
291                         if (in->buf->len > MAX_DATA_CHUNK_OFFSET) {
292                                 sr_err("Couldn't find data chunk.");
293                                 return SR_ERR;
294                         }
295                 }
296                 inc->found_data = TRUE;
297         } else
298                 offset = 0;
299
300         /* Round off up to the last channels * unitsize boundary. */
301         chunk_samples = (in->buf->len - offset) / inc->num_channels / inc->unitsize;
302         max_chunk_samples = CHUNK_SIZE / inc->num_channels / inc->unitsize;
303         processed = 0;
304         total_samples = chunk_samples;
305         while (processed < total_samples) {
306                 if (chunk_samples > max_chunk_samples)
307                         num_samples = max_chunk_samples;
308                 else
309                         num_samples = chunk_samples;
310                 send_chunk(in, offset, num_samples);
311                 offset += num_samples * inc->unitsize;
312                 chunk_samples -= num_samples;
313                 processed += num_samples;
314         }
315
316         if ((unsigned int)offset < in->buf->len) {
317                 /*
318                  * The incoming buffer wasn't processed completely. Stash
319                  * the leftover data for next time.
320                  */
321                 g_string_erase(in->buf, 0, offset);
322         } else
323                 g_string_truncate(in->buf, 0);
324
325         return SR_OK;
326 }
327
328 static int cleanup(struct sr_input *in)
329 {
330         struct sr_datafeed_packet packet;
331
332         if (in->priv) {
333                 /* End of stream. */
334                 packet.type = SR_DF_END;
335                 sr_session_send(in->sdi, &packet);
336
337                 g_free(in->priv);
338                 in->priv = NULL;
339         }
340
341         return SR_OK;
342 }
343
344 SR_PRIV struct sr_input_module input_wav = {
345         .id = "wav",
346         .name = "WAV",
347         .desc = "WAV file",
348         .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
349         .format_match = format_match,
350         .init = init,
351         .receive = receive,
352         .cleanup = cleanup,
353 };
354