]> sigrok.org Git - pulseview.git/blob - pv/session.cpp
Add metadata object handling
[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_signals();
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 bool Session::all_segments_complete(uint32_t segment_id) const
861 {
862         bool all_complete = true;
863
864         for (const shared_ptr<data::SignalBase>& base : signalbases_)
865                 if (!base->segment_is_complete(segment_id))
866                         all_complete = false;
867
868         return all_complete;
869 }
870
871 #ifdef ENABLE_DECODE
872 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
873 {
874         shared_ptr<data::DecodeSignal> signal;
875
876         try {
877                 // Create the decode signal
878                 signal = make_shared<data::DecodeSignal>(*this);
879
880                 signalbases_.push_back(signal);
881
882                 // Add the decode signal to all views
883                 for (shared_ptr<views::ViewBase>& view : views_)
884                         view->add_decode_signal(signal);
885         } catch (runtime_error& e) {
886                 remove_decode_signal(signal);
887                 return nullptr;
888         }
889
890         signals_changed();
891
892         return signal;
893 }
894
895 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
896 {
897         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
898                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
899                 signalbases_.end());
900
901         for (shared_ptr<views::ViewBase>& view : views_)
902                 view->remove_decode_signal(signal);
903
904         signals_changed();
905 }
906 #endif
907
908 MetadataObjManager* Session::metadata_obj_manager()
909 {
910         return &metadata_obj_manager_;
911 }
912
913 void Session::set_capture_state(capture_state state)
914 {
915         bool changed;
916
917         if (state == Running)
918                 acq_time_.restart();
919         if (state == Stopped)
920                 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
921
922         {
923                 lock_guard<mutex> lock(sampling_mutex_);
924                 changed = capture_state_ != state;
925                 capture_state_ = state;
926         }
927
928         if (changed)
929                 capture_state_changed(state);
930 }
931
932 void Session::update_signals()
933 {
934         if (!device_) {
935                 signalbases_.clear();
936                 logic_data_.reset();
937                 for (shared_ptr<views::ViewBase>& view : views_) {
938                         view->clear_signals();
939 #ifdef ENABLE_DECODE
940                         view->clear_decode_signals();
941 #endif
942                 }
943                 return;
944         }
945
946         lock_guard<recursive_mutex> lock(data_mutex_);
947
948         const shared_ptr<sigrok::Device> sr_dev = device_->device();
949         if (!sr_dev) {
950                 signalbases_.clear();
951                 logic_data_.reset();
952                 for (shared_ptr<views::ViewBase>& view : views_) {
953                         view->clear_signals();
954 #ifdef ENABLE_DECODE
955                         view->clear_decode_signals();
956 #endif
957                 }
958                 return;
959         }
960
961         // Detect what data types we will receive
962         auto channels = sr_dev->channels();
963         unsigned int logic_channel_count = count_if(
964                 channels.begin(), channels.end(),
965                 [] (shared_ptr<Channel> channel) {
966                         return channel->type() == sigrok::ChannelType::LOGIC; });
967
968         // Create data containers for the logic data segments
969         {
970                 lock_guard<recursive_mutex> data_lock(data_mutex_);
971
972                 if (logic_channel_count == 0) {
973                         logic_data_.reset();
974                 } else if (!logic_data_ ||
975                         logic_data_->num_channels() != logic_channel_count) {
976                         logic_data_.reset(new data::Logic(
977                                 logic_channel_count));
978                         assert(logic_data_);
979                 }
980         }
981
982         // Make the signals list
983         for (shared_ptr<views::ViewBase>& viewbase : views_) {
984                 views::trace::View *trace_view =
985                         qobject_cast<views::trace::View*>(viewbase.get());
986
987                 if (trace_view) {
988                         vector< shared_ptr<Signal> > prev_sigs(trace_view->signals());
989                         trace_view->clear_signals();
990
991                         for (auto channel : sr_dev->channels()) {
992                                 shared_ptr<data::SignalBase> signalbase;
993                                 shared_ptr<Signal> signal;
994
995                                 // Find the channel in the old signals
996                                 const auto iter = find_if(
997                                         prev_sigs.cbegin(), prev_sigs.cend(),
998                                         [&](const shared_ptr<Signal> &s) {
999                                                 return s->base()->channel() == channel;
1000                                         });
1001                                 if (iter != prev_sigs.end()) {
1002                                         // Copy the signal from the old set to the new
1003                                         signal = *iter;
1004                                         trace_view->add_signal(signal);
1005                                 } else {
1006                                         // Find the signalbase for this channel if possible
1007                                         signalbase.reset();
1008                                         for (const shared_ptr<data::SignalBase>& b : signalbases_)
1009                                                 if (b->channel() == channel)
1010                                                         signalbase = b;
1011
1012                                         shared_ptr<Signal> signal;
1013
1014                                         switch(channel->type()->id()) {
1015                                         case SR_CHANNEL_LOGIC:
1016                                                 if (!signalbase) {
1017                                                         signalbase = make_shared<data::SignalBase>(channel,
1018                                                                 data::SignalBase::LogicChannel);
1019                                                         signalbases_.push_back(signalbase);
1020
1021                                                         all_signal_data_.insert(logic_data_);
1022                                                         signalbase->set_data(logic_data_);
1023
1024                                                         connect(this, SIGNAL(capture_state_changed(int)),
1025                                                                 signalbase.get(), SLOT(on_capture_state_changed(int)));
1026                                                 }
1027
1028                                                 signal = shared_ptr<Signal>(new LogicSignal(*this, device_, signalbase));
1029                                                 break;
1030
1031                                         case SR_CHANNEL_ANALOG:
1032                                         {
1033                                                 if (!signalbase) {
1034                                                         signalbase = make_shared<data::SignalBase>(channel,
1035                                                                 data::SignalBase::AnalogChannel);
1036                                                         signalbases_.push_back(signalbase);
1037
1038                                                         shared_ptr<data::Analog> data(new data::Analog());
1039                                                         all_signal_data_.insert(data);
1040                                                         signalbase->set_data(data);
1041
1042                                                         connect(this, SIGNAL(capture_state_changed(int)),
1043                                                                 signalbase.get(), SLOT(on_capture_state_changed(int)));
1044                                                 }
1045
1046                                                 signal = shared_ptr<Signal>(new AnalogSignal(*this, signalbase));
1047                                                 break;
1048                                         }
1049
1050                                         default:
1051                                                 assert(false);
1052                                                 break;
1053                                         }
1054
1055                                         // New views take their signal settings from the main view
1056                                         if (!viewbase->is_main_view()) {
1057                                                 shared_ptr<pv::views::trace::View> main_tv =
1058                                                         dynamic_pointer_cast<pv::views::trace::View>(main_view_);
1059                                                 shared_ptr<Signal> main_signal =
1060                                                         main_tv->get_signal_by_signalbase(signalbase);
1061                                                 signal->restore_settings(main_signal->save_settings());
1062                                         }
1063
1064                                         trace_view->add_signal(signal);
1065                                 }
1066                         }
1067                 }
1068         }
1069
1070         signals_changed();
1071 }
1072
1073 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1074         shared_ptr<sigrok::Channel> channel) const
1075 {
1076         for (shared_ptr<data::SignalBase> sig : signalbases_) {
1077                 assert(sig);
1078                 if (sig->channel() == channel)
1079                         return sig;
1080         }
1081         return shared_ptr<data::SignalBase>();
1082 }
1083
1084 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1085 {
1086         assert(error_handler);
1087
1088 #ifdef ENABLE_FLOW
1089         pipeline_ = Pipeline::create();
1090
1091         source_ = ElementFactory::create_element("filesrc", "source");
1092         sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1093
1094         pipeline_->add(source_)->add(sink_);
1095         source_->link(sink_);
1096
1097         source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1098
1099         sink_->set_property("emit-signals", TRUE);
1100         sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1101
1102         // Get the bus from the pipeline and add a bus watch to the default main context
1103         RefPtr<Bus> bus = pipeline_->get_bus();
1104         bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1105
1106         // Start pipeline and Wait until it finished processing
1107         pipeline_done_interrupt_ = false;
1108         pipeline_->set_state(Gst::STATE_PLAYING);
1109
1110         unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1111         pipeline_done_cond_.wait(pipeline_done_lock_);
1112
1113         // Let the pipeline free all resources
1114         pipeline_->set_state(Gst::STATE_NULL);
1115
1116 #else
1117         if (!device_)
1118                 return;
1119
1120         try {
1121                 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1122         } catch (Error& e) {
1123                 cur_samplerate_ = 0;
1124         }
1125
1126         out_of_memory_ = false;
1127
1128         {
1129                 lock_guard<recursive_mutex> lock(data_mutex_);
1130                 cur_logic_segment_.reset();
1131                 cur_analog_segments_.clear();
1132         }
1133         highest_segment_id_ = -1;
1134         frame_began_ = false;
1135
1136         try {
1137                 device_->start();
1138         } catch (Error& e) {
1139                 error_handler(e.what());
1140                 return;
1141         }
1142
1143         set_capture_state(device_->session()->trigger() ?
1144                 AwaitingTrigger : Running);
1145
1146         try {
1147                 device_->run();
1148         } catch (Error& e) {
1149                 error_handler(e.what());
1150                 set_capture_state(Stopped);
1151                 return;
1152         } catch (QString& e) {
1153                 error_handler(e);
1154                 set_capture_state(Stopped);
1155                 return;
1156         }
1157
1158         set_capture_state(Stopped);
1159
1160         // Confirm that SR_DF_END was received
1161         if (cur_logic_segment_)
1162                 qDebug() << "WARNING: SR_DF_END was not received.";
1163 #endif
1164
1165         // Optimize memory usage
1166         free_unused_memory();
1167
1168         // We now have unsaved data unless we just "captured" from a file
1169         shared_ptr<devices::File> file_device =
1170                 dynamic_pointer_cast<devices::File>(device_);
1171
1172         if (!file_device)
1173                 data_saved_ = false;
1174
1175         if (out_of_memory_)
1176                 error_handler(tr("Out of memory, acquisition stopped."));
1177 }
1178
1179 void Session::free_unused_memory()
1180 {
1181         for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1182                 const vector< shared_ptr<data::Segment> > segments = data->segments();
1183
1184                 for (const shared_ptr<data::Segment>& segment : segments)
1185                         segment->free_unused_memory();
1186         }
1187 }
1188
1189 void Session::signal_new_segment()
1190 {
1191         int new_segment_id = 0;
1192
1193         if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1194
1195                 // Determine new frame/segment number, assuming that all
1196                 // signals have the same number of frames/segments
1197                 if (cur_logic_segment_) {
1198                         new_segment_id = logic_data_->get_segment_count() - 1;
1199                 } else {
1200                         shared_ptr<sigrok::Channel> any_channel =
1201                                 (*cur_analog_segments_.begin()).first;
1202
1203                         shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1204                         assert(base);
1205
1206                         shared_ptr<data::Analog> data(base->analog_data());
1207                         assert(data);
1208
1209                         new_segment_id = data->get_segment_count() - 1;
1210                 }
1211         }
1212
1213         if (new_segment_id > highest_segment_id_) {
1214                 highest_segment_id_ = new_segment_id;
1215                 new_segment(highest_segment_id_);
1216         }
1217 }
1218
1219 void Session::signal_segment_completed()
1220 {
1221         int segment_id = 0;
1222
1223         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1224                 // We only care about analog and logic channels, not derived ones
1225                 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1226                         segment_id = signalbase->analog_data()->get_segment_count() - 1;
1227                         break;
1228                 }
1229
1230                 if (signalbase->type() == data::SignalBase::LogicChannel) {
1231                         segment_id = signalbase->logic_data()->get_segment_count() - 1;
1232                         break;
1233                 }
1234         }
1235
1236         if (segment_id >= 0)
1237                 segment_completed(segment_id);
1238 }
1239
1240 #ifdef ENABLE_FLOW
1241 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1242 {
1243         (void)bus;
1244
1245         if ((message->get_source() == pipeline_) && \
1246                 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1247                 pipeline_done_cond_.notify_one();
1248
1249         // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1250
1251         return true;
1252 }
1253
1254 Gst::FlowReturn Session::on_gst_new_sample()
1255 {
1256         RefPtr<Gst::Sample> sample = sink_->pull_sample();
1257         RefPtr<Gst::Buffer> buf = sample->get_buffer();
1258
1259         for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1260                 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1261                 Gst::MapInfo mapinfo;
1262                 buf_mem->map(mapinfo, Gst::MAP_READ);
1263
1264                 shared_ptr<sigrok::Packet> logic_packet =
1265                         sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1266
1267                 try {
1268                         feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1269                 } catch (bad_alloc&) {
1270                         out_of_memory_ = true;
1271                         device_->stop();
1272                         buf_mem->unmap(mapinfo);
1273                         return Gst::FLOW_ERROR;
1274                 }
1275
1276                 buf_mem->unmap(mapinfo);
1277         }
1278
1279         return Gst::FLOW_OK;
1280 }
1281 #endif
1282
1283 void Session::feed_in_header()
1284 {
1285         // Nothing to do here for now
1286 }
1287
1288 void Session::feed_in_meta(shared_ptr<Meta> meta)
1289 {
1290         for (auto& entry : meta->config()) {
1291                 switch (entry.first->id()) {
1292                 case SR_CONF_SAMPLERATE:
1293                         cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1294                         break;
1295                 default:
1296                         qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1297                         break;
1298                 }
1299         }
1300
1301         signals_changed();
1302 }
1303
1304 void Session::feed_in_trigger()
1305 {
1306         // The channel containing most samples should be most accurate
1307         uint64_t sample_count = 0;
1308
1309         {
1310                 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1311                         assert(d);
1312                         uint64_t temp_count = 0;
1313
1314                         const vector< shared_ptr<pv::data::Segment> > segments =
1315                                 d->segments();
1316                         for (const shared_ptr<pv::data::Segment> &s : segments)
1317                                 temp_count += s->get_sample_count();
1318
1319                         if (temp_count > sample_count)
1320                                 sample_count = temp_count;
1321                 }
1322         }
1323
1324         uint32_t segment_id = 0;  // Default segment when no frames are used
1325
1326         // If a frame began, we'd ideally be able to use the highest segment ID for
1327         // the trigger. However, as new segments are only created when logic or
1328         // analog data comes in, this doesn't work if the trigger appears right
1329         // after the beginning of the frame, before any sample data.
1330         // For this reason, we use highest segment ID + 1 if no sample data came in
1331         // yet and the highest segment ID otherwise.
1332         if (frame_began_) {
1333                 segment_id = highest_segment_id_;
1334                 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1335                         segment_id++;
1336         }
1337
1338         // TODO Create timestamp from segment start time + segment's current sample count
1339         util::Timestamp timestamp = sample_count / get_samplerate();
1340         trigger_list_.emplace_back(segment_id, timestamp);
1341         trigger_event(segment_id, timestamp);
1342 }
1343
1344 void Session::feed_in_frame_begin()
1345 {
1346         frame_began_ = true;
1347 }
1348
1349 void Session::feed_in_frame_end()
1350 {
1351         if (!frame_began_)
1352                 return;
1353
1354         {
1355                 lock_guard<recursive_mutex> lock(data_mutex_);
1356
1357                 if (cur_logic_segment_)
1358                         cur_logic_segment_->set_complete();
1359
1360                 for (auto& entry : cur_analog_segments_) {
1361                         shared_ptr<data::AnalogSegment> segment = entry.second;
1362                         segment->set_complete();
1363                 }
1364
1365                 cur_logic_segment_.reset();
1366                 cur_analog_segments_.clear();
1367         }
1368
1369         frame_began_ = false;
1370
1371         signal_segment_completed();
1372 }
1373
1374 void Session::feed_in_logic(shared_ptr<Logic> logic)
1375 {
1376         if (logic->data_length() == 0) {
1377                 qDebug() << "WARNING: Received logic packet with 0 samples.";
1378                 return;
1379         }
1380
1381         if (logic->unit_size() > 8)
1382                 throw QString(tr("Can't handle more than 64 logic channels."));
1383
1384         if (!cur_samplerate_)
1385                 try {
1386                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1387                 } catch (Error& e) {
1388                         // Do nothing
1389                 }
1390
1391         lock_guard<recursive_mutex> lock(data_mutex_);
1392
1393         if (!logic_data_) {
1394                 // The only reason logic_data_ would not have been created is
1395                 // if it was not possible to determine the signals when the
1396                 // device was created.
1397                 update_signals();
1398         }
1399
1400         if (!cur_logic_segment_) {
1401                 // This could be the first packet after a trigger
1402                 set_capture_state(Running);
1403
1404                 // Create a new data segment
1405                 cur_logic_segment_ = make_shared<data::LogicSegment>(
1406                         *logic_data_, logic_data_->get_segment_count(),
1407                         logic->unit_size(), cur_samplerate_);
1408                 logic_data_->push_segment(cur_logic_segment_);
1409
1410                 signal_new_segment();
1411         }
1412
1413         cur_logic_segment_->append_payload(logic);
1414
1415         data_received();
1416 }
1417
1418 void Session::feed_in_analog(shared_ptr<Analog> analog)
1419 {
1420         if (analog->num_samples() == 0) {
1421                 qDebug() << "WARNING: Received analog packet with 0 samples.";
1422                 return;
1423         }
1424
1425         if (!cur_samplerate_)
1426                 try {
1427                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1428                 } catch (Error& e) {
1429                         // Do nothing
1430                 }
1431
1432         lock_guard<recursive_mutex> lock(data_mutex_);
1433
1434         const vector<shared_ptr<Channel>> channels = analog->channels();
1435         bool sweep_beginning = false;
1436
1437         unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1438         analog->get_data_as_float(data.get());
1439
1440         if (signalbases_.empty())
1441                 update_signals();
1442
1443         float *channel_data = data.get();
1444         for (auto& channel : channels) {
1445                 shared_ptr<data::AnalogSegment> segment;
1446
1447                 // Try to get the segment of the channel
1448                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1449                         iterator iter = cur_analog_segments_.find(channel);
1450                 if (iter != cur_analog_segments_.end())
1451                         segment = (*iter).second;
1452                 else {
1453                         // If no segment was found, this means we haven't
1454                         // created one yet. i.e. this is the first packet
1455                         // in the sweep containing this segment.
1456                         sweep_beginning = true;
1457
1458                         // Find the analog data associated with the channel
1459                         shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1460                         assert(base);
1461
1462                         shared_ptr<data::Analog> data(base->analog_data());
1463                         assert(data);
1464
1465                         // Create a segment, keep it in the maps of channels
1466                         segment = make_shared<data::AnalogSegment>(
1467                                 *data, data->get_segment_count(), cur_samplerate_);
1468                         cur_analog_segments_[channel] = segment;
1469
1470                         // Push the segment into the analog data.
1471                         data->push_segment(segment);
1472
1473                         signal_new_segment();
1474                 }
1475
1476                 assert(segment);
1477
1478                 // Append the samples in the segment
1479                 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1480                         channels.size());
1481         }
1482
1483         if (sweep_beginning) {
1484                 // This could be the first packet after a trigger
1485                 set_capture_state(Running);
1486         }
1487
1488         data_received();
1489 }
1490
1491 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1492         shared_ptr<Packet> packet)
1493 {
1494         (void)device;
1495
1496         assert(device);
1497         assert(device == device_->device());
1498         assert(packet);
1499
1500         switch (packet->type()->id()) {
1501         case SR_DF_HEADER:
1502                 feed_in_header();
1503                 break;
1504
1505         case SR_DF_META:
1506                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1507                 break;
1508
1509         case SR_DF_TRIGGER:
1510                 feed_in_trigger();
1511                 break;
1512
1513         case SR_DF_LOGIC:
1514                 try {
1515                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1516                 } catch (bad_alloc&) {
1517                         out_of_memory_ = true;
1518                         device_->stop();
1519                 }
1520                 break;
1521
1522         case SR_DF_ANALOG:
1523                 try {
1524                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1525                 } catch (bad_alloc&) {
1526                         out_of_memory_ = true;
1527                         device_->stop();
1528                 }
1529                 break;
1530
1531         case SR_DF_FRAME_BEGIN:
1532                 feed_in_frame_begin();
1533                 break;
1534
1535         case SR_DF_FRAME_END:
1536                 feed_in_frame_end();
1537                 break;
1538
1539         case SR_DF_END:
1540                 // Strictly speaking, this is performed when a frame end marker was
1541                 // received, so there's no point doing this again. However, not all
1542                 // devices use frames, and for those devices, we need to do it here.
1543                 {
1544                         lock_guard<recursive_mutex> lock(data_mutex_);
1545
1546                         if (cur_logic_segment_)
1547                                 cur_logic_segment_->set_complete();
1548
1549                         for (auto& entry : cur_analog_segments_) {
1550                                 shared_ptr<data::AnalogSegment> segment = entry.second;
1551                                 segment->set_complete();
1552                         }
1553
1554                         cur_logic_segment_.reset();
1555                         cur_analog_segments_.clear();
1556                 }
1557                 break;
1558
1559         default:
1560                 break;
1561         }
1562 }
1563
1564 void Session::on_data_saved()
1565 {
1566         data_saved_ = true;
1567 }
1568
1569 #ifdef ENABLE_DECODE
1570 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1571 {
1572         assert(decoders.size() > 0);
1573
1574         shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1575
1576         if (signal)
1577                 for (unsigned int i = 0; i < decoders.size(); i++) {
1578                         const srd_decoder* d = decoders[i];
1579                         signal->stack_decoder(d, !(i < decoders.size() - 1));
1580                 }
1581 }
1582 #endif
1583
1584 } // namespace pv