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