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