]> sigrok.org Git - libsigrok.git/blob - src/session.c
dev_acquisition_{start,stop}(): Drop duplicate 'cb_data' parameter.
[libsigrok.git] / src / session.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2015 Daniel Elstner <daniel.kitta@gmail.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <glib.h>
28 #include <libsigrok/libsigrok.h>
29 #include "libsigrok-internal.h"
30
31 /** @cond PRIVATE */
32 #define LOG_PREFIX "session"
33 /** @endcond */
34
35 /**
36  * @file
37  *
38  * Creating, using, or destroying libsigrok sessions.
39  */
40
41 /**
42  * @defgroup grp_session Session handling
43  *
44  * Creating, using, or destroying libsigrok sessions.
45  *
46  * @{
47  */
48
49 struct datafeed_callback {
50         sr_datafeed_callback cb;
51         void *cb_data;
52 };
53
54 /** Custom GLib event source for generic descriptor I/O.
55  * @see https://developer.gnome.org/glib/stable/glib-The-Main-Event-Loop.html
56  * @internal
57  */
58 struct fd_source {
59         GSource base;
60
61         int64_t timeout_us;
62         int64_t due_us;
63
64         /* Meta-data needed to keep track of installed sources */
65         struct sr_session *session;
66         void *key;
67
68         GPollFD pollfd;
69 };
70
71 /** FD event source prepare() method.
72  * This is called immediately before poll().
73  */
74 static gboolean fd_source_prepare(GSource *source, int *timeout)
75 {
76         int64_t now_us;
77         struct fd_source *fsource;
78         int remaining_ms;
79
80         fsource = (struct fd_source *)source;
81
82         if (fsource->timeout_us >= 0) {
83                 now_us = g_source_get_time(source);
84
85                 if (fsource->due_us == 0) {
86                         /* First-time initialization of the expiration time */
87                         fsource->due_us = now_us + fsource->timeout_us;
88                 }
89                 remaining_ms = (MAX(0, fsource->due_us - now_us) + 999) / 1000;
90         } else {
91                 remaining_ms = -1;
92         }
93         *timeout = remaining_ms;
94
95         return (remaining_ms == 0);
96 }
97
98 /** FD event source check() method.
99  * This is called after poll() returns to check whether an event fired.
100  */
101 static gboolean fd_source_check(GSource *source)
102 {
103         struct fd_source *fsource;
104         unsigned int revents;
105
106         fsource = (struct fd_source *)source;
107         revents = fsource->pollfd.revents;
108
109         return (revents != 0 || (fsource->timeout_us >= 0
110                         && fsource->due_us <= g_source_get_time(source)));
111 }
112
113 /** FD event source dispatch() method.
114  * This is called if either prepare() or check() returned TRUE.
115  */
116 static gboolean fd_source_dispatch(GSource *source,
117                 GSourceFunc callback, void *user_data)
118 {
119         struct fd_source *fsource;
120         unsigned int revents;
121         gboolean keep;
122
123         fsource = (struct fd_source *)source;
124         revents = fsource->pollfd.revents;
125
126         if (!callback) {
127                 sr_err("Callback not set, cannot dispatch event.");
128                 return G_SOURCE_REMOVE;
129         }
130         keep = (*(sr_receive_data_callback)callback)
131                         (fsource->pollfd.fd, revents, user_data);
132
133         if (fsource->timeout_us >= 0 && G_LIKELY(keep)
134                         && G_LIKELY(!g_source_is_destroyed(source)))
135                 fsource->due_us = g_source_get_time(source)
136                                 + fsource->timeout_us;
137         return keep;
138 }
139
140 /** FD event source finalize() method.
141  */
142 static void fd_source_finalize(GSource *source)
143 {
144         struct fd_source *fsource;
145
146         fsource = (struct fd_source *)source;
147
148         sr_dbg("%s: key %p", __func__, fsource->key);
149
150         sr_session_source_destroyed(fsource->session, fsource->key, source);
151 }
152
153 /** Create an event source for I/O on a file descriptor.
154  *
155  * In order to maintain API compatibility, this event source also doubles
156  * as a timer event source.
157  *
158  * @param session The session the event source belongs to.
159  * @param key The key used to identify this source.
160  * @param fd The file descriptor or HANDLE.
161  * @param timeout_ms The timeout interval in ms, or -1 to wait indefinitely.
162  * @return A new event source object, or NULL on failure.
163  */
164 static GSource *fd_source_new(struct sr_session *session, void *key,
165                 gintptr fd, int events, int timeout_ms)
166 {
167         static GSourceFuncs fd_source_funcs = {
168                 .prepare  = &fd_source_prepare,
169                 .check    = &fd_source_check,
170                 .dispatch = &fd_source_dispatch,
171                 .finalize = &fd_source_finalize
172         };
173         GSource *source;
174         struct fd_source *fsource;
175
176         source = g_source_new(&fd_source_funcs, sizeof(struct fd_source));
177         fsource = (struct fd_source *)source;
178
179         g_source_set_name(source, (fd < 0) ? "timer" : "fd");
180
181         if (timeout_ms >= 0) {
182                 fsource->timeout_us = 1000 * (int64_t)timeout_ms;
183                 fsource->due_us = 0;
184         } else {
185                 fsource->timeout_us = -1;
186                 fsource->due_us = INT64_MAX;
187         }
188         fsource->session = session;
189         fsource->key = key;
190
191         fsource->pollfd.fd = fd;
192         fsource->pollfd.events = events;
193         fsource->pollfd.revents = 0;
194
195         if (fd >= 0)
196                 g_source_add_poll(source, &fsource->pollfd);
197
198         return source;
199 }
200
201 /**
202  * Create a new session.
203  *
204  * @param ctx         The context in which to create the new session.
205  * @param new_session This will contain a pointer to the newly created
206  *                    session if the return value is SR_OK, otherwise the value
207  *                    is undefined and should not be used. Must not be NULL.
208  *
209  * @retval SR_OK Success.
210  * @retval SR_ERR_ARG Invalid argument.
211  *
212  * @since 0.4.0
213  */
214 SR_API int sr_session_new(struct sr_context *ctx,
215                 struct sr_session **new_session)
216 {
217         struct sr_session *session;
218
219         if (!new_session)
220                 return SR_ERR_ARG;
221
222         session = g_malloc0(sizeof(struct sr_session));
223
224         session->ctx = ctx;
225
226         g_mutex_init(&session->main_mutex);
227
228         /* To maintain API compatibility, we need a lookup table
229          * which maps poll_object IDs to GSource* pointers.
230          */
231         session->event_sources = g_hash_table_new(NULL, NULL);
232
233         *new_session = session;
234
235         return SR_OK;
236 }
237
238 /**
239  * Destroy a session.
240  * This frees up all memory used by the session.
241  *
242  * @param session The session to destroy. Must not be NULL.
243  *
244  * @retval SR_OK Success.
245  * @retval SR_ERR_ARG Invalid session passed.
246  *
247  * @since 0.4.0
248  */
249 SR_API int sr_session_destroy(struct sr_session *session)
250 {
251         if (!session) {
252                 sr_err("%s: session was NULL", __func__);
253                 return SR_ERR_ARG;
254         }
255
256         sr_session_dev_remove_all(session);
257         g_slist_free_full(session->owned_devs, (GDestroyNotify)sr_dev_inst_free);
258
259         sr_session_datafeed_callback_remove_all(session);
260
261         g_hash_table_unref(session->event_sources);
262
263         g_mutex_clear(&session->main_mutex);
264
265         g_free(session);
266
267         return SR_OK;
268 }
269
270 /**
271  * Remove all the devices from a session.
272  *
273  * The session itself (i.e., the struct sr_session) is not free'd and still
274  * exists after this function returns.
275  *
276  * @param session The session to use. Must not be NULL.
277  *
278  * @retval SR_OK Success.
279  * @retval SR_ERR_BUG Invalid session passed.
280  *
281  * @since 0.4.0
282  */
283 SR_API int sr_session_dev_remove_all(struct sr_session *session)
284 {
285         struct sr_dev_inst *sdi;
286         GSList *l;
287
288         if (!session) {
289                 sr_err("%s: session was NULL", __func__);
290                 return SR_ERR_ARG;
291         }
292
293         for (l = session->devs; l; l = l->next) {
294                 sdi = (struct sr_dev_inst *) l->data;
295                 sdi->session = NULL;
296         }
297
298         g_slist_free(session->devs);
299         session->devs = NULL;
300
301         return SR_OK;
302 }
303
304 /**
305  * Add a device instance to a session.
306  *
307  * @param session The session to add to. Must not be NULL.
308  * @param sdi The device instance to add to a session. Must not
309  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
310  *            not be NULL.
311  *
312  * @retval SR_OK Success.
313  * @retval SR_ERR_ARG Invalid argument.
314  *
315  * @since 0.4.0
316  */
317 SR_API int sr_session_dev_add(struct sr_session *session,
318                 struct sr_dev_inst *sdi)
319 {
320         int ret;
321
322         if (!sdi) {
323                 sr_err("%s: sdi was NULL", __func__);
324                 return SR_ERR_ARG;
325         }
326
327         if (!session) {
328                 sr_err("%s: session was NULL", __func__);
329                 return SR_ERR_ARG;
330         }
331
332         /* If sdi->session is not NULL, the device is already in this or
333          * another session. */
334         if (sdi->session) {
335                 sr_err("%s: already assigned to session", __func__);
336                 return SR_ERR_ARG;
337         }
338
339         /* If sdi->driver is NULL, this is a virtual device. */
340         if (!sdi->driver) {
341                 /* Just add the device, don't run dev_open(). */
342                 session->devs = g_slist_append(session->devs, sdi);
343                 sdi->session = session;
344                 return SR_OK;
345         }
346
347         /* sdi->driver is non-NULL (i.e. we have a real device). */
348         if (!sdi->driver->dev_open) {
349                 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
350                 return SR_ERR_BUG;
351         }
352
353         session->devs = g_slist_append(session->devs, sdi);
354         sdi->session = session;
355
356         /* TODO: This is invalid if the session runs in a different thread.
357          * The usage semantics and restrictions need to be documented.
358          */
359         if (session->running) {
360                 /* Adding a device to a running session. Commit settings
361                  * and start acquisition on that device now. */
362                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
363                         sr_err("Failed to commit device settings before "
364                                "starting acquisition in running session (%s)",
365                                sr_strerror(ret));
366                         return ret;
367                 }
368                 if ((ret = sdi->driver->dev_acquisition_start(sdi)) != SR_OK) {
369                         sr_err("Failed to start acquisition of device in "
370                                "running session (%s)", sr_strerror(ret));
371                         return ret;
372                 }
373         }
374
375         return SR_OK;
376 }
377
378 /**
379  * List all device instances attached to a session.
380  *
381  * @param session The session to use. Must not be NULL.
382  * @param devlist A pointer where the device instance list will be
383  *                stored on return. If no devices are in the session,
384  *                this will be NULL. Each element in the list points
385  *                to a struct sr_dev_inst *.
386  *                The list must be freed by the caller, but not the
387  *                elements pointed to.
388  *
389  * @retval SR_OK Success.
390  * @retval SR_ERR_ARG Invalid argument.
391  *
392  * @since 0.4.0
393  */
394 SR_API int sr_session_dev_list(struct sr_session *session, GSList **devlist)
395 {
396         if (!session)
397                 return SR_ERR_ARG;
398
399         if (!devlist)
400                 return SR_ERR_ARG;
401
402         *devlist = g_slist_copy(session->devs);
403
404         return SR_OK;
405 }
406
407 /**
408  * Remove a device instance from a session.
409  *
410  * @param session The session to remove from. Must not be NULL.
411  * @param sdi The device instance to remove from a session. Must not
412  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
413  *            not be NULL.
414  *
415  * @retval SR_OK Success.
416  * @retval SR_ERR_ARG Invalid argument.
417  *
418  * @since 0.4.0
419  */
420 SR_API int sr_session_dev_remove(struct sr_session *session,
421                 struct sr_dev_inst *sdi)
422 {
423         if (!sdi) {
424                 sr_err("%s: sdi was NULL", __func__);
425                 return SR_ERR_ARG;
426         }
427
428         if (!session) {
429                 sr_err("%s: session was NULL", __func__);
430                 return SR_ERR_ARG;
431         }
432
433         /* If sdi->session is not session, the device is not in this
434          * session. */
435         if (sdi->session != session) {
436                 sr_err("%s: not assigned to this session", __func__);
437                 return SR_ERR_ARG;
438         }
439
440         session->devs = g_slist_remove(session->devs, sdi);
441         sdi->session = NULL;
442
443         return SR_OK;
444 }
445
446 /**
447  * Remove all datafeed callbacks in a session.
448  *
449  * @param session The session to use. Must not be NULL.
450  *
451  * @retval SR_OK Success.
452  * @retval SR_ERR_ARG Invalid session passed.
453  *
454  * @since 0.4.0
455  */
456 SR_API int sr_session_datafeed_callback_remove_all(struct sr_session *session)
457 {
458         if (!session) {
459                 sr_err("%s: session was NULL", __func__);
460                 return SR_ERR_ARG;
461         }
462
463         g_slist_free_full(session->datafeed_callbacks, g_free);
464         session->datafeed_callbacks = NULL;
465
466         return SR_OK;
467 }
468
469 /**
470  * Add a datafeed callback to a session.
471  *
472  * @param session The session to use. Must not be NULL.
473  * @param cb Function to call when a chunk of data is received.
474  *           Must not be NULL.
475  * @param cb_data Opaque pointer passed in by the caller.
476  *
477  * @retval SR_OK Success.
478  * @retval SR_ERR_BUG No session exists.
479  *
480  * @since 0.3.0
481  */
482 SR_API int sr_session_datafeed_callback_add(struct sr_session *session,
483                 sr_datafeed_callback cb, void *cb_data)
484 {
485         struct datafeed_callback *cb_struct;
486
487         if (!session) {
488                 sr_err("%s: session was NULL", __func__);
489                 return SR_ERR_BUG;
490         }
491
492         if (!cb) {
493                 sr_err("%s: cb was NULL", __func__);
494                 return SR_ERR_ARG;
495         }
496
497         cb_struct = g_malloc0(sizeof(struct datafeed_callback));
498         cb_struct->cb = cb;
499         cb_struct->cb_data = cb_data;
500
501         session->datafeed_callbacks =
502             g_slist_append(session->datafeed_callbacks, cb_struct);
503
504         return SR_OK;
505 }
506
507 /**
508  * Get the trigger assigned to this session.
509  *
510  * @param session The session to use.
511  *
512  * @retval NULL Invalid (NULL) session was passed to the function.
513  * @retval other The trigger assigned to this session (can be NULL).
514  *
515  * @since 0.4.0
516  */
517 SR_API struct sr_trigger *sr_session_trigger_get(struct sr_session *session)
518 {
519         if (!session)
520                 return NULL;
521
522         return session->trigger;
523 }
524
525 /**
526  * Set the trigger of this session.
527  *
528  * @param session The session to use. Must not be NULL.
529  * @param trig The trigger to assign to this session. Can be NULL.
530  *
531  * @retval SR_OK Success.
532  * @retval SR_ERR_ARG Invalid argument.
533  *
534  * @since 0.4.0
535  */
536 SR_API int sr_session_trigger_set(struct sr_session *session, struct sr_trigger *trig)
537 {
538         if (!session)
539                 return SR_ERR_ARG;
540
541         session->trigger = trig;
542
543         return SR_OK;
544 }
545
546 static int verify_trigger(struct sr_trigger *trigger)
547 {
548         struct sr_trigger_stage *stage;
549         struct sr_trigger_match *match;
550         GSList *l, *m;
551
552         if (!trigger->stages) {
553                 sr_err("No trigger stages defined.");
554                 return SR_ERR;
555         }
556
557         sr_spew("Checking trigger:");
558         for (l = trigger->stages; l; l = l->next) {
559                 stage = l->data;
560                 if (!stage->matches) {
561                         sr_err("Stage %d has no matches defined.", stage->stage);
562                         return SR_ERR;
563                 }
564                 for (m = stage->matches; m; m = m->next) {
565                         match = m->data;
566                         if (!match->channel) {
567                                 sr_err("Stage %d match has no channel.", stage->stage);
568                                 return SR_ERR;
569                         }
570                         if (!match->match) {
571                                 sr_err("Stage %d match is not defined.", stage->stage);
572                                 return SR_ERR;
573                         }
574                         sr_spew("Stage %d match on channel %s, match %d", stage->stage,
575                                         match->channel->name, match->match);
576                 }
577         }
578
579         return SR_OK;
580 }
581
582 /** Set up the main context the session will be executing in.
583  *
584  * Must be called just before the session starts, by the thread which
585  * will execute the session main loop. Once acquired, the main context
586  * pointer is immutable for the duration of the session run.
587  */
588 static int set_main_context(struct sr_session *session)
589 {
590         GMainContext *main_context;
591
592         g_mutex_lock(&session->main_mutex);
593
594         /* May happen if sr_session_start() is called a second time
595          * while the session is still running.
596          */
597         if (session->main_context) {
598                 sr_err("Main context already set.");
599
600                 g_mutex_unlock(&session->main_mutex);
601                 return SR_ERR;
602         }
603         main_context = g_main_context_ref_thread_default();
604         /*
605          * Try to use an existing main context if possible, but only if we
606          * can make it owned by the current thread. Otherwise, create our
607          * own main context so that event source callbacks can execute in
608          * the session thread.
609          */
610         if (g_main_context_acquire(main_context)) {
611                 g_main_context_release(main_context);
612
613                 sr_dbg("Using thread-default main context.");
614         } else {
615                 g_main_context_unref(main_context);
616
617                 sr_dbg("Creating our own main context.");
618                 main_context = g_main_context_new();
619         }
620         session->main_context = main_context;
621
622         g_mutex_unlock(&session->main_mutex);
623
624         return SR_OK;
625 }
626
627 /** Unset the main context used for the current session run.
628  *
629  * Must be called right after stopping the session. Note that if the
630  * session is stopped asynchronously, the main loop may still be running
631  * after the main context has been unset. This is OK as long as no new
632  * event sources are created -- the main loop holds its own reference
633  * to the main context.
634  */
635 static int unset_main_context(struct sr_session *session)
636 {
637         int ret;
638
639         g_mutex_lock(&session->main_mutex);
640
641         if (session->main_context) {
642                 g_main_context_unref(session->main_context);
643                 session->main_context = NULL;
644                 ret = SR_OK;
645         } else {
646                 /* May happen if the set/unset calls are not matched.
647                  */
648                 sr_err("No main context to unset.");
649                 ret = SR_ERR;
650         }
651         g_mutex_unlock(&session->main_mutex);
652
653         return ret;
654 }
655
656 static unsigned int session_source_attach(struct sr_session *session,
657                 GSource *source)
658 {
659         unsigned int id = 0;
660
661         g_mutex_lock(&session->main_mutex);
662
663         if (session->main_context)
664                 id = g_source_attach(source, session->main_context);
665         else
666                 sr_err("Cannot add event source without main context.");
667
668         g_mutex_unlock(&session->main_mutex);
669
670         return id;
671 }
672
673 /* Idle handler; invoked when the number of registered event sources
674  * for a running session drops to zero.
675  */
676 static gboolean delayed_stop_check(void *data)
677 {
678         struct sr_session *session;
679
680         session = data;
681         session->stop_check_id = 0;
682
683         /* Session already ended? */
684         if (!session->running)
685                 return G_SOURCE_REMOVE;
686
687         /* New event sources may have been installed in the meantime. */
688         if (g_hash_table_size(session->event_sources) != 0)
689                 return G_SOURCE_REMOVE;
690
691         session->running = FALSE;
692         unset_main_context(session);
693
694         sr_info("Stopped.");
695
696         /* This indicates a bug in user code, since it is not valid to
697          * restart or destroy a session while it may still be running.
698          */
699         if (!session->main_loop && !session->stopped_callback) {
700                 sr_err("BUG: Session stop left unhandled.");
701                 return G_SOURCE_REMOVE;
702         }
703         if (session->main_loop)
704                 g_main_loop_quit(session->main_loop);
705
706         if (session->stopped_callback)
707                 (*session->stopped_callback)(session->stopped_cb_data);
708
709         return G_SOURCE_REMOVE;
710 }
711
712 static int stop_check_later(struct sr_session *session)
713 {
714         GSource *source;
715         unsigned int source_id;
716
717         if (session->stop_check_id != 0)
718                 return SR_OK; /* idle handler already installed */
719
720         source = g_idle_source_new();
721         g_source_set_callback(source, &delayed_stop_check, session, NULL);
722
723         source_id = session_source_attach(session, source);
724         session->stop_check_id = source_id;
725
726         g_source_unref(source);
727
728         return (source_id != 0) ? SR_OK : SR_ERR;
729 }
730
731 /**
732  * Start a session.
733  *
734  * When this function returns with a status code indicating success, the
735  * session is running. Use sr_session_stopped_callback_set() to receive
736  * notification upon completion, or call sr_session_run() to block until
737  * the session stops.
738  *
739  * Session events will be processed in the context of the current thread.
740  * If a thread-default GLib main context has been set, and is not owned by
741  * any other thread, it will be used. Otherwise, libsigrok will create its
742  * own main context for the current thread.
743  *
744  * @param session The session to use. Must not be NULL.
745  *
746  * @retval SR_OK Success.
747  * @retval SR_ERR_ARG Invalid session passed.
748  * @retval SR_ERR Other error.
749  *
750  * @since 0.4.0
751  */
752 SR_API int sr_session_start(struct sr_session *session)
753 {
754         struct sr_dev_inst *sdi;
755         struct sr_channel *ch;
756         GSList *l, *c, *lend;
757         int ret;
758
759         if (!session) {
760                 sr_err("%s: session was NULL", __func__);
761                 return SR_ERR_ARG;
762         }
763
764         if (!session->devs) {
765                 sr_err("%s: session->devs was NULL; a session "
766                        "cannot be started without devices.", __func__);
767                 return SR_ERR_ARG;
768         }
769
770         if (session->running) {
771                 sr_err("Cannot (re-)start session while it is still running.");
772                 return SR_ERR;
773         }
774
775         if (session->trigger) {
776                 ret = verify_trigger(session->trigger);
777                 if (ret != SR_OK)
778                         return ret;
779         }
780
781         /* Check enabled channels and commit settings of all devices. */
782         for (l = session->devs; l; l = l->next) {
783                 sdi = l->data;
784                 for (c = sdi->channels; c; c = c->next) {
785                         ch = c->data;
786                         if (ch->enabled)
787                                 break;
788                 }
789                 if (!c) {
790                         sr_err("%s device %s has no enabled channels.",
791                                 sdi->driver->name, sdi->connection_id);
792                         return SR_ERR;
793                 }
794
795                 ret = sr_config_commit(sdi);
796                 if (ret != SR_OK) {
797                         sr_err("Failed to commit %s device %s settings "
798                                 "before starting acquisition.",
799                                 sdi->driver->name, sdi->connection_id);
800                         return ret;
801                 }
802         }
803
804         ret = set_main_context(session);
805         if (ret != SR_OK)
806                 return ret;
807
808         sr_info("Starting.");
809
810         session->running = TRUE;
811
812         /* Have all devices start acquisition. */
813         for (l = session->devs; l; l = l->next) {
814                 sdi = l->data;
815                 ret = sdi->driver->dev_acquisition_start(sdi);
816                 if (ret != SR_OK) {
817                         sr_err("Could not start %s device %s acquisition.",
818                                 sdi->driver->name, sdi->connection_id);
819                         break;
820                 }
821         }
822
823         if (ret != SR_OK) {
824                 /* If there are multiple devices, some of them may already have
825                  * started successfully. Stop them now before returning. */
826                 lend = l->next;
827                 for (l = session->devs; l != lend; l = l->next) {
828                         sdi = l->data;
829                         if (sdi->driver->dev_acquisition_stop)
830                                 sdi->driver->dev_acquisition_stop(sdi);
831                 }
832                 /* TODO: Handle delayed stops. Need to iterate the event
833                  * sources... */
834                 session->running = FALSE;
835
836                 unset_main_context(session);
837                 return ret;
838         }
839
840         if (g_hash_table_size(session->event_sources) == 0)
841                 stop_check_later(session);
842
843         return SR_OK;
844 }
845
846 /**
847  * Block until the running session stops.
848  *
849  * This is a convenience function which creates a GLib main loop and runs
850  * it to process session events until the session stops.
851  *
852  * Instead of using this function, applications may run their own GLib main
853  * loop, and use sr_session_stopped_callback_set() to receive notification
854  * when the session finished running.
855  *
856  * @param session The session to use. Must not be NULL.
857  *
858  * @retval SR_OK Success.
859  * @retval SR_ERR_ARG Invalid session passed.
860  * @retval SR_ERR Other error.
861  *
862  * @since 0.4.0
863  */
864 SR_API int sr_session_run(struct sr_session *session)
865 {
866         if (!session) {
867                 sr_err("%s: session was NULL", __func__);
868                 return SR_ERR_ARG;
869         }
870         if (!session->running) {
871                 sr_err("No session running.");
872                 return SR_ERR;
873         }
874         if (session->main_loop) {
875                 sr_err("Main loop already created.");
876                 return SR_ERR;
877         }
878
879         g_mutex_lock(&session->main_mutex);
880
881         if (!session->main_context) {
882                 sr_err("Cannot run without main context.");
883                 g_mutex_unlock(&session->main_mutex);
884                 return SR_ERR;
885         }
886         session->main_loop = g_main_loop_new(session->main_context, FALSE);
887
888         g_mutex_unlock(&session->main_mutex);
889
890         g_main_loop_run(session->main_loop);
891
892         g_main_loop_unref(session->main_loop);
893         session->main_loop = NULL;
894
895         return SR_OK;
896 }
897
898 static gboolean session_stop_sync(void *user_data)
899 {
900         struct sr_session *session;
901         struct sr_dev_inst *sdi;
902         GSList *node;
903
904         session = user_data;
905
906         if (!session->running)
907                 return G_SOURCE_REMOVE;
908
909         sr_info("Stopping.");
910
911         for (node = session->devs; node; node = node->next) {
912                 sdi = node->data;
913                 if (sdi->driver && sdi->driver->dev_acquisition_stop)
914                         sdi->driver->dev_acquisition_stop(sdi);
915         }
916
917         return G_SOURCE_REMOVE;
918 }
919
920 /**
921  * Stop a session.
922  *
923  * This requests the drivers of each device participating in the session to
924  * abort the acquisition as soon as possible. Even after this function returns,
925  * event processing still continues until all devices have actually stopped.
926  *
927  * Use sr_session_stopped_callback_set() to receive notification when the event
928  * processing finished.
929  *
930  * This function is reentrant. That is, it may be called from a different
931  * thread than the one executing the session, as long as it can be ensured
932  * that the session object is valid.
933  *
934  * If the session is not running, sr_session_stop() silently does nothing.
935  *
936  * @param session The session to use. Must not be NULL.
937  *
938  * @retval SR_OK Success.
939  * @retval SR_ERR_ARG Invalid session passed.
940  *
941  * @since 0.4.0
942  */
943 SR_API int sr_session_stop(struct sr_session *session)
944 {
945         GMainContext *main_context;
946
947         if (!session) {
948                 sr_err("%s: session was NULL", __func__);
949                 return SR_ERR_ARG;
950         }
951
952         g_mutex_lock(&session->main_mutex);
953
954         main_context = (session->main_context)
955                 ? g_main_context_ref(session->main_context)
956                 : NULL;
957
958         g_mutex_unlock(&session->main_mutex);
959
960         if (!main_context) {
961                 sr_dbg("No main context set; already stopped?");
962                 /* Not an error; as it would be racy. */
963                 return SR_OK;
964         }
965         g_main_context_invoke(main_context, &session_stop_sync, session);
966         g_main_context_unref(main_context);
967
968         return SR_OK;
969 }
970
971 /**
972  * Return whether the session is currently running.
973  *
974  * Note that this function should be called from the same thread
975  * the session was started in.
976  *
977  * @param session The session to use. Must not be NULL.
978  *
979  * @retval TRUE Session is running.
980  * @retval FALSE Session is not running.
981  * @retval SR_ERR_ARG Invalid session passed.
982  *
983  * @since 0.4.0
984  */
985 SR_API int sr_session_is_running(struct sr_session *session)
986 {
987         if (!session) {
988                 sr_err("%s: session was NULL", __func__);
989                 return SR_ERR_ARG;
990         }
991         return session->running;
992 }
993
994 /**
995  * Set the callback to be invoked after a session stopped running.
996  *
997  * Install a callback to receive notification when a session run stopped.
998  * This can be used to integrate session execution with an existing main
999  * loop, without having to block in sr_session_run().
1000  *
1001  * Note that the callback will be invoked in the context of the thread
1002  * that calls sr_session_start().
1003  *
1004  * @param session The session to use. Must not be NULL.
1005  * @param cb The callback to invoke on session stop. May be NULL to unset.
1006  * @param cb_data User data pointer to be passed to the callback.
1007  *
1008  * @retval SR_OK Success.
1009  * @retval SR_ERR_ARG Invalid session passed.
1010  *
1011  * @since 0.4.0
1012  */
1013 SR_API int sr_session_stopped_callback_set(struct sr_session *session,
1014                 sr_session_stopped_callback cb, void *cb_data)
1015 {
1016         if (!session) {
1017                 sr_err("%s: session was NULL", __func__);
1018                 return SR_ERR_ARG;
1019         }
1020         session->stopped_callback = cb;
1021         session->stopped_cb_data = cb_data;
1022
1023         return SR_OK;
1024 }
1025
1026 /**
1027  * Debug helper.
1028  *
1029  * @param packet The packet to show debugging information for.
1030  */
1031 static void datafeed_dump(const struct sr_datafeed_packet *packet)
1032 {
1033         const struct sr_datafeed_logic *logic;
1034         const struct sr_datafeed_analog_old *analog_old;
1035         const struct sr_datafeed_analog *analog;
1036
1037         /* Please use the same order as in libsigrok.h. */
1038         switch (packet->type) {
1039         case SR_DF_HEADER:
1040                 sr_dbg("bus: Received SR_DF_HEADER packet.");
1041                 break;
1042         case SR_DF_END:
1043                 sr_dbg("bus: Received SR_DF_END packet.");
1044                 break;
1045         case SR_DF_META:
1046                 sr_dbg("bus: Received SR_DF_META packet.");
1047                 break;
1048         case SR_DF_TRIGGER:
1049                 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
1050                 break;
1051         case SR_DF_LOGIC:
1052                 logic = packet->payload;
1053                 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes, "
1054                        "unitsize = %d).", logic->length, logic->unitsize);
1055                 break;
1056         case SR_DF_ANALOG_OLD:
1057                 analog_old = packet->payload;
1058                 sr_dbg("bus: Received SR_DF_ANALOG_OLD packet (%d samples).",
1059                        analog_old->num_samples);
1060                 break;
1061         case SR_DF_FRAME_BEGIN:
1062                 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
1063                 break;
1064         case SR_DF_FRAME_END:
1065                 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
1066                 break;
1067         case SR_DF_ANALOG:
1068                 analog = packet->payload;
1069                 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
1070                        analog->num_samples);
1071                 break;
1072         default:
1073                 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
1074                 break;
1075         }
1076 }
1077
1078 /**
1079  * Send a packet to whatever is listening on the datafeed bus.
1080  *
1081  * Hardware drivers use this to send a data packet to the frontend.
1082  *
1083  * @param sdi TODO.
1084  * @param packet The datafeed packet to send to the session bus.
1085  *
1086  * @retval SR_OK Success.
1087  * @retval SR_ERR_ARG Invalid argument.
1088  *
1089  * @private
1090  */
1091 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
1092                 const struct sr_datafeed_packet *packet)
1093 {
1094         GSList *l;
1095         struct datafeed_callback *cb_struct;
1096         struct sr_datafeed_packet *packet_in, *packet_out;
1097         struct sr_transform *t;
1098         int ret;
1099
1100         if (!sdi) {
1101                 sr_err("%s: sdi was NULL", __func__);
1102                 return SR_ERR_ARG;
1103         }
1104
1105         if (!packet) {
1106                 sr_err("%s: packet was NULL", __func__);
1107                 return SR_ERR_ARG;
1108         }
1109
1110         if (!sdi->session) {
1111                 sr_err("%s: session was NULL", __func__);
1112                 return SR_ERR_BUG;
1113         }
1114
1115         if (packet->type == SR_DF_ANALOG_OLD) {
1116                 /* Convert to SR_DF_ANALOG. */
1117                 const struct sr_datafeed_analog_old *analog_old = packet->payload;
1118                 struct sr_analog_encoding encoding;
1119                 struct sr_analog_meaning meaning;
1120                 struct sr_analog_spec spec;
1121                 struct sr_datafeed_analog analog;
1122                 struct sr_datafeed_packet new_packet;
1123                 new_packet.type = SR_DF_ANALOG;
1124                 new_packet.payload = &analog;
1125                 analog.data = analog_old->data;
1126                 analog.num_samples = analog_old->num_samples;
1127                 analog.encoding = &encoding;
1128                 analog.meaning = &meaning;
1129                 analog.spec = &spec;
1130                 encoding.unitsize = sizeof(float);
1131                 encoding.is_signed = TRUE;
1132                 encoding.is_float = TRUE;
1133 #ifdef WORDS_BIGENDIAN
1134                 encoding.is_bigendian = TRUE;
1135 #else
1136                 encoding.is_bigendian = FALSE;
1137 #endif
1138                 encoding.digits = 0;
1139                 encoding.is_digits_decimal = FALSE;
1140                 encoding.scale.p = 1;
1141                 encoding.scale.q = 1;
1142                 encoding.offset.p = 0;
1143                 encoding.offset.q = 1;
1144                 meaning.mq = analog_old->mq;
1145                 meaning.unit = analog_old->unit;
1146                 meaning.mqflags = analog_old->mqflags;
1147                 meaning.channels = analog_old->channels;
1148                 spec.spec_digits = 0;
1149                 return sr_session_send(sdi, &new_packet);
1150         }
1151
1152         /*
1153          * Pass the packet to the first transform module. If that returns
1154          * another packet (instead of NULL), pass that packet to the next
1155          * transform module in the list, and so on.
1156          */
1157         packet_in = (struct sr_datafeed_packet *)packet;
1158         for (l = sdi->session->transforms; l; l = l->next) {
1159                 t = l->data;
1160                 sr_spew("Running transform module '%s'.", t->module->id);
1161                 ret = t->module->receive(t, packet_in, &packet_out);
1162                 if (ret < 0) {
1163                         sr_err("Error while running transform module: %d.", ret);
1164                         return SR_ERR;
1165                 }
1166                 if (!packet_out) {
1167                         /*
1168                          * If any of the transforms don't return an output
1169                          * packet, abort.
1170                          */
1171                         sr_spew("Transform module didn't return a packet, aborting.");
1172                         return SR_OK;
1173                 } else {
1174                         /*
1175                          * Use this transform module's output packet as input
1176                          * for the next transform module.
1177                          */
1178                         packet_in = packet_out;
1179                 }
1180         }
1181         packet = packet_in;
1182
1183         /*
1184          * If the last transform did output a packet, pass it to all datafeed
1185          * callbacks.
1186          */
1187         for (l = sdi->session->datafeed_callbacks; l; l = l->next) {
1188                 if (sr_log_loglevel_get() >= SR_LOG_DBG)
1189                         datafeed_dump(packet);
1190                 cb_struct = l->data;
1191                 cb_struct->cb(sdi, packet, cb_struct->cb_data);
1192         }
1193
1194         return SR_OK;
1195 }
1196
1197 /**
1198  * Add an event source for a file descriptor.
1199  *
1200  * @param session The session to use. Must not be NULL.
1201  * @param key The key which identifies the event source.
1202  * @param source An event source object. Must not be NULL.
1203  *
1204  * @retval SR_OK Success.
1205  * @retval SR_ERR_ARG Invalid argument.
1206  * @retval SR_ERR_BUG Event source with @a key already installed.
1207  * @retval SR_ERR Other error.
1208  *
1209  * @private
1210  */
1211 SR_PRIV int sr_session_source_add_internal(struct sr_session *session,
1212                 void *key, GSource *source)
1213 {
1214         /*
1215          * This must not ever happen, since the source has already been
1216          * created and its finalize() method will remove the key for the
1217          * already installed source. (Well it would, if we did not have
1218          * another sanity check there.)
1219          */
1220         if (g_hash_table_contains(session->event_sources, key)) {
1221                 sr_err("Event source with key %p already exists.", key);
1222                 return SR_ERR_BUG;
1223         }
1224         g_hash_table_insert(session->event_sources, key, source);
1225
1226         if (session_source_attach(session, source) == 0)
1227                 return SR_ERR;
1228
1229         return SR_OK;
1230 }
1231
1232 SR_PRIV int sr_session_fd_source_add(struct sr_session *session,
1233                 void *key, gintptr fd, int events, int timeout,
1234                 sr_receive_data_callback cb, void *cb_data)
1235 {
1236         GSource *source;
1237         int ret;
1238
1239         source = fd_source_new(session, key, fd, events, timeout);
1240         if (!source)
1241                 return SR_ERR;
1242
1243         g_source_set_callback(source, (GSourceFunc)cb, cb_data, NULL);
1244
1245         ret = sr_session_source_add_internal(session, key, source);
1246         g_source_unref(source);
1247
1248         return ret;
1249 }
1250
1251 /**
1252  * Add an event source for a file descriptor.
1253  *
1254  * @param session The session to use. Must not be NULL.
1255  * @param fd The file descriptor, or a negative value to create a timer source.
1256  * @param events Events to check for.
1257  * @param timeout Max time in ms to wait before the callback is called,
1258  *                or -1 to wait indefinitely.
1259  * @param cb Callback function to add. Must not be NULL.
1260  * @param cb_data Data for the callback function. Can be NULL.
1261  *
1262  * @retval SR_OK Success.
1263  * @retval SR_ERR_ARG Invalid argument.
1264  *
1265  * @since 0.3.0
1266  * @private
1267  */
1268 SR_PRIV int sr_session_source_add(struct sr_session *session, int fd,
1269                 int events, int timeout, sr_receive_data_callback cb, void *cb_data)
1270 {
1271         if (fd < 0 && timeout < 0) {
1272                 sr_err("Cannot create timer source without timeout.");
1273                 return SR_ERR_ARG;
1274         }
1275         return sr_session_fd_source_add(session, GINT_TO_POINTER(fd),
1276                         fd, events, timeout, cb, cb_data);
1277 }
1278
1279 /**
1280  * Add an event source for a GPollFD.
1281  *
1282  * @param session The session to use. Must not be NULL.
1283  * @param pollfd The GPollFD. Must not be NULL.
1284  * @param timeout Max time in ms to wait before the callback is called,
1285  *                or -1 to wait indefinitely.
1286  * @param cb Callback function to add. Must not be NULL.
1287  * @param cb_data Data for the callback function. Can be NULL.
1288  *
1289  * @retval SR_OK Success.
1290  * @retval SR_ERR_ARG Invalid argument.
1291  *
1292  * @since 0.3.0
1293  * @private
1294  */
1295 SR_PRIV int sr_session_source_add_pollfd(struct sr_session *session,
1296                 GPollFD *pollfd, int timeout, sr_receive_data_callback cb,
1297                 void *cb_data)
1298 {
1299         if (!pollfd) {
1300                 sr_err("%s: pollfd was NULL", __func__);
1301                 return SR_ERR_ARG;
1302         }
1303         return sr_session_fd_source_add(session, pollfd, pollfd->fd,
1304                         pollfd->events, timeout, cb, cb_data);
1305 }
1306
1307 /**
1308  * Add an event source for a GIOChannel.
1309  *
1310  * @param session The session to use. Must not be NULL.
1311  * @param channel The GIOChannel.
1312  * @param events Events to poll on.
1313  * @param timeout Max time in ms to wait before the callback is called,
1314  *                or -1 to wait indefinitely.
1315  * @param cb Callback function to add. Must not be NULL.
1316  * @param cb_data Data for the callback function. Can be NULL.
1317  *
1318  * @retval SR_OK Success.
1319  * @retval SR_ERR_ARG Invalid argument.
1320  *
1321  * @since 0.3.0
1322  * @private
1323  */
1324 SR_PRIV int sr_session_source_add_channel(struct sr_session *session,
1325                 GIOChannel *channel, int events, int timeout,
1326                 sr_receive_data_callback cb, void *cb_data)
1327 {
1328         GPollFD pollfd;
1329
1330         if (!channel) {
1331                 sr_err("%s: channel was NULL", __func__);
1332                 return SR_ERR_ARG;
1333         }
1334         /* We should be using g_io_create_watch(), but can't without
1335          * changing the driver API, as the callback signature is different.
1336          */
1337 #ifdef G_OS_WIN32
1338         g_io_channel_win32_make_pollfd(channel, events, &pollfd);
1339 #else
1340         pollfd.fd = g_io_channel_unix_get_fd(channel);
1341         pollfd.events = events;
1342 #endif
1343         return sr_session_fd_source_add(session, channel, pollfd.fd,
1344                         pollfd.events, timeout, cb, cb_data);
1345 }
1346
1347 /**
1348  * Remove the source identified by the specified poll object.
1349  *
1350  * @param session The session to use. Must not be NULL.
1351  * @param key The key by which the source is identified.
1352  *
1353  * @retval SR_OK Success
1354  * @retval SR_ERR_BUG No event source for poll_object found.
1355  *
1356  * @private
1357  */
1358 SR_PRIV int sr_session_source_remove_internal(struct sr_session *session,
1359                 void *key)
1360 {
1361         GSource *source;
1362
1363         source = g_hash_table_lookup(session->event_sources, key);
1364         /*
1365          * Trying to remove an already removed event source is problematic
1366          * since the poll_object handle may have been reused in the meantime.
1367          */
1368         if (!source) {
1369                 sr_warn("Cannot remove non-existing event source %p.", key);
1370                 return SR_ERR_BUG;
1371         }
1372         g_source_destroy(source);
1373
1374         return SR_OK;
1375 }
1376
1377 /**
1378  * Remove the source belonging to the specified file descriptor.
1379  *
1380  * @param session The session to use. Must not be NULL.
1381  * @param fd The file descriptor for which the source should be removed.
1382  *
1383  * @retval SR_OK Success
1384  * @retval SR_ERR_ARG Invalid argument
1385  * @retval SR_ERR_BUG Internal error.
1386  *
1387  * @since 0.3.0
1388  * @private
1389  */
1390 SR_PRIV int sr_session_source_remove(struct sr_session *session, int fd)
1391 {
1392         return sr_session_source_remove_internal(session, GINT_TO_POINTER(fd));
1393 }
1394
1395 /**
1396  * Remove the source belonging to the specified poll descriptor.
1397  *
1398  * @param session The session to use. Must not be NULL.
1399  * @param pollfd The poll descriptor for which the source should be removed.
1400  *               Must not be NULL.
1401  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
1402  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
1403  *         internal errors.
1404  *
1405  * @since 0.2.0
1406  * @private
1407  */
1408 SR_PRIV int sr_session_source_remove_pollfd(struct sr_session *session,
1409                 GPollFD *pollfd)
1410 {
1411         if (!pollfd) {
1412                 sr_err("%s: pollfd was NULL", __func__);
1413                 return SR_ERR_ARG;
1414         }
1415         return sr_session_source_remove_internal(session, pollfd);
1416 }
1417
1418 /**
1419  * Remove the source belonging to the specified channel.
1420  *
1421  * @param session The session to use. Must not be NULL.
1422  * @param channel The channel for which the source should be removed.
1423  *                Must not be NULL.
1424  * @retval SR_OK Success.
1425  * @retval SR_ERR_ARG Invalid argument.
1426  * @return SR_ERR_BUG Internal error.
1427  *
1428  * @since 0.2.0
1429  * @private
1430  */
1431 SR_PRIV int sr_session_source_remove_channel(struct sr_session *session,
1432                 GIOChannel *channel)
1433 {
1434         if (!channel) {
1435                 sr_err("%s: channel was NULL", __func__);
1436                 return SR_ERR_ARG;
1437         }
1438         return sr_session_source_remove_internal(session, channel);
1439 }
1440
1441 /** Unregister an event source that has been destroyed.
1442  *
1443  * This is intended to be called from a source's finalize() method.
1444  *
1445  * @param session The session to use. Must not be NULL.
1446  * @param key The key used to identify @a source.
1447  * @param source The source object that was destroyed.
1448  *
1449  * @retval SR_OK Success.
1450  * @retval SR_ERR_BUG Event source for @a key does not match @a source.
1451  * @retval SR_ERR Other error.
1452  *
1453  * @private
1454  */
1455 SR_PRIV int sr_session_source_destroyed(struct sr_session *session,
1456                 void *key, GSource *source)
1457 {
1458         GSource *registered_source;
1459
1460         registered_source = g_hash_table_lookup(session->event_sources, key);
1461         /*
1462          * Trying to remove an already removed event source is problematic
1463          * since the poll_object handle may have been reused in the meantime.
1464          */
1465         if (!registered_source) {
1466                 sr_err("No event source for key %p found.", key);
1467                 return SR_ERR_BUG;
1468         }
1469         if (registered_source != source) {
1470                 sr_err("Event source for key %p does not match"
1471                         " destroyed source.", key);
1472                 return SR_ERR_BUG;
1473         }
1474         g_hash_table_remove(session->event_sources, key);
1475
1476         if (g_hash_table_size(session->event_sources) > 0)
1477                 return SR_OK;
1478
1479         /* If no event sources are left, consider the acquisition finished.
1480          * This is pretty crude, as it requires all event sources to be
1481          * registered via the libsigrok API.
1482          */
1483         return stop_check_later(session);
1484 }
1485
1486 static void copy_src(struct sr_config *src, struct sr_datafeed_meta *meta_copy)
1487 {
1488         g_variant_ref(src->data);
1489         meta_copy->config = g_slist_append(meta_copy->config,
1490                                            g_memdup(src, sizeof(struct sr_config)));
1491 }
1492
1493 SR_PRIV int sr_packet_copy(const struct sr_datafeed_packet *packet,
1494                 struct sr_datafeed_packet **copy)
1495 {
1496         const struct sr_datafeed_meta *meta;
1497         struct sr_datafeed_meta *meta_copy;
1498         const struct sr_datafeed_logic *logic;
1499         struct sr_datafeed_logic *logic_copy;
1500         const struct sr_datafeed_analog_old *analog_old;
1501         struct sr_datafeed_analog_old *analog_old_copy;
1502         const struct sr_datafeed_analog *analog;
1503         struct sr_datafeed_analog *analog_copy;
1504         uint8_t *payload;
1505
1506         *copy = g_malloc0(sizeof(struct sr_datafeed_packet));
1507         (*copy)->type = packet->type;
1508
1509         switch (packet->type) {
1510         case SR_DF_TRIGGER:
1511         case SR_DF_END:
1512                 /* No payload. */
1513                 break;
1514         case SR_DF_HEADER:
1515                 payload = g_malloc(sizeof(struct sr_datafeed_header));
1516                 memcpy(payload, packet->payload, sizeof(struct sr_datafeed_header));
1517                 (*copy)->payload = payload;
1518                 break;
1519         case SR_DF_META:
1520                 meta = packet->payload;
1521                 meta_copy = g_malloc0(sizeof(struct sr_datafeed_meta));
1522                 g_slist_foreach(meta->config, (GFunc)copy_src, meta_copy->config);
1523                 (*copy)->payload = meta_copy;
1524                 break;
1525         case SR_DF_LOGIC:
1526                 logic = packet->payload;
1527                 logic_copy = g_malloc(sizeof(*logic_copy));
1528                 logic_copy->length = logic->length;
1529                 logic_copy->unitsize = logic->unitsize;
1530                 memcpy(logic_copy->data, logic->data, logic->length * logic->unitsize);
1531                 (*copy)->payload = logic_copy;
1532                 break;
1533         case SR_DF_ANALOG_OLD:
1534                 analog_old = packet->payload;
1535                 analog_old_copy = g_malloc(sizeof(*analog_old_copy));
1536                 analog_old_copy->channels = g_slist_copy(analog_old->channels);
1537                 analog_old_copy->num_samples = analog_old->num_samples;
1538                 analog_old_copy->mq = analog_old->mq;
1539                 analog_old_copy->unit = analog_old->unit;
1540                 analog_old_copy->mqflags = analog_old->mqflags;
1541                 analog_old_copy->data = g_malloc(analog_old->num_samples * sizeof(float));
1542                 memcpy(analog_old_copy->data, analog_old->data,
1543                                 analog_old->num_samples * sizeof(float));
1544                 (*copy)->payload = analog_old_copy;
1545                 break;
1546         case SR_DF_ANALOG:
1547                 analog = packet->payload;
1548                 analog_copy = g_malloc(sizeof(*analog_copy));
1549                 analog_copy->data = g_malloc(
1550                                 analog->encoding->unitsize * analog->num_samples);
1551                 memcpy(analog_copy->data, analog->data,
1552                                 analog->encoding->unitsize * analog->num_samples);
1553                 analog_copy->num_samples = analog->num_samples;
1554                 analog_copy->encoding = g_memdup(analog->encoding,
1555                                 sizeof(struct sr_analog_encoding));
1556                 analog_copy->meaning = g_memdup(analog->meaning,
1557                                 sizeof(struct sr_analog_meaning));
1558                 analog_copy->meaning->channels = g_slist_copy(
1559                                 analog->meaning->channels);
1560                 analog_copy->spec = g_memdup(analog->spec,
1561                                 sizeof(struct sr_analog_spec));
1562                 (*copy)->payload = analog_copy;
1563                 break;
1564         default:
1565                 sr_err("Unknown packet type %d", packet->type);
1566                 return SR_ERR;
1567         }
1568
1569         return SR_OK;
1570 }
1571
1572 void sr_packet_free(struct sr_datafeed_packet *packet)
1573 {
1574         const struct sr_datafeed_meta *meta;
1575         const struct sr_datafeed_logic *logic;
1576         const struct sr_datafeed_analog_old *analog_old;
1577         const struct sr_datafeed_analog *analog;
1578         struct sr_config *src;
1579         GSList *l;
1580
1581         switch (packet->type) {
1582         case SR_DF_TRIGGER:
1583         case SR_DF_END:
1584                 /* No payload. */
1585                 break;
1586         case SR_DF_HEADER:
1587                 /* Payload is a simple struct. */
1588                 g_free((void *)packet->payload);
1589                 break;
1590         case SR_DF_META:
1591                 meta = packet->payload;
1592                 for (l = meta->config; l; l = l->next) {
1593                         src = l->data;
1594                         g_variant_unref(src->data);
1595                         g_free(src);
1596                 }
1597                 g_slist_free(meta->config);
1598                 g_free((void *)packet->payload);
1599                 break;
1600         case SR_DF_LOGIC:
1601                 logic = packet->payload;
1602                 g_free(logic->data);
1603                 g_free((void *)packet->payload);
1604                 break;
1605         case SR_DF_ANALOG_OLD:
1606                 analog_old = packet->payload;
1607                 g_slist_free(analog_old->channels);
1608                 g_free(analog_old->data);
1609                 g_free((void *)packet->payload);
1610                 break;
1611         case SR_DF_ANALOG:
1612                 analog = packet->payload;
1613                 g_free(analog->data);
1614                 g_free(analog->encoding);
1615                 g_slist_free(analog->meaning->channels);
1616                 g_free(analog->meaning);
1617                 g_free(analog->spec);
1618                 g_free((void *)packet->payload);
1619                 break;
1620         default:
1621                 sr_err("Unknown packet type %d", packet->type);
1622         }
1623         g_free(packet);
1624
1625 }
1626
1627 /** @} */