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