ec8082eb7cf0158ec0c85954a1bcc99e12227b86
[pulseview.git] / pv / session.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
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 2 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 <cassert>
21 #include <memory>
22 #include <mutex>
23 #include <stdexcept>
24
25 #include <sys/stat.h>
26
27 #include <QDebug>
28 #include <QFileInfo>
29
30 #include "devicemanager.hpp"
31 #include "mainwindow.hpp"
32 #include "session.hpp"
33 #include "util.hpp"
34
35 #include "data/analog.hpp"
36 #include "data/analogsegment.hpp"
37 #include "data/decode/decoder.hpp"
38 #include "data/logic.hpp"
39 #include "data/logicsegment.hpp"
40 #include "data/signalbase.hpp"
41
42 #include "devices/hardwaredevice.hpp"
43 #include "devices/inputfile.hpp"
44 #include "devices/sessionfile.hpp"
45
46 #include "toolbars/mainbar.hpp"
47
48 #include "views/trace/analogsignal.hpp"
49 #include "views/trace/decodetrace.hpp"
50 #include "views/trace/logicsignal.hpp"
51 #include "views/trace/signal.hpp"
52 #include "views/trace/view.hpp"
53
54 #include <libsigrokcxx/libsigrokcxx.hpp>
55
56 #ifdef ENABLE_FLOW
57 #include <gstreamermm.h>
58 #include <libsigrokflow/libsigrokflow.hpp>
59 #endif
60
61 #ifdef ENABLE_DECODE
62 #include <libsigrokdecode/libsigrokdecode.h>
63 #include "data/decodesignal.hpp"
64 #endif
65
66 using std::bad_alloc;
67 using std::dynamic_pointer_cast;
68 using std::find_if;
69 using std::function;
70 using std::list;
71 using std::lock_guard;
72 using std::make_pair;
73 using std::make_shared;
74 using std::map;
75 using std::max;
76 using std::move;
77 using std::mutex;
78 using std::pair;
79 using std::recursive_mutex;
80 using std::runtime_error;
81 using std::shared_ptr;
82 using std::string;
83 #ifdef ENABLE_FLOW
84 using std::unique_lock;
85 #endif
86 using std::unique_ptr;
87 using std::vector;
88
89 using sigrok::Analog;
90 using sigrok::Channel;
91 using sigrok::ConfigKey;
92 using sigrok::DatafeedCallbackFunction;
93 using sigrok::Error;
94 using sigrok::InputFormat;
95 using sigrok::Logic;
96 using sigrok::Meta;
97 using sigrok::Packet;
98 using sigrok::Session;
99
100 using Glib::VariantBase;
101
102 #ifdef ENABLE_FLOW
103 using Gst::Bus;
104 using Gst::ElementFactory;
105 using Gst::Pipeline;
106 #endif
107
108 using pv::data::SignalGroup;
109 using pv::util::Timestamp;
110 using pv::views::trace::Signal;
111 using pv::views::trace::AnalogSignal;
112 using pv::views::trace::LogicSignal;
113
114 namespace pv {
115
116 shared_ptr<sigrok::Context> Session::sr_context;
117
118 Session::Session(DeviceManager &device_manager, QString name) :
119         shutting_down_(false),
120         device_manager_(device_manager),
121         default_name_(name),
122         name_(name),
123         capture_state_(Stopped),
124         cur_samplerate_(0),
125         data_saved_(true)
126 {
127 }
128
129 Session::~Session()
130 {
131         shutting_down_ = true;
132
133         // Stop and join to the thread
134         stop_capture();
135
136         for (SignalGroup* group : signal_groups_) {
137                 group->clear();
138                 delete group;
139         }
140 }
141
142 DeviceManager& Session::device_manager()
143 {
144         return device_manager_;
145 }
146
147 const DeviceManager& Session::device_manager() const
148 {
149         return device_manager_;
150 }
151
152 shared_ptr<sigrok::Session> Session::session() const
153 {
154         if (!device_)
155                 return shared_ptr<sigrok::Session>();
156         return device_->session();
157 }
158
159 shared_ptr<devices::Device> Session::device() const
160 {
161         return device_;
162 }
163
164 QString Session::name() const
165 {
166         return name_;
167 }
168
169 void Session::set_name(QString name)
170 {
171         if (default_name_.isEmpty())
172                 default_name_ = name;
173
174         name_ = name;
175
176         name_changed();
177 }
178
179 QString Session::save_path() const
180 {
181         return save_path_;
182 }
183
184 void Session::set_save_path(QString path)
185 {
186         save_path_ = path;
187 }
188
189 const vector< shared_ptr<views::ViewBase> > Session::views() const
190 {
191         return views_;
192 }
193
194 shared_ptr<views::ViewBase> Session::main_view() const
195 {
196         return main_view_;
197 }
198
199 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
200 {
201         main_bar_ = main_bar;
202 }
203
204 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
205 {
206         return main_bar_;
207 }
208
209 bool Session::data_saved() const
210 {
211         return data_saved_;
212 }
213
214 void Session::save_setup(QSettings &settings) const
215 {
216         int i = 0;
217
218         // Save channels and decoders
219         for (const shared_ptr<data::SignalBase>& base : signalbases_) {
220 #ifdef ENABLE_DECODE
221                 if (base->is_decode_signal()) {
222                         settings.beginGroup("decode_signal" + QString::number(i++));
223                         base->save_settings(settings);
224                         settings.endGroup();
225                 } else
226 #endif
227                 {
228                         settings.beginGroup(base->internal_name());
229                         base->save_settings(settings);
230                         settings.endGroup();
231                 }
232         }
233
234         settings.setValue("decode_signals", i);
235
236         // Save view states and their signal settings
237         // Note: main_view must be saved as view0
238         i = 0;
239         settings.beginGroup("view" + QString::number(i++));
240         main_view_->save_settings(settings);
241         settings.endGroup();
242
243         for (const shared_ptr<views::ViewBase>& view : views_) {
244                 if (view != main_view_) {
245                         settings.beginGroup("view" + QString::number(i++));
246                         settings.setValue("type", view->get_type());
247                         view->save_settings(settings);
248                         settings.endGroup();
249                 }
250         }
251
252         settings.setValue("views", i);
253
254         int view_id = 0;
255         i = 0;
256         for (const shared_ptr<views::ViewBase>& vb : views_) {
257                 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(vb);
258                 if (tv) {
259                         for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
260
261                                 const shared_ptr<views::trace::Flag> flag =
262                                         dynamic_pointer_cast<views::trace::Flag>(time_item);
263                                 if (flag) {
264                                         if (!flag->enabled())
265                                                 continue;
266
267                                         settings.beginGroup("meta_obj" + QString::number(i++));
268                                         settings.setValue("type", "time_marker");
269                                         settings.setValue("assoc_view", view_id);
270                                         GlobalSettings::store_timestamp(settings, "time", flag->time());
271                                         settings.setValue("text", flag->get_text());
272                                         settings.endGroup();
273                                 }
274                         }
275
276                         if (tv->cursors_shown()) {
277                                 settings.beginGroup("meta_obj" + QString::number(i++));
278                                 settings.setValue("type", "selection");
279                                 settings.setValue("assoc_view", view_id);
280                                 const shared_ptr<views::trace::CursorPair> cp = tv->cursors();
281                                 GlobalSettings::store_timestamp(settings, "start_time", cp->first()->time());
282                                 GlobalSettings::store_timestamp(settings, "end_time", cp->second()->time());
283                                 settings.endGroup();
284                         }
285                 }
286
287                 view_id++;
288         }
289
290         settings.setValue("meta_objs", i);
291 }
292
293 void Session::save_settings(QSettings &settings) const
294 {
295         map<string, string> dev_info;
296         list<string> key_list;
297
298         if (device_) {
299                 shared_ptr<devices::HardwareDevice> hw_device =
300                         dynamic_pointer_cast< devices::HardwareDevice >(device_);
301
302                 if (hw_device) {
303                         settings.setValue("device_type", "hardware");
304                         settings.beginGroup("device");
305
306                         key_list.emplace_back("vendor");
307                         key_list.emplace_back("model");
308                         key_list.emplace_back("version");
309                         key_list.emplace_back("serial_num");
310                         key_list.emplace_back("connection_id");
311
312                         dev_info = device_manager_.get_device_info(device_);
313
314                         for (string& key : key_list) {
315                                 if (dev_info.count(key))
316                                         settings.setValue(QString::fromUtf8(key.c_str()),
317                                                         QString::fromUtf8(dev_info.at(key).c_str()));
318                                 else
319                                         settings.remove(QString::fromUtf8(key.c_str()));
320                         }
321
322                         settings.endGroup();
323                 }
324
325                 shared_ptr<devices::SessionFile> sessionfile_device =
326                         dynamic_pointer_cast<devices::SessionFile>(device_);
327
328                 if (sessionfile_device) {
329                         settings.setValue("device_type", "sessionfile");
330                         settings.beginGroup("device");
331                         settings.setValue("filename", QString::fromStdString(
332                                 sessionfile_device->full_name()));
333                         settings.endGroup();
334                 }
335
336                 shared_ptr<devices::InputFile> inputfile_device =
337                         dynamic_pointer_cast<devices::InputFile>(device_);
338
339                 if (inputfile_device) {
340                         settings.setValue("device_type", "inputfile");
341                         settings.beginGroup("device");
342                         inputfile_device->save_meta_to_settings(settings);
343                         settings.endGroup();
344                 }
345
346                 save_setup(settings);
347         }
348 }
349
350 void Session::restore_setup(QSettings &settings)
351 {
352         // Restore channels
353         for (shared_ptr<data::SignalBase> base : signalbases_) {
354                 settings.beginGroup(base->internal_name());
355                 base->restore_settings(settings);
356                 settings.endGroup();
357         }
358
359         // Restore decoders
360 #ifdef ENABLE_DECODE
361         int decode_signals = settings.value("decode_signals").toInt();
362
363         for (int i = 0; i < decode_signals; i++) {
364                 settings.beginGroup("decode_signal" + QString::number(i));
365                 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
366                 signal->restore_settings(settings);
367                 settings.endGroup();
368         }
369 #endif
370
371         // Restore views
372         int views = settings.value("views").toInt();
373
374         for (int i = 0; i < views; i++) {
375                 settings.beginGroup("view" + QString::number(i));
376
377                 if (i > 0) {
378                         views::ViewType type = (views::ViewType)settings.value("type").toInt();
379                         add_view(type, this);
380                         views_.back()->restore_settings(settings);
381                 } else
382                         main_view_->restore_settings(settings);
383
384                 settings.endGroup();
385         }
386
387         // Restore meta objects like markers and cursors
388         int meta_objs = settings.value("meta_objs").toInt();
389
390         for (int i = 0; i < meta_objs; i++) {
391                 settings.beginGroup("meta_obj" + QString::number(i));
392
393                 shared_ptr<views::ViewBase> vb;
394                 shared_ptr<views::trace::View> tv;
395                 if (settings.contains("assoc_view"))
396                         vb = views_.at(settings.value("assoc_view").toInt());
397
398                 if (vb)
399                         tv = dynamic_pointer_cast<views::trace::View>(vb);
400
401                 const QString type = settings.value("type").toString();
402
403                 if ((type == "time_marker") && tv) {
404                         Timestamp ts = GlobalSettings::restore_timestamp(settings, "time");
405                         shared_ptr<views::trace::Flag> flag = tv->add_flag(ts);
406                         flag->set_text(settings.value("text").toString());
407                 }
408
409                 if ((type == "selection") && tv) {
410                         Timestamp start = GlobalSettings::restore_timestamp(settings, "start_time");
411                         Timestamp end = GlobalSettings::restore_timestamp(settings, "end_time");
412                         tv->set_cursors(start, end);
413                         tv->show_cursors();
414                 }
415
416                 settings.endGroup();
417         }
418 }
419
420 void Session::restore_settings(QSettings &settings)
421 {
422         shared_ptr<devices::Device> device;
423
424         const QString device_type = settings.value("device_type").toString();
425
426         if (device_type == "hardware") {
427                 map<string, string> dev_info;
428                 list<string> key_list;
429
430                 // Re-select last used device if possible but only if it's not demo
431                 settings.beginGroup("device");
432                 key_list.emplace_back("vendor");
433                 key_list.emplace_back("model");
434                 key_list.emplace_back("version");
435                 key_list.emplace_back("serial_num");
436                 key_list.emplace_back("connection_id");
437
438                 for (string key : key_list) {
439                         const QString k = QString::fromStdString(key);
440                         if (!settings.contains(k))
441                                 continue;
442
443                         const string value = settings.value(k).toString().toStdString();
444                         if (!value.empty())
445                                 dev_info.insert(make_pair(key, value));
446                 }
447
448                 if (dev_info.count("model") > 0)
449                         device = device_manager_.find_device_from_info(dev_info);
450
451                 if (device)
452                         set_device(device);
453
454                 settings.endGroup();
455         }
456
457
458         QString filename;
459         if ((device_type == "sessionfile") || (device_type == "inputfile")) {
460                 if (device_type == "sessionfile") {
461                         settings.beginGroup("device");
462                         filename = settings.value("filename").toString();
463                         settings.endGroup();
464
465                         if (QFileInfo(filename).isReadable())
466                                 device = make_shared<devices::SessionFile>(device_manager_.context(),
467                                         filename.toStdString());
468                 }
469
470                 if (device_type == "inputfile") {
471                         settings.beginGroup("device");
472                         device = make_shared<devices::InputFile>(device_manager_.context(),
473                                 settings);
474                         settings.endGroup();
475                 }
476
477                 if (device) {
478                         set_device(device);
479
480                         start_capture([](QString infoMessage) {
481                                 // TODO Emulate noquote()
482                                 qDebug() << "Session error:" << infoMessage; });
483
484                         set_name(QString::fromStdString(
485                                 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
486
487                         if (!filename.isEmpty()) {
488                                 // Only set the save path if we load an srzip file
489                                 if (device_type == "sessionfile")
490                                         set_save_path(QFileInfo(filename).absolutePath());
491
492                                 set_name(QFileInfo(filename).fileName());
493                         }
494                 }
495         }
496
497         if (device)
498                 restore_setup(settings);
499 }
500
501 void Session::select_device(shared_ptr<devices::Device> device)
502 {
503         try {
504                 if (device)
505                         set_device(device);
506                 else
507                         set_default_device();
508         } catch (const QString &e) {
509                 MainWindow::show_session_error(tr("Failed to select device"), e);
510         }
511 }
512
513 void Session::set_device(shared_ptr<devices::Device> device)
514 {
515         assert(device);
516
517         // Ensure we are not capturing before setting the device
518         stop_capture();
519
520         if (device_)
521                 device_->close();
522
523         device_.reset();
524
525         // Revert name back to default name (e.g. "Session 1") as the data is gone
526         name_ = default_name_;
527         name_changed();
528
529         // Remove all stored data and reset all views
530         for (shared_ptr<views::ViewBase> view : views_) {
531                 view->clear_signalbases();
532 #ifdef ENABLE_DECODE
533                 view->clear_decode_signals();
534 #endif
535                 view->reset_view_state();
536         }
537
538         for (SignalGroup* group : signal_groups_) {
539                 group->clear();
540                 delete group;
541         }
542         signal_groups_.clear();
543
544         for (const shared_ptr<data::SignalData>& d : all_signal_data_)
545                 d->clear();
546
547         all_signal_data_.clear();
548         signalbases_.clear();
549         cur_logic_segment_.reset();
550
551         for (auto& entry : cur_analog_segments_) {
552                 shared_ptr<sigrok::Channel>(entry.first).reset();
553                 shared_ptr<data::AnalogSegment>(entry.second).reset();
554         }
555
556         logic_data_.reset();
557
558         signals_changed();
559
560         device_ = move(device);
561
562         try {
563                 device_->open();
564         } catch (const QString &e) {
565                 device_.reset();
566                 MainWindow::show_session_error(tr("Failed to open device"), e);
567         }
568
569         if (device_) {
570                 device_->session()->add_datafeed_callback([=]
571                         (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
572                                 data_feed_in(device, packet);
573                         });
574
575                 update_signals();
576         }
577
578         device_changed();
579 }
580
581 void Session::set_default_device()
582 {
583         const list< shared_ptr<devices::HardwareDevice> > &devices =
584                 device_manager_.devices();
585
586         if (devices.empty())
587                 return;
588
589         // Try and find the demo device and select that by default
590         const auto iter = find_if(devices.begin(), devices.end(),
591                 [] (const shared_ptr<devices::HardwareDevice> &d) {
592                         return d->hardware_device()->driver()->name() == "demo"; });
593         set_device((iter == devices.end()) ? devices.front() : *iter);
594 }
595
596 bool Session::using_file_device() const
597 {
598         shared_ptr<devices::SessionFile> sessionfile_device =
599                 dynamic_pointer_cast<devices::SessionFile>(device_);
600
601         shared_ptr<devices::InputFile> inputfile_device =
602                 dynamic_pointer_cast<devices::InputFile>(device_);
603
604         return (sessionfile_device || inputfile_device);
605 }
606
607 /**
608  * Convert generic options to data types that are specific to InputFormat.
609  *
610  * @param[in] user_spec Vector of tokenized words, string format.
611  * @param[in] fmt_opts Input format's options, result of InputFormat::options().
612  *
613  * @return Map of options suitable for InputFormat::create_input().
614  */
615 map<string, Glib::VariantBase>
616 Session::input_format_options(vector<string> user_spec,
617                 map<string, shared_ptr<Option>> fmt_opts)
618 {
619         map<string, Glib::VariantBase> result;
620
621         for (auto& entry : user_spec) {
622                 /*
623                  * Split key=value specs. Accept entries without separator
624                  * (for simplified boolean specifications).
625                  */
626                 string key, val;
627                 size_t pos = entry.find("=");
628                 if (pos == std::string::npos) {
629                         key = entry;
630                         val = "";
631                 } else {
632                         key = entry.substr(0, pos);
633                         val = entry.substr(pos + 1);
634                 }
635
636                 /*
637                  * Skip user specifications that are not a member of the
638                  * format's set of supported options. Have the text input
639                  * spec converted to the required input format specific
640                  * data type.
641                  */
642                 auto found = fmt_opts.find(key);
643                 if (found == fmt_opts.end()) {
644                         qCritical() << "Supplied input option" << QString::fromStdString(key) <<
645                                 "is not a valid option for this input module, it will be ignored!";
646                         continue;
647                 }
648
649                 shared_ptr<Option> opt = found->second;
650                 result[key] = opt->parse_string(val);
651         }
652
653         return result;
654 }
655
656 void Session::load_init_file(const string &file_name,
657         const string &format, const string &setup_file_name)
658 {
659         shared_ptr<InputFormat> input_format;
660         map<string, Glib::VariantBase> input_opts;
661
662         if (!format.empty()) {
663                 const map<string, shared_ptr<InputFormat> > formats =
664                         device_manager_.context()->input_formats();
665                 auto user_opts = pv::util::split_string(format, ":");
666                 string user_name = user_opts.front();
667                 user_opts.erase(user_opts.begin());
668                 const auto iter = find_if(formats.begin(), formats.end(),
669                         [&](const pair<string, shared_ptr<InputFormat> > f) {
670                                 return f.first == user_name; });
671                 if (iter == formats.end()) {
672                         MainWindow::show_session_error(tr("Error"),
673                                 tr("Unexpected input format: %1").arg(QString::fromStdString(format)));
674                         return;
675                 }
676                 input_format = (*iter).second;
677                 input_opts = input_format_options(user_opts,
678                         input_format->options());
679         }
680
681         load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
682                 input_format, input_opts);
683 }
684
685 void Session::load_file(QString file_name, QString setup_file_name,
686         shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
687 {
688         const QString errorMessage(
689                 QString("Failed to load file %1").arg(file_name));
690
691         // In the absence of a caller's format spec, try to auto detect.
692         // Assume "sigrok session file" upon lookup miss.
693         if (!format)
694                 format = device_manager_.context()->input_format_match(file_name.toStdString());
695         try {
696                 if (format)
697                         set_device(shared_ptr<devices::Device>(
698                                 new devices::InputFile(
699                                         device_manager_.context(),
700                                         file_name.toStdString(),
701                                         format, options)));
702                 else
703                         set_device(shared_ptr<devices::Device>(
704                                 new devices::SessionFile(
705                                         device_manager_.context(),
706                                         file_name.toStdString())));
707         } catch (Error& e) {
708                 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
709                 set_default_device();
710                 main_bar_->update_device_list();
711                 return;
712         }
713
714         // Use the input file with .pvs extension if no setup file was given
715         if (setup_file_name.isEmpty()) {
716                 setup_file_name = file_name;
717                 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
718                 setup_file_name.append(".pvs");
719         }
720
721         if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
722                 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
723                 restore_setup(settings_storage);
724         }
725
726         main_bar_->update_device_list();
727
728         start_capture([&, errorMessage](QString infoMessage) {
729                 MainWindow::show_session_error(errorMessage, infoMessage); });
730
731         // Only set save path if we loaded an srzip file
732         if (dynamic_pointer_cast<devices::SessionFile>(device_))
733                 set_save_path(QFileInfo(file_name).absolutePath());
734
735         set_name(QFileInfo(file_name).fileName());
736 }
737
738 Session::capture_state Session::get_capture_state() const
739 {
740         lock_guard<mutex> lock(sampling_mutex_);
741         return capture_state_;
742 }
743
744 void Session::start_capture(function<void (const QString)> error_handler)
745 {
746         if (!device_) {
747                 error_handler(tr("No active device set, can't start acquisition."));
748                 return;
749         }
750
751         stop_capture();
752
753         // Check that at least one channel is enabled
754         const shared_ptr<sigrok::Device> sr_dev = device_->device();
755         if (sr_dev) {
756                 const auto channels = sr_dev->channels();
757                 if (!any_of(channels.begin(), channels.end(),
758                         [](shared_ptr<Channel> channel) {
759                                 return channel->enabled(); })) {
760                         error_handler(tr("No channels enabled."));
761                         return;
762                 }
763         }
764
765         // Clear signal data
766         for (const shared_ptr<data::SignalData>& d : all_signal_data_)
767                 d->clear();
768
769         trigger_list_.clear();
770
771         // Revert name back to default name (e.g. "Session 1") for real devices
772         // as the (possibly saved) data is gone. File devices keep their name.
773         shared_ptr<devices::HardwareDevice> hw_device =
774                 dynamic_pointer_cast< devices::HardwareDevice >(device_);
775
776         if (hw_device) {
777                 name_ = default_name_;
778                 name_changed();
779         }
780
781         // Begin the session
782         sampling_thread_ = std::thread(
783                 &Session::sample_thread_proc, this, error_handler);
784 }
785
786 void Session::stop_capture()
787 {
788         if (get_capture_state() != Stopped)
789                 device_->stop();
790
791         // Check that sampling stopped
792         if (sampling_thread_.joinable())
793                 sampling_thread_.join();
794 }
795
796 void Session::register_view(shared_ptr<views::ViewBase> view)
797 {
798         if (views_.empty())
799                 main_view_ = view;
800
801         views_.push_back(view);
802
803         // Add all device signals
804         update_signals();
805
806         // Add all other signals
807         vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
808
809         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
810                 const int sb_exists = count_if(
811                         view_signalbases.cbegin(), view_signalbases.cend(),
812                         [&](const shared_ptr<data::SignalBase> &sb) {
813                                 return sb == signalbase;
814                         });
815
816                 // Add the signal to the view if it doesn't have it yet
817                 if (!sb_exists)
818                         switch (signalbase->type()) {
819                         case data::SignalBase::AnalogChannel:
820                         case data::SignalBase::LogicChannel:
821                         case data::SignalBase::MathChannel:
822                                 view->add_signalbase(signalbase);
823                                 break;
824                         case data::SignalBase::DecodeChannel:
825 #ifdef ENABLE_DECODE
826                                 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
827 #endif
828                                 break;
829                         }
830         }
831
832         signals_changed();
833 }
834
835 void Session::deregister_view(shared_ptr<views::ViewBase> view)
836 {
837         views_.erase(std::remove_if(views_.begin(), views_.end(),
838                 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
839                 views_.end());
840
841         if (views_.empty()) {
842                 main_view_.reset();
843
844                 // Without a view there can be no main bar
845                 main_bar_.reset();
846         }
847 }
848
849 bool Session::has_view(shared_ptr<views::ViewBase> view)
850 {
851         for (shared_ptr<views::ViewBase>& v : views_)
852                 if (v == view)
853                         return true;
854
855         return false;
856 }
857
858 double Session::get_samplerate() const
859 {
860         double samplerate = 0.0;
861
862         for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
863                 assert(d);
864                 const vector< shared_ptr<pv::data::Segment> > segments =
865                         d->segments();
866                 for (const shared_ptr<pv::data::Segment>& s : segments)
867                         samplerate = max(samplerate, s->samplerate());
868         }
869         // If there is no sample rate given we use samples as unit
870         if (samplerate == 0.0)
871                 samplerate = 1.0;
872
873         return samplerate;
874 }
875
876 uint32_t Session::get_segment_count() const
877 {
878         uint32_t value = 0;
879
880         // Find the highest number of segments
881         for (const shared_ptr<data::SignalData>& data : all_signal_data_)
882                 if (data->get_segment_count() > value)
883                         value = data->get_segment_count();
884
885         return value;
886 }
887
888 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
889 {
890         vector<util::Timestamp> result;
891
892         for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
893                 if (entry.first == segment_id)
894                         result.push_back(entry.second);
895
896         return result;
897 }
898
899 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
900 {
901         return signalbases_;
902 }
903
904 void Session::add_generated_signal(shared_ptr<data::SignalBase> signal)
905 {
906         signalbases_.push_back(signal);
907
908         for (shared_ptr<views::ViewBase>& view : views_)
909                 view->add_signalbase(signal);
910
911         update_signals();
912 }
913
914 void Session::remove_generated_signal(shared_ptr<data::SignalBase> signal)
915 {
916         if (shutting_down_)
917                 return;
918
919         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
920                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
921                 signalbases_.end());
922
923         for (shared_ptr<views::ViewBase>& view : views_)
924                 view->remove_signalbase(signal);
925
926         update_signals();
927 }
928
929 #ifdef ENABLE_DECODE
930 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
931 {
932         shared_ptr<data::DecodeSignal> signal;
933
934         try {
935                 // Create the decode signal
936                 signal = make_shared<data::DecodeSignal>(*this);
937
938                 signalbases_.push_back(signal);
939
940                 // Add the decode signal to all views
941                 for (shared_ptr<views::ViewBase>& view : views_)
942                         view->add_decode_signal(signal);
943         } catch (runtime_error& e) {
944                 remove_decode_signal(signal);
945                 return nullptr;
946         }
947
948         signals_changed();
949
950         return signal;
951 }
952
953 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
954 {
955         if (shutting_down_)
956                 return;
957
958         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
959                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
960                 signalbases_.end());
961
962         for (shared_ptr<views::ViewBase>& view : views_)
963                 view->remove_decode_signal(signal);
964
965         signals_changed();
966 }
967 #endif
968
969 bool Session::all_segments_complete(uint32_t segment_id) const
970 {
971         bool all_complete = true;
972
973         for (const shared_ptr<data::SignalBase>& base : signalbases_)
974                 if (!base->segment_is_complete(segment_id))
975                         all_complete = false;
976
977         return all_complete;
978 }
979
980 MetadataObjManager* Session::metadata_obj_manager()
981 {
982         return &metadata_obj_manager_;
983 }
984
985 void Session::set_capture_state(capture_state state)
986 {
987         bool changed;
988
989         if (state == Running)
990                 acq_time_.restart();
991         if (state == Stopped)
992                 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
993
994         {
995                 lock_guard<mutex> lock(sampling_mutex_);
996                 changed = capture_state_ != state;
997                 capture_state_ = state;
998         }
999
1000         if (changed)
1001                 capture_state_changed(state);
1002 }
1003
1004 void Session::update_signals()
1005 {
1006         if (!device_) {
1007                 signalbases_.clear();
1008                 logic_data_.reset();
1009                 for (shared_ptr<views::ViewBase>& view : views_) {
1010                         view->clear_signalbases();
1011 #ifdef ENABLE_DECODE
1012                         view->clear_decode_signals();
1013 #endif
1014                 }
1015                 return;
1016         }
1017
1018         lock_guard<recursive_mutex> lock(data_mutex_);
1019
1020         const shared_ptr<sigrok::Device> sr_dev = device_->device();
1021         if (!sr_dev) {
1022                 signalbases_.clear();
1023                 logic_data_.reset();
1024                 for (shared_ptr<views::ViewBase>& view : views_) {
1025                         view->clear_signalbases();
1026 #ifdef ENABLE_DECODE
1027                         view->clear_decode_signals();
1028 #endif
1029                 }
1030                 return;
1031         }
1032
1033         // Detect what data types we will receive
1034         auto channels = sr_dev->channels();
1035         unsigned int logic_channel_count = count_if(
1036                 channels.begin(), channels.end(),
1037                 [] (shared_ptr<Channel> channel) {
1038                         return channel->type() == sigrok::ChannelType::LOGIC; });
1039
1040         // Create a common data container for the logic signalbases
1041         {
1042                 lock_guard<recursive_mutex> data_lock(data_mutex_);
1043
1044                 if (logic_channel_count == 0) {
1045                         logic_data_.reset();
1046                 } else if (!logic_data_ ||
1047                         logic_data_->num_channels() != logic_channel_count) {
1048                         logic_data_.reset(new data::Logic(logic_channel_count));
1049                         assert(logic_data_);
1050                 }
1051         }
1052
1053         // Create signalbases if necessary
1054         for (auto channel : sr_dev->channels()) {
1055
1056                 // Try to find the channel in the list of existing signalbases
1057                 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1058                         [&](const shared_ptr<SignalBase> &sb) { return sb->channel() == channel; });
1059
1060                 // Not found, let's make a signalbase for it
1061                 if (iter == signalbases_.cend()) {
1062                         shared_ptr<SignalBase> signalbase;
1063                         switch(channel->type()->id()) {
1064                         case SR_CHANNEL_LOGIC:
1065                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::LogicChannel);
1066                                 signalbases_.push_back(signalbase);
1067
1068                                 all_signal_data_.insert(logic_data_);
1069                                 signalbase->set_data(logic_data_);
1070
1071                                 connect(this, SIGNAL(capture_state_changed(int)),
1072                                         signalbase.get(), SLOT(on_capture_state_changed(int)));
1073                                 break;
1074
1075                         case SR_CHANNEL_ANALOG:
1076                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::AnalogChannel);
1077                                 signalbases_.push_back(signalbase);
1078
1079                                 shared_ptr<data::Analog> data(new data::Analog());
1080                                 all_signal_data_.insert(data);
1081                                 signalbase->set_data(data);
1082
1083                                 connect(this, SIGNAL(capture_state_changed(int)),
1084                                         signalbase.get(), SLOT(on_capture_state_changed(int)));
1085                                 break;
1086                         }
1087                 }
1088         }
1089
1090         // Create and assign default signal groups if needed
1091         if (signal_groups_.empty()) {
1092                 for (auto& entry : sr_dev->channel_groups()) {
1093                         const shared_ptr<sigrok::ChannelGroup>& group = entry.second;
1094
1095                         if (group->channels().size() <= 1)
1096                                 continue;
1097
1098                         SignalGroup* sg = new SignalGroup(QString::fromStdString(entry.first));
1099                         for (const shared_ptr<sigrok::Channel>& channel : group->channels()) {
1100                                 for (shared_ptr<data::SignalBase> s : signalbases_) {
1101                                         if (s->channel() == channel) {
1102                                                 sg->append_signal(s);
1103                                                 break;
1104                                         }
1105                                 }
1106                         }
1107                         signal_groups_.emplace_back(sg);
1108                 }
1109         }
1110
1111         // Update all views
1112         for (shared_ptr<views::ViewBase>& viewbase : views_) {
1113                 vector< shared_ptr<SignalBase> > view_signalbases =
1114                                 viewbase->signalbases();
1115
1116                 // Add all non-decode signalbases that don't yet exist in the view
1117                 for (shared_ptr<SignalBase>& session_sb : signalbases_) {
1118                         if (session_sb->type() == SignalBase::DecodeChannel)
1119                                 continue;
1120
1121                         const auto iter = find_if(view_signalbases.cbegin(), view_signalbases.cend(),
1122                                 [&](const shared_ptr<SignalBase> &sb) { return sb == session_sb; });
1123
1124                         if (iter == view_signalbases.cend())
1125                                 viewbase->add_signalbase(session_sb);
1126                 }
1127
1128                 // Remove all non-decode signalbases that no longer exist
1129                 for (shared_ptr<SignalBase>& view_sb : view_signalbases) {
1130                         if (view_sb->type() == SignalBase::DecodeChannel)
1131                                 continue;
1132
1133                         const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1134                                 [&](const shared_ptr<SignalBase> &sb) { return sb == view_sb; });
1135
1136                         if (iter == signalbases_.cend())
1137                                 viewbase->remove_signalbase(view_sb);
1138                 }
1139         }
1140
1141         signals_changed();
1142 }
1143
1144 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1145         shared_ptr<sigrok::Channel> channel) const
1146 {
1147         for (shared_ptr<data::SignalBase> sig : signalbases_) {
1148                 assert(sig);
1149                 if (sig->channel() == channel)
1150                         return sig;
1151         }
1152         return shared_ptr<data::SignalBase>();
1153 }
1154
1155 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1156 {
1157         assert(error_handler);
1158
1159 #ifdef ENABLE_FLOW
1160         pipeline_ = Pipeline::create();
1161
1162         source_ = ElementFactory::create_element("filesrc", "source");
1163         sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1164
1165         pipeline_->add(source_)->add(sink_);
1166         source_->link(sink_);
1167
1168         source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1169
1170         sink_->set_property("emit-signals", TRUE);
1171         sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1172
1173         // Get the bus from the pipeline and add a bus watch to the default main context
1174         RefPtr<Bus> bus = pipeline_->get_bus();
1175         bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1176
1177         // Start pipeline and Wait until it finished processing
1178         pipeline_done_interrupt_ = false;
1179         pipeline_->set_state(Gst::STATE_PLAYING);
1180
1181         unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1182         pipeline_done_cond_.wait(pipeline_done_lock_);
1183
1184         // Let the pipeline free all resources
1185         pipeline_->set_state(Gst::STATE_NULL);
1186
1187 #else
1188         if (!device_)
1189                 return;
1190
1191         try {
1192                 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1193         } catch (Error& e) {
1194                 cur_samplerate_ = 0;
1195         }
1196
1197         out_of_memory_ = false;
1198
1199         {
1200                 lock_guard<recursive_mutex> lock(data_mutex_);
1201                 cur_logic_segment_.reset();
1202                 cur_analog_segments_.clear();
1203                 for (shared_ptr<data::SignalBase> sb : signalbases_)
1204                         sb->clear_sample_data();
1205         }
1206         highest_segment_id_ = -1;
1207         frame_began_ = false;
1208
1209         try {
1210                 device_->start();
1211         } catch (Error& e) {
1212                 error_handler(e.what());
1213                 return;
1214         }
1215
1216         set_capture_state(device_->session()->trigger() ?
1217                 AwaitingTrigger : Running);
1218
1219         try {
1220                 device_->run();
1221         } catch (Error& e) {
1222                 error_handler(e.what());
1223                 set_capture_state(Stopped);
1224                 return;
1225         } catch (QString& e) {
1226                 error_handler(e);
1227                 set_capture_state(Stopped);
1228                 return;
1229         }
1230
1231         set_capture_state(Stopped);
1232
1233         // Confirm that SR_DF_END was received
1234         if (cur_logic_segment_)
1235                 qDebug() << "WARNING: SR_DF_END was not received.";
1236 #endif
1237
1238         // Optimize memory usage
1239         free_unused_memory();
1240
1241         // We now have unsaved data unless we just "captured" from a file
1242         shared_ptr<devices::File> file_device =
1243                 dynamic_pointer_cast<devices::File>(device_);
1244
1245         if (!file_device)
1246                 data_saved_ = false;
1247
1248         if (out_of_memory_)
1249                 error_handler(tr("Out of memory, acquisition stopped."));
1250 }
1251
1252 void Session::free_unused_memory()
1253 {
1254         for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1255                 const vector< shared_ptr<data::Segment> > segments = data->segments();
1256
1257                 for (const shared_ptr<data::Segment>& segment : segments)
1258                         segment->free_unused_memory();
1259         }
1260 }
1261
1262 void Session::signal_new_segment()
1263 {
1264         int new_segment_id = 0;
1265
1266         if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1267
1268                 // Determine new frame/segment number, assuming that all
1269                 // signals have the same number of frames/segments
1270                 if (cur_logic_segment_) {
1271                         new_segment_id = logic_data_->get_segment_count() - 1;
1272                 } else {
1273                         shared_ptr<sigrok::Channel> any_channel =
1274                                 (*cur_analog_segments_.begin()).first;
1275
1276                         shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1277                         assert(base);
1278
1279                         shared_ptr<data::Analog> data(base->analog_data());
1280                         assert(data);
1281
1282                         new_segment_id = data->get_segment_count() - 1;
1283                 }
1284         }
1285
1286         if (new_segment_id > highest_segment_id_) {
1287                 highest_segment_id_ = new_segment_id;
1288                 new_segment(highest_segment_id_);
1289         }
1290 }
1291
1292 void Session::signal_segment_completed()
1293 {
1294         int segment_id = 0;
1295
1296         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1297                 // We only care about analog and logic channels, not derived ones
1298                 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1299                         segment_id = signalbase->analog_data()->get_segment_count() - 1;
1300                         break;
1301                 }
1302
1303                 if (signalbase->type() == data::SignalBase::LogicChannel) {
1304                         segment_id = signalbase->logic_data()->get_segment_count() - 1;
1305                         break;
1306                 }
1307         }
1308
1309         if (segment_id >= 0)
1310                 segment_completed(segment_id);
1311 }
1312
1313 #ifdef ENABLE_FLOW
1314 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1315 {
1316         (void)bus;
1317
1318         if ((message->get_source() == pipeline_) && \
1319                 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1320                 pipeline_done_cond_.notify_one();
1321
1322         // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1323
1324         return true;
1325 }
1326
1327 Gst::FlowReturn Session::on_gst_new_sample()
1328 {
1329         RefPtr<Gst::Sample> sample = sink_->pull_sample();
1330         RefPtr<Gst::Buffer> buf = sample->get_buffer();
1331
1332         for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1333                 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1334                 Gst::MapInfo mapinfo;
1335                 buf_mem->map(mapinfo, Gst::MAP_READ);
1336
1337                 shared_ptr<sigrok::Packet> logic_packet =
1338                         sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1339
1340                 try {
1341                         feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1342                 } catch (bad_alloc&) {
1343                         out_of_memory_ = true;
1344                         device_->stop();
1345                         buf_mem->unmap(mapinfo);
1346                         return Gst::FLOW_ERROR;
1347                 }
1348
1349                 buf_mem->unmap(mapinfo);
1350         }
1351
1352         return Gst::FLOW_OK;
1353 }
1354 #endif
1355
1356 void Session::feed_in_header()
1357 {
1358         // Nothing to do here for now
1359 }
1360
1361 void Session::feed_in_meta(shared_ptr<Meta> meta)
1362 {
1363         for (auto& entry : meta->config()) {
1364                 switch (entry.first->id()) {
1365                 case SR_CONF_SAMPLERATE:
1366                         cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1367                         break;
1368                 default:
1369                         qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1370                         break;
1371                 }
1372         }
1373
1374         signals_changed();
1375 }
1376
1377 void Session::feed_in_trigger()
1378 {
1379         // The channel containing most samples should be most accurate
1380         uint64_t sample_count = 0;
1381
1382         {
1383                 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1384                         assert(d);
1385                         uint64_t temp_count = 0;
1386
1387                         const vector< shared_ptr<pv::data::Segment> > segments =
1388                                 d->segments();
1389                         for (const shared_ptr<pv::data::Segment> &s : segments)
1390                                 temp_count += s->get_sample_count();
1391
1392                         if (temp_count > sample_count)
1393                                 sample_count = temp_count;
1394                 }
1395         }
1396
1397         uint32_t segment_id = 0;  // Default segment when no frames are used
1398
1399         // If a frame began, we'd ideally be able to use the highest segment ID for
1400         // the trigger. However, as new segments are only created when logic or
1401         // analog data comes in, this doesn't work if the trigger appears right
1402         // after the beginning of the frame, before any sample data.
1403         // For this reason, we use highest segment ID + 1 if no sample data came in
1404         // yet and the highest segment ID otherwise.
1405         if (frame_began_) {
1406                 segment_id = highest_segment_id_;
1407                 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1408                         segment_id++;
1409         }
1410
1411         // TODO Create timestamp from segment start time + segment's current sample count
1412         util::Timestamp timestamp = sample_count / get_samplerate();
1413         trigger_list_.emplace_back(segment_id, timestamp);
1414         trigger_event(segment_id, timestamp);
1415 }
1416
1417 void Session::feed_in_frame_begin()
1418 {
1419         frame_began_ = true;
1420 }
1421
1422 void Session::feed_in_frame_end()
1423 {
1424         if (!frame_began_)
1425                 return;
1426
1427         {
1428                 lock_guard<recursive_mutex> lock(data_mutex_);
1429
1430                 if (cur_logic_segment_)
1431                         cur_logic_segment_->set_complete();
1432
1433                 for (auto& entry : cur_analog_segments_) {
1434                         shared_ptr<data::AnalogSegment> segment = entry.second;
1435                         segment->set_complete();
1436                 }
1437
1438                 cur_logic_segment_.reset();
1439                 cur_analog_segments_.clear();
1440         }
1441
1442         frame_began_ = false;
1443
1444         signal_segment_completed();
1445 }
1446
1447 void Session::feed_in_logic(shared_ptr<sigrok::Logic> logic)
1448 {
1449         if (logic->data_length() == 0) {
1450                 qDebug() << "WARNING: Received logic packet with 0 samples.";
1451                 return;
1452         }
1453
1454         if (logic->unit_size() > 8)
1455                 throw QString(tr("Can't handle more than 64 logic channels."));
1456
1457         if (!cur_samplerate_)
1458                 try {
1459                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1460                 } catch (Error& e) {
1461                         // Do nothing
1462                 }
1463
1464         lock_guard<recursive_mutex> lock(data_mutex_);
1465
1466         if (!logic_data_) {
1467                 // The only reason logic_data_ would not have been created is
1468                 // if it was not possible to determine the signals when the
1469                 // device was created.
1470                 update_signals();
1471         }
1472
1473         if (!cur_logic_segment_) {
1474                 // This could be the first packet after a trigger
1475                 set_capture_state(Running);
1476
1477                 // Create a new data segment
1478                 cur_logic_segment_ = make_shared<data::LogicSegment>(
1479                         *logic_data_, logic_data_->get_segment_count(),
1480                         logic->unit_size(), cur_samplerate_);
1481                 logic_data_->push_segment(cur_logic_segment_);
1482
1483                 signal_new_segment();
1484         }
1485
1486         cur_logic_segment_->append_payload(logic);
1487
1488         data_received();
1489 }
1490
1491 void Session::feed_in_analog(shared_ptr<sigrok::Analog> analog)
1492 {
1493         if (analog->num_samples() == 0) {
1494                 qDebug() << "WARNING: Received analog packet with 0 samples.";
1495                 return;
1496         }
1497
1498         if (!cur_samplerate_)
1499                 try {
1500                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1501                 } catch (Error& e) {
1502                         // Do nothing
1503                 }
1504
1505         lock_guard<recursive_mutex> lock(data_mutex_);
1506
1507         const vector<shared_ptr<Channel>> channels = analog->channels();
1508         bool sweep_beginning = false;
1509
1510         unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1511         analog->get_data_as_float(data.get());
1512
1513         if (signalbases_.empty())
1514                 update_signals();
1515
1516         float *channel_data = data.get();
1517         for (auto& channel : channels) {
1518                 shared_ptr<data::AnalogSegment> segment;
1519
1520                 // Try to get the segment of the channel
1521                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1522                         iterator iter = cur_analog_segments_.find(channel);
1523                 if (iter != cur_analog_segments_.end())
1524                         segment = (*iter).second;
1525                 else {
1526                         // If no segment was found, this means we haven't
1527                         // created one yet. i.e. this is the first packet
1528                         // in the sweep containing this segment.
1529                         sweep_beginning = true;
1530
1531                         // Find the analog data associated with the channel
1532                         shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1533                         assert(base);
1534
1535                         shared_ptr<data::Analog> data(base->analog_data());
1536                         assert(data);
1537
1538                         // Create a segment, keep it in the maps of channels
1539                         segment = make_shared<data::AnalogSegment>(
1540                                 *data, data->get_segment_count(), cur_samplerate_);
1541                         cur_analog_segments_[channel] = segment;
1542
1543                         // Push the segment into the analog data.
1544                         data->push_segment(segment);
1545
1546                         signal_new_segment();
1547                 }
1548
1549                 assert(segment);
1550
1551                 // Append the samples in the segment
1552                 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1553                         channels.size());
1554         }
1555
1556         if (sweep_beginning) {
1557                 // This could be the first packet after a trigger
1558                 set_capture_state(Running);
1559         }
1560
1561         data_received();
1562 }
1563
1564 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1565         shared_ptr<Packet> packet)
1566 {
1567         (void)device;
1568
1569         assert(device);
1570         assert(device == device_->device());
1571         assert(packet);
1572
1573         switch (packet->type()->id()) {
1574         case SR_DF_HEADER:
1575                 feed_in_header();
1576                 break;
1577
1578         case SR_DF_META:
1579                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1580                 break;
1581
1582         case SR_DF_TRIGGER:
1583                 feed_in_trigger();
1584                 break;
1585
1586         case SR_DF_LOGIC:
1587                 try {
1588                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1589                 } catch (bad_alloc&) {
1590                         out_of_memory_ = true;
1591                         device_->stop();
1592                 }
1593                 break;
1594
1595         case SR_DF_ANALOG:
1596                 try {
1597                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1598                 } catch (bad_alloc&) {
1599                         out_of_memory_ = true;
1600                         device_->stop();
1601                 }
1602                 break;
1603
1604         case SR_DF_FRAME_BEGIN:
1605                 feed_in_frame_begin();
1606                 break;
1607
1608         case SR_DF_FRAME_END:
1609                 feed_in_frame_end();
1610                 break;
1611
1612         case SR_DF_END:
1613                 // Strictly speaking, this is performed when a frame end marker was
1614                 // received, so there's no point doing this again. However, not all
1615                 // devices use frames, and for those devices, we need to do it here.
1616                 {
1617                         lock_guard<recursive_mutex> lock(data_mutex_);
1618
1619                         if (cur_logic_segment_)
1620                                 cur_logic_segment_->set_complete();
1621
1622                         for (auto& entry : cur_analog_segments_) {
1623                                 shared_ptr<data::AnalogSegment> segment = entry.second;
1624                                 segment->set_complete();
1625                         }
1626
1627                         cur_logic_segment_.reset();
1628                         cur_analog_segments_.clear();
1629                 }
1630                 break;
1631
1632         default:
1633                 break;
1634         }
1635 }
1636
1637 void Session::on_data_saved()
1638 {
1639         data_saved_ = true;
1640 }
1641
1642 #ifdef ENABLE_DECODE
1643 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1644 {
1645         assert(decoders.size() > 0);
1646
1647         shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1648
1649         if (signal)
1650                 for (unsigned int i = 0; i < decoders.size(); i++) {
1651                         const srd_decoder* d = decoders[i];
1652                         signal->stack_decoder(d, !(i < decoders.size() - 1));
1653                 }
1654 }
1655 #endif
1656
1657 } // namespace pv