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