Fix #1549 by notifying user of wrong input parameter names
[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                         qCritical() << "Supplied input option" << QString::fromStdString(key) <<
626                                 "is not a valid option for this input module, it will be ignored!";
627                         continue;
628                 }
629
630                 shared_ptr<Option> opt = found->second;
631                 result[key] = opt->parse_string(val);
632         }
633
634         return result;
635 }
636
637 void Session::load_init_file(const string &file_name,
638         const string &format, const string &setup_file_name)
639 {
640         shared_ptr<InputFormat> input_format;
641         map<string, Glib::VariantBase> input_opts;
642
643         if (!format.empty()) {
644                 const map<string, shared_ptr<InputFormat> > formats =
645                         device_manager_.context()->input_formats();
646                 auto user_opts = pv::util::split_string(format, ":");
647                 string user_name = user_opts.front();
648                 user_opts.erase(user_opts.begin());
649                 const auto iter = find_if(formats.begin(), formats.end(),
650                         [&](const pair<string, shared_ptr<InputFormat> > f) {
651                                 return f.first == user_name; });
652                 if (iter == formats.end()) {
653                         MainWindow::show_session_error(tr("Error"),
654                                 tr("Unexpected input format: %1").arg(QString::fromStdString(format)));
655                         return;
656                 }
657                 input_format = (*iter).second;
658                 input_opts = input_format_options(user_opts,
659                         input_format->options());
660         }
661
662         load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
663                 input_format, input_opts);
664 }
665
666 void Session::load_file(QString file_name, QString setup_file_name,
667         shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
668 {
669         const QString errorMessage(
670                 QString("Failed to load file %1").arg(file_name));
671
672         // In the absence of a caller's format spec, try to auto detect.
673         // Assume "sigrok session file" upon lookup miss.
674         if (!format)
675                 format = device_manager_.context()->input_format_match(file_name.toStdString());
676         try {
677                 if (format)
678                         set_device(shared_ptr<devices::Device>(
679                                 new devices::InputFile(
680                                         device_manager_.context(),
681                                         file_name.toStdString(),
682                                         format, options)));
683                 else
684                         set_device(shared_ptr<devices::Device>(
685                                 new devices::SessionFile(
686                                         device_manager_.context(),
687                                         file_name.toStdString())));
688         } catch (Error& e) {
689                 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
690                 set_default_device();
691                 main_bar_->update_device_list();
692                 return;
693         }
694
695         // Use the input file with .pvs extension if no setup file was given
696         if (setup_file_name.isEmpty()) {
697                 setup_file_name = file_name;
698                 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
699                 setup_file_name.append(".pvs");
700         }
701
702         if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
703                 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
704                 restore_setup(settings_storage);
705         }
706
707         main_bar_->update_device_list();
708
709         start_capture([&, errorMessage](QString infoMessage) {
710                 MainWindow::show_session_error(errorMessage, infoMessage); });
711
712         set_name(QFileInfo(file_name).fileName());
713 }
714
715 Session::capture_state Session::get_capture_state() const
716 {
717         lock_guard<mutex> lock(sampling_mutex_);
718         return capture_state_;
719 }
720
721 void Session::start_capture(function<void (const QString)> error_handler)
722 {
723         if (!device_) {
724                 error_handler(tr("No active device set, can't start acquisition."));
725                 return;
726         }
727
728         stop_capture();
729
730         // Check that at least one channel is enabled
731         const shared_ptr<sigrok::Device> sr_dev = device_->device();
732         if (sr_dev) {
733                 const auto channels = sr_dev->channels();
734                 if (!any_of(channels.begin(), channels.end(),
735                         [](shared_ptr<Channel> channel) {
736                                 return channel->enabled(); })) {
737                         error_handler(tr("No channels enabled."));
738                         return;
739                 }
740         }
741
742         // Clear signal data
743         for (const shared_ptr<data::SignalData>& d : all_signal_data_)
744                 d->clear();
745
746         trigger_list_.clear();
747
748         // Revert name back to default name (e.g. "Session 1") for real devices
749         // as the (possibly saved) data is gone. File devices keep their name.
750         shared_ptr<devices::HardwareDevice> hw_device =
751                 dynamic_pointer_cast< devices::HardwareDevice >(device_);
752
753         if (hw_device) {
754                 name_ = default_name_;
755                 name_changed();
756         }
757
758         // Begin the session
759         sampling_thread_ = std::thread(
760                 &Session::sample_thread_proc, this, error_handler);
761 }
762
763 void Session::stop_capture()
764 {
765         if (get_capture_state() != Stopped)
766                 device_->stop();
767
768         // Check that sampling stopped
769         if (sampling_thread_.joinable())
770                 sampling_thread_.join();
771 }
772
773 void Session::register_view(shared_ptr<views::ViewBase> view)
774 {
775         if (views_.empty())
776                 main_view_ = view;
777
778         views_.push_back(view);
779
780         // Add all device signals
781         update_signals();
782
783         // Add all other signals
784         vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
785
786         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
787                 const int sb_exists = count_if(
788                         view_signalbases.cbegin(), view_signalbases.cend(),
789                         [&](const shared_ptr<data::SignalBase> &sb) {
790                                 return sb == signalbase;
791                         });
792
793                 // Add the signal to the view if it doesn't have it yet
794                 if (!sb_exists)
795                         switch (signalbase->type()) {
796                         case data::SignalBase::AnalogChannel:
797                         case data::SignalBase::LogicChannel:
798                         case data::SignalBase::MathChannel:
799                                 view->add_signalbase(signalbase);
800                                 break;
801                         case data::SignalBase::DecodeChannel:
802 #ifdef ENABLE_DECODE
803                                 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
804 #endif
805                                 break;
806                         }
807         }
808
809         signals_changed();
810 }
811
812 void Session::deregister_view(shared_ptr<views::ViewBase> view)
813 {
814         views_.erase(std::remove_if(views_.begin(), views_.end(),
815                 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
816                 views_.end());
817
818         if (views_.empty()) {
819                 main_view_.reset();
820
821                 // Without a view there can be no main bar
822                 main_bar_.reset();
823         }
824 }
825
826 bool Session::has_view(shared_ptr<views::ViewBase> view)
827 {
828         for (shared_ptr<views::ViewBase>& v : views_)
829                 if (v == view)
830                         return true;
831
832         return false;
833 }
834
835 double Session::get_samplerate() const
836 {
837         double samplerate = 0.0;
838
839         for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
840                 assert(d);
841                 const vector< shared_ptr<pv::data::Segment> > segments =
842                         d->segments();
843                 for (const shared_ptr<pv::data::Segment>& s : segments)
844                         samplerate = max(samplerate, s->samplerate());
845         }
846         // If there is no sample rate given we use samples as unit
847         if (samplerate == 0.0)
848                 samplerate = 1.0;
849
850         return samplerate;
851 }
852
853 uint32_t Session::get_segment_count() const
854 {
855         uint32_t value = 0;
856
857         // Find the highest number of segments
858         for (const shared_ptr<data::SignalData>& data : all_signal_data_)
859                 if (data->get_segment_count() > value)
860                         value = data->get_segment_count();
861
862         return value;
863 }
864
865 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
866 {
867         vector<util::Timestamp> result;
868
869         for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
870                 if (entry.first == segment_id)
871                         result.push_back(entry.second);
872
873         return result;
874 }
875
876 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
877 {
878         return signalbases_;
879 }
880
881 void Session::add_generated_signal(shared_ptr<data::SignalBase> signal)
882 {
883         signalbases_.push_back(signal);
884
885         for (shared_ptr<views::ViewBase>& view : views_)
886                 view->add_signalbase(signal);
887
888         update_signals();
889 }
890
891 void Session::remove_generated_signal(shared_ptr<data::SignalBase> signal)
892 {
893         if (shutting_down_)
894                 return;
895
896         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
897                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
898                 signalbases_.end());
899
900         for (shared_ptr<views::ViewBase>& view : views_)
901                 view->remove_signalbase(signal);
902
903         update_signals();
904 }
905
906 #ifdef ENABLE_DECODE
907 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
908 {
909         shared_ptr<data::DecodeSignal> signal;
910
911         try {
912                 // Create the decode signal
913                 signal = make_shared<data::DecodeSignal>(*this);
914
915                 signalbases_.push_back(signal);
916
917                 // Add the decode signal to all views
918                 for (shared_ptr<views::ViewBase>& view : views_)
919                         view->add_decode_signal(signal);
920         } catch (runtime_error& e) {
921                 remove_decode_signal(signal);
922                 return nullptr;
923         }
924
925         signals_changed();
926
927         return signal;
928 }
929
930 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
931 {
932         if (shutting_down_)
933                 return;
934
935         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
936                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
937                 signalbases_.end());
938
939         for (shared_ptr<views::ViewBase>& view : views_)
940                 view->remove_decode_signal(signal);
941
942         signals_changed();
943 }
944 #endif
945
946 bool Session::all_segments_complete(uint32_t segment_id) const
947 {
948         bool all_complete = true;
949
950         for (const shared_ptr<data::SignalBase>& base : signalbases_)
951                 if (!base->segment_is_complete(segment_id))
952                         all_complete = false;
953
954         return all_complete;
955 }
956
957 MetadataObjManager* Session::metadata_obj_manager()
958 {
959         return &metadata_obj_manager_;
960 }
961
962 void Session::set_capture_state(capture_state state)
963 {
964         bool changed;
965
966         if (state == Running)
967                 acq_time_.restart();
968         if (state == Stopped)
969                 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
970
971         {
972                 lock_guard<mutex> lock(sampling_mutex_);
973                 changed = capture_state_ != state;
974                 capture_state_ = state;
975         }
976
977         if (changed)
978                 capture_state_changed(state);
979 }
980
981 void Session::update_signals()
982 {
983         if (!device_) {
984                 signalbases_.clear();
985                 logic_data_.reset();
986                 for (shared_ptr<views::ViewBase>& view : views_) {
987                         view->clear_signalbases();
988 #ifdef ENABLE_DECODE
989                         view->clear_decode_signals();
990 #endif
991                 }
992                 return;
993         }
994
995         lock_guard<recursive_mutex> lock(data_mutex_);
996
997         const shared_ptr<sigrok::Device> sr_dev = device_->device();
998         if (!sr_dev) {
999                 signalbases_.clear();
1000                 logic_data_.reset();
1001                 for (shared_ptr<views::ViewBase>& view : views_) {
1002                         view->clear_signalbases();
1003 #ifdef ENABLE_DECODE
1004                         view->clear_decode_signals();
1005 #endif
1006                 }
1007                 return;
1008         }
1009
1010         // Detect what data types we will receive
1011         auto channels = sr_dev->channels();
1012         unsigned int logic_channel_count = count_if(
1013                 channels.begin(), channels.end(),
1014                 [] (shared_ptr<Channel> channel) {
1015                         return channel->type() == sigrok::ChannelType::LOGIC; });
1016
1017         // Create a common data container for the logic signalbases
1018         {
1019                 lock_guard<recursive_mutex> data_lock(data_mutex_);
1020
1021                 if (logic_channel_count == 0) {
1022                         logic_data_.reset();
1023                 } else if (!logic_data_ ||
1024                         logic_data_->num_channels() != logic_channel_count) {
1025                         logic_data_.reset(new data::Logic(logic_channel_count));
1026                         assert(logic_data_);
1027                 }
1028         }
1029
1030         // Create signalbases if necessary
1031         for (auto channel : sr_dev->channels()) {
1032
1033                 // Try to find the channel in the list of existing signalbases
1034                 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1035                         [&](const shared_ptr<SignalBase> &sb) { return sb->channel() == channel; });
1036
1037                 // Not found, let's make a signalbase for it
1038                 if (iter == signalbases_.cend()) {
1039                         shared_ptr<SignalBase> signalbase;
1040                         switch(channel->type()->id()) {
1041                         case SR_CHANNEL_LOGIC:
1042                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::LogicChannel);
1043                                 signalbases_.push_back(signalbase);
1044
1045                                 all_signal_data_.insert(logic_data_);
1046                                 signalbase->set_data(logic_data_);
1047
1048                                 connect(this, SIGNAL(capture_state_changed(int)),
1049                                         signalbase.get(), SLOT(on_capture_state_changed(int)));
1050                                 break;
1051
1052                         case SR_CHANNEL_ANALOG:
1053                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::AnalogChannel);
1054                                 signalbases_.push_back(signalbase);
1055
1056                                 shared_ptr<data::Analog> data(new data::Analog());
1057                                 all_signal_data_.insert(data);
1058                                 signalbase->set_data(data);
1059
1060                                 connect(this, SIGNAL(capture_state_changed(int)),
1061                                         signalbase.get(), SLOT(on_capture_state_changed(int)));
1062                                 break;
1063                         }
1064                 }
1065         }
1066
1067         // Create and assign default signal groups if needed
1068         if (signal_groups_.empty()) {
1069                 for (auto& entry : sr_dev->channel_groups()) {
1070                         const shared_ptr<sigrok::ChannelGroup>& group = entry.second;
1071
1072                         if (group->channels().size() <= 1)
1073                                 continue;
1074
1075                         SignalGroup* sg = new SignalGroup(QString::fromStdString(entry.first));
1076                         for (const shared_ptr<sigrok::Channel>& channel : group->channels()) {
1077                                 for (shared_ptr<data::SignalBase> s : signalbases_) {
1078                                         if (s->channel() == channel) {
1079                                                 sg->append_signal(s);
1080                                                 break;
1081                                         }
1082                                 }
1083                         }
1084                         signal_groups_.emplace_back(sg);
1085                 }
1086         }
1087
1088         // Update all views
1089         for (shared_ptr<views::ViewBase>& viewbase : views_) {
1090                 vector< shared_ptr<SignalBase> > view_signalbases =
1091                                 viewbase->signalbases();
1092
1093                 // Add all non-decode signalbases that don't yet exist in the view
1094                 for (shared_ptr<SignalBase>& session_sb : signalbases_) {
1095                         if (session_sb->type() == SignalBase::DecodeChannel)
1096                                 continue;
1097
1098                         const auto iter = find_if(view_signalbases.cbegin(), view_signalbases.cend(),
1099                                 [&](const shared_ptr<SignalBase> &sb) { return sb == session_sb; });
1100
1101                         if (iter == view_signalbases.cend())
1102                                 viewbase->add_signalbase(session_sb);
1103                 }
1104
1105                 // Remove all non-decode signalbases that no longer exist
1106                 for (shared_ptr<SignalBase>& view_sb : view_signalbases) {
1107                         if (view_sb->type() == SignalBase::DecodeChannel)
1108                                 continue;
1109
1110                         const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1111                                 [&](const shared_ptr<SignalBase> &sb) { return sb == view_sb; });
1112
1113                         if (iter == signalbases_.cend())
1114                                 viewbase->remove_signalbase(view_sb);
1115                 }
1116         }
1117
1118         signals_changed();
1119 }
1120
1121 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1122         shared_ptr<sigrok::Channel> channel) const
1123 {
1124         for (shared_ptr<data::SignalBase> sig : signalbases_) {
1125                 assert(sig);
1126                 if (sig->channel() == channel)
1127                         return sig;
1128         }
1129         return shared_ptr<data::SignalBase>();
1130 }
1131
1132 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1133 {
1134         assert(error_handler);
1135
1136 #ifdef ENABLE_FLOW
1137         pipeline_ = Pipeline::create();
1138
1139         source_ = ElementFactory::create_element("filesrc", "source");
1140         sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1141
1142         pipeline_->add(source_)->add(sink_);
1143         source_->link(sink_);
1144
1145         source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1146
1147         sink_->set_property("emit-signals", TRUE);
1148         sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1149
1150         // Get the bus from the pipeline and add a bus watch to the default main context
1151         RefPtr<Bus> bus = pipeline_->get_bus();
1152         bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1153
1154         // Start pipeline and Wait until it finished processing
1155         pipeline_done_interrupt_ = false;
1156         pipeline_->set_state(Gst::STATE_PLAYING);
1157
1158         unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1159         pipeline_done_cond_.wait(pipeline_done_lock_);
1160
1161         // Let the pipeline free all resources
1162         pipeline_->set_state(Gst::STATE_NULL);
1163
1164 #else
1165         if (!device_)
1166                 return;
1167
1168         try {
1169                 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1170         } catch (Error& e) {
1171                 cur_samplerate_ = 0;
1172         }
1173
1174         out_of_memory_ = false;
1175
1176         {
1177                 lock_guard<recursive_mutex> lock(data_mutex_);
1178                 cur_logic_segment_.reset();
1179                 cur_analog_segments_.clear();
1180                 for (shared_ptr<data::SignalBase> sb : signalbases_)
1181                         sb->clear_sample_data();
1182         }
1183         highest_segment_id_ = -1;
1184         frame_began_ = false;
1185
1186         try {
1187                 device_->start();
1188         } catch (Error& e) {
1189                 error_handler(e.what());
1190                 return;
1191         }
1192
1193         set_capture_state(device_->session()->trigger() ?
1194                 AwaitingTrigger : Running);
1195
1196         try {
1197                 device_->run();
1198         } catch (Error& e) {
1199                 error_handler(e.what());
1200                 set_capture_state(Stopped);
1201                 return;
1202         } catch (QString& e) {
1203                 error_handler(e);
1204                 set_capture_state(Stopped);
1205                 return;
1206         }
1207
1208         set_capture_state(Stopped);
1209
1210         // Confirm that SR_DF_END was received
1211         if (cur_logic_segment_)
1212                 qDebug() << "WARNING: SR_DF_END was not received.";
1213 #endif
1214
1215         // Optimize memory usage
1216         free_unused_memory();
1217
1218         // We now have unsaved data unless we just "captured" from a file
1219         shared_ptr<devices::File> file_device =
1220                 dynamic_pointer_cast<devices::File>(device_);
1221
1222         if (!file_device)
1223                 data_saved_ = false;
1224
1225         if (out_of_memory_)
1226                 error_handler(tr("Out of memory, acquisition stopped."));
1227 }
1228
1229 void Session::free_unused_memory()
1230 {
1231         for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1232                 const vector< shared_ptr<data::Segment> > segments = data->segments();
1233
1234                 for (const shared_ptr<data::Segment>& segment : segments)
1235                         segment->free_unused_memory();
1236         }
1237 }
1238
1239 void Session::signal_new_segment()
1240 {
1241         int new_segment_id = 0;
1242
1243         if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1244
1245                 // Determine new frame/segment number, assuming that all
1246                 // signals have the same number of frames/segments
1247                 if (cur_logic_segment_) {
1248                         new_segment_id = logic_data_->get_segment_count() - 1;
1249                 } else {
1250                         shared_ptr<sigrok::Channel> any_channel =
1251                                 (*cur_analog_segments_.begin()).first;
1252
1253                         shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1254                         assert(base);
1255
1256                         shared_ptr<data::Analog> data(base->analog_data());
1257                         assert(data);
1258
1259                         new_segment_id = data->get_segment_count() - 1;
1260                 }
1261         }
1262
1263         if (new_segment_id > highest_segment_id_) {
1264                 highest_segment_id_ = new_segment_id;
1265                 new_segment(highest_segment_id_);
1266         }
1267 }
1268
1269 void Session::signal_segment_completed()
1270 {
1271         int segment_id = 0;
1272
1273         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1274                 // We only care about analog and logic channels, not derived ones
1275                 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1276                         segment_id = signalbase->analog_data()->get_segment_count() - 1;
1277                         break;
1278                 }
1279
1280                 if (signalbase->type() == data::SignalBase::LogicChannel) {
1281                         segment_id = signalbase->logic_data()->get_segment_count() - 1;
1282                         break;
1283                 }
1284         }
1285
1286         if (segment_id >= 0)
1287                 segment_completed(segment_id);
1288 }
1289
1290 #ifdef ENABLE_FLOW
1291 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1292 {
1293         (void)bus;
1294
1295         if ((message->get_source() == pipeline_) && \
1296                 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1297                 pipeline_done_cond_.notify_one();
1298
1299         // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1300
1301         return true;
1302 }
1303
1304 Gst::FlowReturn Session::on_gst_new_sample()
1305 {
1306         RefPtr<Gst::Sample> sample = sink_->pull_sample();
1307         RefPtr<Gst::Buffer> buf = sample->get_buffer();
1308
1309         for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1310                 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1311                 Gst::MapInfo mapinfo;
1312                 buf_mem->map(mapinfo, Gst::MAP_READ);
1313
1314                 shared_ptr<sigrok::Packet> logic_packet =
1315                         sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1316
1317                 try {
1318                         feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1319                 } catch (bad_alloc&) {
1320                         out_of_memory_ = true;
1321                         device_->stop();
1322                         buf_mem->unmap(mapinfo);
1323                         return Gst::FLOW_ERROR;
1324                 }
1325
1326                 buf_mem->unmap(mapinfo);
1327         }
1328
1329         return Gst::FLOW_OK;
1330 }
1331 #endif
1332
1333 void Session::feed_in_header()
1334 {
1335         // Nothing to do here for now
1336 }
1337
1338 void Session::feed_in_meta(shared_ptr<Meta> meta)
1339 {
1340         for (auto& entry : meta->config()) {
1341                 switch (entry.first->id()) {
1342                 case SR_CONF_SAMPLERATE:
1343                         cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1344                         break;
1345                 default:
1346                         qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1347                         break;
1348                 }
1349         }
1350
1351         signals_changed();
1352 }
1353
1354 void Session::feed_in_trigger()
1355 {
1356         // The channel containing most samples should be most accurate
1357         uint64_t sample_count = 0;
1358
1359         {
1360                 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1361                         assert(d);
1362                         uint64_t temp_count = 0;
1363
1364                         const vector< shared_ptr<pv::data::Segment> > segments =
1365                                 d->segments();
1366                         for (const shared_ptr<pv::data::Segment> &s : segments)
1367                                 temp_count += s->get_sample_count();
1368
1369                         if (temp_count > sample_count)
1370                                 sample_count = temp_count;
1371                 }
1372         }
1373
1374         uint32_t segment_id = 0;  // Default segment when no frames are used
1375
1376         // If a frame began, we'd ideally be able to use the highest segment ID for
1377         // the trigger. However, as new segments are only created when logic or
1378         // analog data comes in, this doesn't work if the trigger appears right
1379         // after the beginning of the frame, before any sample data.
1380         // For this reason, we use highest segment ID + 1 if no sample data came in
1381         // yet and the highest segment ID otherwise.
1382         if (frame_began_) {
1383                 segment_id = highest_segment_id_;
1384                 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1385                         segment_id++;
1386         }
1387
1388         // TODO Create timestamp from segment start time + segment's current sample count
1389         util::Timestamp timestamp = sample_count / get_samplerate();
1390         trigger_list_.emplace_back(segment_id, timestamp);
1391         trigger_event(segment_id, timestamp);
1392 }
1393
1394 void Session::feed_in_frame_begin()
1395 {
1396         frame_began_ = true;
1397 }
1398
1399 void Session::feed_in_frame_end()
1400 {
1401         if (!frame_began_)
1402                 return;
1403
1404         {
1405                 lock_guard<recursive_mutex> lock(data_mutex_);
1406
1407                 if (cur_logic_segment_)
1408                         cur_logic_segment_->set_complete();
1409
1410                 for (auto& entry : cur_analog_segments_) {
1411                         shared_ptr<data::AnalogSegment> segment = entry.second;
1412                         segment->set_complete();
1413                 }
1414
1415                 cur_logic_segment_.reset();
1416                 cur_analog_segments_.clear();
1417         }
1418
1419         frame_began_ = false;
1420
1421         signal_segment_completed();
1422 }
1423
1424 void Session::feed_in_logic(shared_ptr<sigrok::Logic> logic)
1425 {
1426         if (logic->data_length() == 0) {
1427                 qDebug() << "WARNING: Received logic packet with 0 samples.";
1428                 return;
1429         }
1430
1431         if (logic->unit_size() > 8)
1432                 throw QString(tr("Can't handle more than 64 logic channels."));
1433
1434         if (!cur_samplerate_)
1435                 try {
1436                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1437                 } catch (Error& e) {
1438                         // Do nothing
1439                 }
1440
1441         lock_guard<recursive_mutex> lock(data_mutex_);
1442
1443         if (!logic_data_) {
1444                 // The only reason logic_data_ would not have been created is
1445                 // if it was not possible to determine the signals when the
1446                 // device was created.
1447                 update_signals();
1448         }
1449
1450         if (!cur_logic_segment_) {
1451                 // This could be the first packet after a trigger
1452                 set_capture_state(Running);
1453
1454                 // Create a new data segment
1455                 cur_logic_segment_ = make_shared<data::LogicSegment>(
1456                         *logic_data_, logic_data_->get_segment_count(),
1457                         logic->unit_size(), cur_samplerate_);
1458                 logic_data_->push_segment(cur_logic_segment_);
1459
1460                 signal_new_segment();
1461         }
1462
1463         cur_logic_segment_->append_payload(logic);
1464
1465         data_received();
1466 }
1467
1468 void Session::feed_in_analog(shared_ptr<sigrok::Analog> analog)
1469 {
1470         if (analog->num_samples() == 0) {
1471                 qDebug() << "WARNING: Received analog packet with 0 samples.";
1472                 return;
1473         }
1474
1475         if (!cur_samplerate_)
1476                 try {
1477                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1478                 } catch (Error& e) {
1479                         // Do nothing
1480                 }
1481
1482         lock_guard<recursive_mutex> lock(data_mutex_);
1483
1484         const vector<shared_ptr<Channel>> channels = analog->channels();
1485         bool sweep_beginning = false;
1486
1487         unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1488         analog->get_data_as_float(data.get());
1489
1490         if (signalbases_.empty())
1491                 update_signals();
1492
1493         float *channel_data = data.get();
1494         for (auto& channel : channels) {
1495                 shared_ptr<data::AnalogSegment> segment;
1496
1497                 // Try to get the segment of the channel
1498                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1499                         iterator iter = cur_analog_segments_.find(channel);
1500                 if (iter != cur_analog_segments_.end())
1501                         segment = (*iter).second;
1502                 else {
1503                         // If no segment was found, this means we haven't
1504                         // created one yet. i.e. this is the first packet
1505                         // in the sweep containing this segment.
1506                         sweep_beginning = true;
1507
1508                         // Find the analog data associated with the channel
1509                         shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1510                         assert(base);
1511
1512                         shared_ptr<data::Analog> data(base->analog_data());
1513                         assert(data);
1514
1515                         // Create a segment, keep it in the maps of channels
1516                         segment = make_shared<data::AnalogSegment>(
1517                                 *data, data->get_segment_count(), cur_samplerate_);
1518                         cur_analog_segments_[channel] = segment;
1519
1520                         // Push the segment into the analog data.
1521                         data->push_segment(segment);
1522
1523                         signal_new_segment();
1524                 }
1525
1526                 assert(segment);
1527
1528                 // Append the samples in the segment
1529                 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1530                         channels.size());
1531         }
1532
1533         if (sweep_beginning) {
1534                 // This could be the first packet after a trigger
1535                 set_capture_state(Running);
1536         }
1537
1538         data_received();
1539 }
1540
1541 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1542         shared_ptr<Packet> packet)
1543 {
1544         (void)device;
1545
1546         assert(device);
1547         assert(device == device_->device());
1548         assert(packet);
1549
1550         switch (packet->type()->id()) {
1551         case SR_DF_HEADER:
1552                 feed_in_header();
1553                 break;
1554
1555         case SR_DF_META:
1556                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1557                 break;
1558
1559         case SR_DF_TRIGGER:
1560                 feed_in_trigger();
1561                 break;
1562
1563         case SR_DF_LOGIC:
1564                 try {
1565                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1566                 } catch (bad_alloc&) {
1567                         out_of_memory_ = true;
1568                         device_->stop();
1569                 }
1570                 break;
1571
1572         case SR_DF_ANALOG:
1573                 try {
1574                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1575                 } catch (bad_alloc&) {
1576                         out_of_memory_ = true;
1577                         device_->stop();
1578                 }
1579                 break;
1580
1581         case SR_DF_FRAME_BEGIN:
1582                 feed_in_frame_begin();
1583                 break;
1584
1585         case SR_DF_FRAME_END:
1586                 feed_in_frame_end();
1587                 break;
1588
1589         case SR_DF_END:
1590                 // Strictly speaking, this is performed when a frame end marker was
1591                 // received, so there's no point doing this again. However, not all
1592                 // devices use frames, and for those devices, we need to do it here.
1593                 {
1594                         lock_guard<recursive_mutex> lock(data_mutex_);
1595
1596                         if (cur_logic_segment_)
1597                                 cur_logic_segment_->set_complete();
1598
1599                         for (auto& entry : cur_analog_segments_) {
1600                                 shared_ptr<data::AnalogSegment> segment = entry.second;
1601                                 segment->set_complete();
1602                         }
1603
1604                         cur_logic_segment_.reset();
1605                         cur_analog_segments_.clear();
1606                 }
1607                 break;
1608
1609         default:
1610                 break;
1611         }
1612 }
1613
1614 void Session::on_data_saved()
1615 {
1616         data_saved_ = true;
1617 }
1618
1619 #ifdef ENABLE_DECODE
1620 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1621 {
1622         assert(decoders.size() > 0);
1623
1624         shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1625
1626         if (signal)
1627                 for (unsigned int i = 0; i < decoders.size(); i++) {
1628                         const srd_decoder* d = decoders[i];
1629                         signal->stack_decoder(d, !(i < decoders.size() - 1));
1630                 }
1631 }
1632 #endif
1633
1634 } // namespace pv