]> sigrok.org Git - libsigrok.git/blob - src/output/srzip.c
srzip: Save analog data.
[libsigrok.git] / src / output / srzip.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 <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <glib.h>
25 #include <glib/gstdio.h>
26 #include <zip.h>
27 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
29
30 #define LOG_PREFIX "output/srzip"
31
32 struct out_context {
33         gboolean zip_created;
34         uint64_t samplerate;
35         char *filename;
36 };
37
38 static int init(struct sr_output *o, GHashTable *options)
39 {
40         struct out_context *outc;
41
42         (void)options;
43
44         if (!o->filename || o->filename[0] == '\0') {
45                 sr_info("srzip output module requires a file name, cannot save.");
46                 return SR_ERR_ARG;
47         }
48
49         outc = g_malloc0(sizeof(struct out_context));
50         outc->filename = g_strdup(o->filename);
51         o->priv = outc;
52
53         return SR_OK;
54 }
55
56 static int zip_create(const struct sr_output *o)
57 {
58         struct out_context *outc;
59         struct zip *zipfile;
60         struct zip_source *versrc, *metasrc;
61         struct sr_channel *ch;
62         GVariant *gvar;
63         GKeyFile *meta;
64         GSList *l;
65         const char *devgroup;
66         char *s, *metabuf;
67         gsize metalen;
68         guint logic_channels = 0, analog_channels = 0;
69
70         outc = o->priv;
71
72         if (outc->samplerate == 0 && sr_config_get(o->sdi->driver, o->sdi, NULL,
73                                         SR_CONF_SAMPLERATE, &gvar) == SR_OK) {
74                 outc->samplerate = g_variant_get_uint64(gvar);
75                 g_variant_unref(gvar);
76         }
77
78         /* Quietly delete it first, libzip wants replace ops otherwise. */
79         g_unlink(outc->filename);
80         zipfile = zip_open(outc->filename, ZIP_CREATE, NULL);
81         if (!zipfile)
82                 return SR_ERR;
83
84         /* "version" */
85         versrc = zip_source_buffer(zipfile, "2", 1, FALSE);
86         if (zip_add(zipfile, "version", versrc) < 0) {
87                 sr_err("Error saving version into zipfile: %s",
88                         zip_strerror(zipfile));
89                 zip_source_free(versrc);
90                 zip_discard(zipfile);
91                 return SR_ERR;
92         }
93
94         /* init "metadata" */
95         meta = g_key_file_new();
96
97         g_key_file_set_string(meta, "global", "sigrok version",
98                         SR_PACKAGE_VERSION_STRING);
99
100         devgroup = "device 1";
101         g_key_file_set_string(meta, devgroup, "capturefile", "logic-1");
102
103         s = sr_samplerate_string(outc->samplerate);
104         g_key_file_set_string(meta, devgroup, "samplerate", s);
105         g_free(s);
106
107         for (l = o->sdi->channels; l; l = l->next) {
108                 ch = l->data;
109                 switch (ch->type) {
110                         case SR_CHANNEL_LOGIC:
111                                 logic_channels++;
112                                 break;
113                         case SR_CHANNEL_ANALOG:
114                                 analog_channels++;
115                                 break;
116                 }
117         }
118
119         g_key_file_set_integer(meta, devgroup, "total probes", logic_channels);
120         g_key_file_set_integer(meta, devgroup, "total analog", analog_channels);
121
122         for (l = o->sdi->channels; l; l = l->next) {
123                 ch = l->data;
124                 switch (ch->type) {
125                         case SR_CHANNEL_LOGIC:
126                                 s = g_strdup_printf("probe%d", ch->index + 1);
127                                 break;
128                         case SR_CHANNEL_ANALOG:
129                                 s = g_strdup_printf("analog%d", ch->index + 1);
130                                 break;
131                 }
132                 if (ch->enabled)
133                         g_key_file_set_string(meta, devgroup, s, ch->name);
134                 g_free(s);
135         }
136
137         metabuf = g_key_file_to_data(meta, &metalen, NULL);
138         g_key_file_free(meta);
139
140         metasrc = zip_source_buffer(zipfile, metabuf, metalen, FALSE);
141         if (zip_add(zipfile, "metadata", metasrc) < 0) {
142                 sr_err("Error saving metadata into zipfile: %s",
143                         zip_strerror(zipfile));
144                 zip_source_free(metasrc);
145                 zip_discard(zipfile);
146                 g_free(metabuf);
147                 return SR_ERR;
148         }
149
150         if (zip_close(zipfile) < 0) {
151                 sr_err("Error saving zipfile: %s", zip_strerror(zipfile));
152                 zip_discard(zipfile);
153                 g_free(metabuf);
154                 return SR_ERR;
155         }
156         g_free(metabuf);
157
158         return SR_OK;
159 }
160
161 static int zip_append(const struct sr_output *o, unsigned char *buf,
162                 int unitsize, int length)
163 {
164         struct out_context *outc;
165         struct zip *archive;
166         struct zip_source *logicsrc;
167         int64_t i, num_files;
168         struct zip_stat zs;
169         struct zip_source *metasrc;
170         GKeyFile *kf;
171         GError *error;
172         uint64_t chunk_num;
173         const char *entry_name;
174         char *metabuf;
175         gsize metalen;
176         char *chunkname;
177         unsigned int next_chunk_num;
178
179         outc = o->priv;
180         if (!(archive = zip_open(outc->filename, 0, NULL)))
181                 return SR_ERR;
182
183         if (zip_stat(archive, "metadata", 0, &zs) < 0) {
184                 sr_err("Failed to open metadata: %s", zip_strerror(archive));
185                 zip_discard(archive);
186                 return SR_ERR;
187         }
188         kf = sr_sessionfile_read_metadata(archive, &zs);
189         if (!kf) {
190                 zip_discard(archive);
191                 return SR_ERR_DATA;
192         }
193         /*
194          * If the file was only initialized but doesn't yet have any
195          * data it in, it won't have a unitsize field in metadata yet.
196          */
197         error = NULL;
198         metabuf = NULL;
199         if (!g_key_file_has_key(kf, "device 1", "unitsize", &error)) {
200                 if (error && error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND) {
201                         sr_err("Failed to check unitsize key: %s", error->message);
202                         g_error_free(error);
203                         g_key_file_free(kf);
204                         zip_discard(archive);
205                         return SR_ERR;
206                 }
207                 g_clear_error(&error);
208
209                 /* Add unitsize field. */
210                 g_key_file_set_integer(kf, "device 1", "unitsize", unitsize);
211                 metabuf = g_key_file_to_data(kf, &metalen, NULL);
212                 metasrc = zip_source_buffer(archive, metabuf, metalen, FALSE);
213
214                 if (zip_replace(archive, zs.index, metasrc) < 0) {
215                         sr_err("Failed to replace metadata: %s",
216                                 zip_strerror(archive));
217                         g_key_file_free(kf);
218                         zip_source_free(metasrc);
219                         zip_discard(archive);
220                         g_free(metabuf);
221                         return SR_ERR;
222                 }
223         }
224         g_key_file_free(kf);
225
226         next_chunk_num = 1;
227         num_files = zip_get_num_entries(archive, 0);
228         for (i = 0; i < num_files; i++) {
229                 entry_name = zip_get_name(archive, i, 0);
230                 if (!entry_name || strncmp(entry_name, "logic-1", 7) != 0)
231                         continue;
232                 if (entry_name[7] == '\0') {
233                         /* This file has no extra chunks, just a single "logic-1".
234                          * Rename it to "logic-1-1" * and continue with chunk 2. */
235                         if (zip_rename(archive, i, "logic-1-1") < 0) {
236                                 sr_err("Failed to rename 'logic-1' to 'logic-1-1': %s",
237                                         zip_strerror(archive));
238                                 zip_discard(archive);
239                                 g_free(metabuf);
240                                 return SR_ERR;
241                         }
242                         next_chunk_num = 2;
243                         break;
244                 } else if (entry_name[7] == '-') {
245                         chunk_num = g_ascii_strtoull(entry_name + 8, NULL, 10);
246                         if (chunk_num < G_MAXINT && chunk_num >= next_chunk_num)
247                                 next_chunk_num = chunk_num + 1;
248                 }
249         }
250
251         if (length % unitsize != 0) {
252                 sr_warn("Chunk size %d not a multiple of the"
253                         " unit size %d.", length, unitsize);
254         }
255         logicsrc = zip_source_buffer(archive, buf, length, FALSE);
256         chunkname = g_strdup_printf("logic-1-%u", next_chunk_num);
257         i = zip_add(archive, chunkname, logicsrc);
258         g_free(chunkname);
259         if (i < 0) {
260                 sr_err("Failed to add chunk 'logic-1-%u': %s",
261                         next_chunk_num, zip_strerror(archive));
262                 zip_source_free(logicsrc);
263                 zip_discard(archive);
264                 g_free(metabuf);
265                 return SR_ERR;
266         }
267         if (zip_close(archive) < 0) {
268                 sr_err("Error saving session file: %s", zip_strerror(archive));
269                 zip_discard(archive);
270                 g_free(metabuf);
271                 return SR_ERR;
272         }
273         g_free(metabuf);
274
275         return SR_OK;
276 }
277
278 static int zip_append_analog(const struct sr_output *o,
279                 const struct sr_datafeed_analog *analog)
280 {
281         struct out_context *outc;
282         struct zip *archive;
283         struct zip_source *analogsrc;
284         int64_t i, num_files;
285         struct zip_stat zs;
286         uint64_t chunk_num;
287         const char *entry_name;
288         char *basename;
289         gsize baselen;
290         struct sr_channel *channel;
291         float *chunkbuf;
292         gsize chunksize;
293         char *chunkname;
294         unsigned int next_chunk_num;
295
296         outc = o->priv;
297         if (!(archive = zip_open(outc->filename, 0, NULL)))
298                 return SR_ERR;
299
300         if (zip_stat(archive, "metadata", 0, &zs) < 0) {
301                 sr_err("Failed to open metadata: %s", zip_strerror(archive));
302                 zip_discard(archive);
303                 return SR_ERR;
304         }
305
306         /* TODO: support packets covering multiple channels */
307         if (g_slist_length(analog->meaning->channels) != 1) {
308                 sr_err("Analog packets covering multiple channels not supported yet");
309                 return SR_ERR;
310         }
311         channel = analog->meaning->channels->data;
312
313         basename = g_strdup_printf("analog-1-%u", channel->index + 1);
314         baselen = strlen(basename);
315         next_chunk_num = 1;
316         num_files = zip_get_num_entries(archive, 0);
317         for (i = 0; i < num_files; i++) {
318                 entry_name = zip_get_name(archive, i, 0);
319                 if (!entry_name || strncmp(entry_name, basename, baselen) != 0) {
320                         continue;
321                 } else if (entry_name[baselen] == '-') {
322                         chunk_num = g_ascii_strtoull(entry_name + baselen + 1, NULL, 10);
323                         if (chunk_num < G_MAXINT && chunk_num >= next_chunk_num)
324                                 next_chunk_num = chunk_num + 1;
325                 }
326         }
327
328         chunksize = sizeof(float) * analog->num_samples;
329         if (!(chunkbuf = g_try_malloc(chunksize)))
330                 return SR_ERR;
331         if (sr_analog_to_float(analog, chunkbuf) != SR_OK)
332                 return SR_ERR;
333
334         analogsrc = zip_source_buffer(archive, chunkbuf, chunksize, FALSE);
335         chunkname = g_strdup_printf("%s-%u", basename, next_chunk_num);
336         i = zip_add(archive, chunkname, analogsrc);
337         g_free(chunkname);
338         if (i < 0) {
339                 sr_err("Failed to add chunk '%s': %s", chunkname, zip_strerror(archive));
340                 zip_source_free(analogsrc);
341                 zip_discard(archive);
342                 return SR_ERR;
343         }
344         if (zip_close(archive) < 0) {
345                 sr_err("Error saving session file: %s", zip_strerror(archive));
346                 zip_discard(archive);
347                 return SR_ERR;
348         }
349
350         return SR_OK;
351 }
352
353 static int receive(const struct sr_output *o, const struct sr_datafeed_packet *packet,
354                 GString **out)
355 {
356         struct out_context *outc;
357         const struct sr_datafeed_meta *meta;
358         const struct sr_datafeed_logic *logic;
359         const struct sr_datafeed_analog *analog;
360         const struct sr_config *src;
361         GSList *l;
362
363         int ret;
364
365         *out = NULL;
366         if (!o || !o->sdi || !(outc = o->priv))
367                 return SR_ERR_ARG;
368
369         switch (packet->type) {
370         case SR_DF_META:
371                 meta = packet->payload;
372                 for (l = meta->config; l; l = l->next) {
373                         src = l->data;
374                         if (src->key != SR_CONF_SAMPLERATE)
375                                 continue;
376                         outc->samplerate = g_variant_get_uint64(src->data);
377                 }
378                 break;
379         case SR_DF_LOGIC:
380                 if (!outc->zip_created) {
381                         if ((ret = zip_create(o)) != SR_OK)
382                                 return ret;
383                         outc->zip_created = TRUE;
384                 }
385                 logic = packet->payload;
386                 ret = zip_append(o, logic->data, logic->unitsize, logic->length);
387                 if (ret != SR_OK)
388                         return ret;
389                 break;
390         case SR_DF_ANALOG:
391                 if (!outc->zip_created) {
392                         if ((ret = zip_create(o)) != SR_OK)
393                                 return ret;
394                         outc->zip_created = TRUE;
395                 }
396                 analog = packet->payload;
397                 ret = zip_append_analog(o, analog);
398                 if (ret != SR_OK)
399                         return ret;
400                 break;
401         }
402
403         return SR_OK;
404 }
405
406 static struct sr_option options[] = {
407         ALL_ZERO
408 };
409
410 static const struct sr_option *get_options(void)
411 {
412         if (!options[0].def)
413                 options[0].def = g_variant_ref_sink(g_variant_new_string(""));
414
415         return options;
416 }
417
418 static int cleanup(struct sr_output *o)
419 {
420         struct out_context *outc;
421
422         outc = o->priv;
423         g_variant_unref(options[0].def);
424         g_free(outc->filename);
425         g_free(outc);
426         o->priv = NULL;
427
428         return SR_OK;
429 }
430
431 SR_PRIV struct sr_output_module output_srzip = {
432         .id = "srzip",
433         .name = "srzip",
434         .desc = "srzip session file",
435         .exts = (const char*[]){"sr", NULL},
436         .flags = SR_OUTPUT_INTERNAL_IO_HANDLING,
437         .options = get_options,
438         .init = init,
439         .receive = receive,
440         .cleanup = cleanup,
441 };