]> sigrok.org Git - libsigrok.git/blob - src/output/wav.c
Rework sr_period_string
[libsigrok.git] / src / output / wav.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 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 <string.h>
22 #include <libsigrok/libsigrok.h>
23 #include "libsigrok-internal.h"
24
25 #define LOG_PREFIX "output/wav"
26
27 /* Minimum/maximum number of samples per channel to put in a data chunk */
28 #define MIN_DATA_CHUNK_SAMPLES 10
29
30 struct out_context {
31         double scale;
32         gboolean header_done;
33         uint64_t samplerate;
34         int num_channels;
35         GSList *channels;
36         int chanbuf_size;
37         int *chanbuf_used;
38         uint8_t **chanbuf;
39         float *fdata;
40 };
41
42 static int realloc_chanbufs(const struct sr_output *o, int size)
43 {
44         struct out_context *outc;
45         int i;
46
47         outc = o->priv;
48         for (i = 0; i < outc->num_channels; i++) {
49                 if (!(outc->chanbuf[i] = g_try_realloc(outc->chanbuf[i], sizeof(float) * size))) { 
50                         sr_err("Unable to allocate enough output buffer memory.");
51                         return SR_ERR;
52                 }
53                 outc->chanbuf_used[i] = 0;
54         }
55         outc->chanbuf_size = size;
56
57         return SR_OK;
58 }
59
60 static int flush_chanbufs(const struct sr_output *o, GString *out)
61 {
62         struct out_context *outc;
63         int num_samples, i, j;
64         char *buf, *bufp;
65
66         outc = o->priv;
67
68         /* Any one of them will do. */
69         num_samples = outc->chanbuf_used[0];
70         if (!(buf = g_try_malloc(4 * num_samples * outc->num_channels))) {
71                 sr_err("Unable to allocate enough interleaved output buffer memory.");
72                 return SR_ERR;
73         }
74
75         bufp = buf;
76         for (i = 0; i < num_samples; i++) {
77                 for (j = 0; j < outc->num_channels; j++) {
78                         memcpy(bufp, outc->chanbuf[j] + i * 4, 4);
79                         bufp += 4;
80                 }
81         }
82         g_string_append_len(out, buf, 4 * num_samples * outc->num_channels);
83         g_free(buf);
84
85         for (i = 0; i < outc->num_channels; i++)
86                 outc->chanbuf_used[i] = 0;
87
88         return SR_OK;
89 }
90
91 static int init(struct sr_output *o, GHashTable *options)
92 {
93         struct out_context *outc;
94         struct sr_channel *ch;
95         GSList *l;
96
97         outc = g_malloc0(sizeof(struct out_context));
98         o->priv = outc;
99         outc->scale = g_variant_get_double(g_hash_table_lookup(options, "scale"));
100
101         for (l = o->sdi->channels; l; l = l->next) {
102                 ch = l->data;
103                 if (ch->type != SR_CHANNEL_ANALOG)
104                         continue;
105                 if (!ch->enabled)
106                         continue;
107                 outc->channels = g_slist_append(outc->channels, ch);
108                 outc->num_channels++;
109         }
110
111         outc->chanbuf = g_malloc0(sizeof(float *) * outc->num_channels);
112         outc->chanbuf_used = g_malloc0(sizeof(int) * outc->num_channels);
113
114         /* Start off the interleaved buffer with 100 samples/channel. */
115         realloc_chanbufs(o, 100);
116
117         return SR_OK;
118 }
119
120 static void add_data_chunk(const struct sr_output *o, GString *gs)
121 {
122         struct out_context *outc;
123         char tmp[4];
124
125         outc = o->priv;
126         g_string_append(gs, "fmt ");
127         /* Remaining chunk size */
128         WL32(tmp, 0x12);
129         g_string_append_len(gs, tmp, 4);
130         /* Format code 3 = IEEE float */
131         WL16(tmp, 0x0003);
132         g_string_append_len(gs, tmp, 2);
133         /* Number of channels */
134         WL16(tmp, outc->num_channels);
135         g_string_append_len(gs, tmp, 2);
136         /* Samplerate */
137         WL32(tmp, outc->samplerate);
138         g_string_append_len(gs, tmp, 4);
139         /* Byterate, using 32-bit floats. */
140         WL32(tmp, outc->samplerate * outc->num_channels * 4);
141         g_string_append_len(gs, tmp, 4);
142         /* Blockalign */
143         WL16(tmp, outc->num_channels * 4);
144         g_string_append_len(gs, tmp, 2);
145         /* Bits per sample */
146         WL16(tmp, 32);
147         g_string_append_len(gs, tmp, 2);
148         WL16(tmp, 0);
149         g_string_append_len(gs, tmp, 2);
150
151         g_string_append(gs, "data");
152         /* Data chunk size, max it out. */
153         WL32(tmp, 0xffffffff);
154         g_string_append_len(gs, tmp, 4);
155 }
156
157 static GString *gen_header(const struct sr_output *o)
158 {
159         struct out_context *outc;
160         GVariant *gvar;
161         GString *header;
162         char tmp[4];
163
164         outc = o->priv;
165         if (outc->samplerate == 0) {
166                 if (sr_config_get(o->sdi->driver, o->sdi, NULL, SR_CONF_SAMPLERATE,
167                                 &gvar) == SR_OK) {
168                         outc->samplerate = g_variant_get_uint64(gvar);
169                         g_variant_unref(gvar);
170                 }
171         }
172
173         header = g_string_sized_new(512);
174         g_string_append(header, "RIFF");
175         /* Total size. Max out the field. */
176         WL32(tmp, 0xffffffff);
177         g_string_append_len(header, tmp, 4);
178         g_string_append(header, "WAVE");
179         add_data_chunk(o, header);
180
181         return header;
182 }
183
184 /*
185  * Stores the float in little-endian BINARY32 IEEE-754 2008 format.
186  */
187 static void float_to_le(uint8_t *buf, float value)
188 {
189         char *old;
190
191         old = (char *)&value;
192 #ifdef WORDS_BIGENDIAN
193         buf[0] = old[3];
194         buf[1] = old[2];
195         buf[2] = old[1];
196         buf[3] = old[0];
197 #else
198         buf[0] = old[0];
199         buf[1] = old[1];
200         buf[2] = old[2];
201         buf[3] = old[3];
202 #endif
203 }
204
205 /*
206  * Returns the number of samples used in the current channel buffers,
207  * or -1 if they're not all the same.
208  */
209 static int check_chanbuf_size(const struct sr_output *o)
210 {
211         struct out_context *outc;
212         int size, i;
213
214         outc = o->priv;
215         size = 0;
216         for (i = 0; i < outc->num_channels; i++) {
217                 if (size == 0) {
218                         if (outc->chanbuf_used[i] == 0) {
219                                 /* Nothing in all the buffers yet. */
220                                 size = -1;
221                                 break;
222                         } else
223                                 /* New high water mark. */
224                                 size = outc->chanbuf_used[i];
225                 } else if (outc->chanbuf_used[i] != size) {
226                         /* All channel buffers are not equally full yet. */
227                         size = -1;
228                         break;
229                 }
230         }
231
232         return size;
233 }
234
235 static int receive(const struct sr_output *o, const struct sr_datafeed_packet *packet,
236                 GString **out)
237 {
238         struct out_context *outc;
239         const struct sr_datafeed_meta *meta;
240         const struct sr_datafeed_analog *analog;
241         const struct sr_config *src;
242         struct sr_channel *ch;
243         GSList *l;
244         const GSList *channels;
245         float f;
246         int num_channels, num_samples, size, *chan_idx, idx, i, j, ret;
247         float *data;
248         uint8_t *buf;
249
250         *out = NULL;
251         if (!o || !o->sdi || !(outc = o->priv))
252                 return SR_ERR_ARG;
253
254         switch (packet->type) {
255         case SR_DF_META:
256                 meta = packet->payload;
257                 for (l = meta->config; l; l = l->next) {
258                         src = l->data;
259                         if (src->key != SR_CONF_SAMPLERATE)
260                                 continue;
261                         outc->samplerate = g_variant_get_uint64(src->data);
262                 }
263                 break;
264         case SR_DF_ANALOG:
265                 if (!outc->header_done) {
266                         *out = gen_header(o);
267                         outc->header_done = TRUE;
268                 } else
269                         *out = g_string_sized_new(512);
270
271                 analog = packet->payload;
272                 num_samples = analog->num_samples;
273                 channels = analog->meaning->channels;
274                 num_channels = g_slist_length(analog->meaning->channels);
275                 if (!(data = g_try_realloc(outc->fdata, sizeof(float) * num_samples * num_channels)))
276                         return SR_ERR_MALLOC;
277                 outc->fdata = data;
278                 ret = sr_analog_to_float(analog, data);
279                 if (ret != SR_OK)
280                         return ret;
281
282                 if (num_samples == 0)
283                         return SR_OK;
284
285                 if (num_channels > outc->num_channels) {
286                         sr_err("Packet has %d channels, but only %d were enabled.",
287                                         num_channels, outc->num_channels);
288                         return SR_ERR;
289                 }
290
291                 if (num_samples > outc->chanbuf_size) {
292                         if (realloc_chanbufs(o, analog->num_samples) != SR_OK)
293                                 return SR_ERR_MALLOC;
294                 }
295
296                 /* Index the channels in this packet, so we can interleave quicker. */
297                 chan_idx = g_malloc(sizeof(int) * outc->num_channels);
298                 for (i = 0; i < num_channels; i++) {
299                         ch = g_slist_nth_data((GSList *) channels, i);
300                         chan_idx[i] = g_slist_index(outc->channels, ch);
301                 }
302
303                 for (i = 0; i < num_samples; i++) {
304                         for (j = 0; j < num_channels; j++) {
305                                 idx = chan_idx[j];
306                                 buf = outc->chanbuf[idx] + outc->chanbuf_used[idx]++ * 4;
307                                 f = data[i * num_channels + j];
308                                 if (outc->scale != 0.0)
309                                         f /= outc->scale;
310                                 float_to_le(buf, f);
311                         }
312                 }
313                 g_free(chan_idx);
314
315                 size = check_chanbuf_size(o);
316                 if (size > MIN_DATA_CHUNK_SAMPLES)
317                         if (flush_chanbufs(o, *out) != SR_OK)
318                                 return SR_ERR;
319                 break;
320         case SR_DF_END:
321                 size = check_chanbuf_size(o);
322                 if (size > 0) {
323                         *out = g_string_sized_new(4 * size * outc->num_channels);
324                         if (flush_chanbufs(o, *out) != SR_OK)
325                                 return SR_ERR;
326                 }
327                 break;
328         }
329
330         return SR_OK;
331 }
332
333 static struct sr_option options[] = {
334         { "scale", "Scale", "Scale values by factor", NULL, NULL },
335         ALL_ZERO
336 };
337
338 static const struct sr_option *get_options(void)
339 {
340         if (!options[0].def)
341                 options[0].def = g_variant_ref_sink(g_variant_new_double(0.0));
342
343         return options;
344 }
345
346 static int cleanup(struct sr_output *o)
347 {
348         struct out_context *outc;
349         int i;
350
351         outc = o->priv;
352         g_slist_free(outc->channels);
353         g_variant_unref(options[0].def);
354         for (i = 0; i < outc->num_channels; i++)
355                 g_free(outc->chanbuf[i]);
356         g_free(outc->chanbuf_used);
357         g_free(outc->chanbuf);
358         g_free(outc->fdata);
359         g_free(outc);
360         o->priv = NULL;
361
362         return SR_OK;
363 }
364
365 SR_PRIV struct sr_output_module output_wav = {
366         .id = "wav",
367         .name = "WAV",
368         .desc = "Microsoft WAV file format",
369         .exts = (const char*[]){"wav", NULL},
370         .flags = 0,
371         .options = get_options,
372         .init = init,
373         .receive = receive,
374         .cleanup = cleanup,
375 };