SignalBase: Add SignalGroup class and handling
[pulseview.git] / pv / session.cpp
blob9ec8bd07264036e85c052c05695749f4bccf797b
1 /*
2 * This file is part of the PulseView project.
4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
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.
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.
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/>.
20 #include <cassert>
21 #include <memory>
22 #include <mutex>
23 #include <stdexcept>
25 #include <sys/stat.h>
27 #include <QDebug>
28 #include <QFileInfo>
30 #include "devicemanager.hpp"
31 #include "mainwindow.hpp"
32 #include "session.hpp"
33 #include "util.hpp"
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"
42 #include "devices/hardwaredevice.hpp"
43 #include "devices/inputfile.hpp"
44 #include "devices/sessionfile.hpp"
46 #include "toolbars/mainbar.hpp"
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"
54 #include <libsigrokcxx/libsigrokcxx.hpp>
56 #ifdef ENABLE_FLOW
57 #include <gstreamermm.h>
58 #include <libsigrokflow/libsigrokflow.hpp>
59 #endif
61 #ifdef ENABLE_DECODE
62 #include <libsigrokdecode/libsigrokdecode.h>
63 #include "data/decodesignal.hpp"
64 #endif
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;
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;
100 using Glib::VariantBase;
102 #ifdef ENABLE_FLOW
103 using Gst::Bus;
104 using Gst::ElementFactory;
105 using Gst::Pipeline;
106 #endif
108 using pv::data::SignalGroup;
109 using pv::util::Timestamp;
110 using pv::views::trace::Signal;
111 using pv::views::trace::AnalogSignal;
112 using pv::views::trace::LogicSignal;
114 namespace pv {
116 shared_ptr<sigrok::Context> Session::sr_context;
118 Session::Session(DeviceManager &device_manager, QString name) :
119 shutting_down_(false),
120 device_manager_(device_manager),
121 default_name_(name),
122 name_(name),
123 capture_state_(Stopped),
124 cur_samplerate_(0),
125 data_saved_(true)
129 Session::~Session()
131 shutting_down_ = true;
133 // Stop and join to the thread
134 stop_capture();
136 for (SignalGroup* group : signal_groups_) {
137 group->clear();
138 delete group;
142 DeviceManager& Session::device_manager()
144 return device_manager_;
147 const DeviceManager& Session::device_manager() const
149 return device_manager_;
152 shared_ptr<sigrok::Session> Session::session() const
154 if (!device_)
155 return shared_ptr<sigrok::Session>();
156 return device_->session();
159 shared_ptr<devices::Device> Session::device() const
161 return device_;
164 QString Session::name() const
166 return name_;
169 void Session::set_name(QString name)
171 if (default_name_.isEmpty())
172 default_name_ = name;
174 name_ = name;
176 name_changed();
179 const vector< shared_ptr<views::ViewBase> > Session::views() const
181 return views_;
184 shared_ptr<views::ViewBase> Session::main_view() const
186 return main_view_;
189 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
191 main_bar_ = main_bar;
194 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
196 return main_bar_;
199 bool Session::data_saved() const
201 return data_saved_;
204 void Session::save_setup(QSettings &settings) const
206 int i = 0;
208 // Save channels and decoders
209 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
210 #ifdef ENABLE_DECODE
211 if (base->is_decode_signal()) {
212 settings.beginGroup("decode_signal" + QString::number(i++));
213 base->save_settings(settings);
214 settings.endGroup();
215 } else
216 #endif
218 settings.beginGroup(base->internal_name());
219 base->save_settings(settings);
220 settings.endGroup();
224 settings.setValue("decode_signals", i);
226 // Save view states and their signal settings
227 // Note: main_view must be saved as view0
228 i = 0;
229 settings.beginGroup("view" + QString::number(i++));
230 main_view_->save_settings(settings);
231 settings.endGroup();
233 for (const shared_ptr<views::ViewBase>& view : views_) {
234 if (view != main_view_) {
235 settings.beginGroup("view" + QString::number(i++));
236 settings.setValue("type", view->get_type());
237 view->save_settings(settings);
238 settings.endGroup();
242 settings.setValue("views", i);
244 int view_id = 0;
245 i = 0;
246 for (const shared_ptr<views::ViewBase>& vb : views_) {
247 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(vb);
248 if (tv) {
249 for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
251 const shared_ptr<views::trace::Flag> flag =
252 dynamic_pointer_cast<views::trace::Flag>(time_item);
253 if (flag) {
254 if (!flag->enabled())
255 continue;
257 settings.beginGroup("meta_obj" + QString::number(i++));
258 settings.setValue("type", "time_marker");
259 settings.setValue("assoc_view", view_id);
260 GlobalSettings::store_timestamp(settings, "time", flag->time());
261 settings.setValue("text", flag->get_text());
262 settings.endGroup();
266 if (tv->cursors_shown()) {
267 settings.beginGroup("meta_obj" + QString::number(i++));
268 settings.setValue("type", "selection");
269 settings.setValue("assoc_view", view_id);
270 const shared_ptr<views::trace::CursorPair> cp = tv->cursors();
271 GlobalSettings::store_timestamp(settings, "start_time", cp->first()->time());
272 GlobalSettings::store_timestamp(settings, "end_time", cp->second()->time());
273 settings.endGroup();
277 view_id++;
280 settings.setValue("meta_objs", i);
283 void Session::save_settings(QSettings &settings) const
285 map<string, string> dev_info;
286 list<string> key_list;
288 if (device_) {
289 shared_ptr<devices::HardwareDevice> hw_device =
290 dynamic_pointer_cast< devices::HardwareDevice >(device_);
292 if (hw_device) {
293 settings.setValue("device_type", "hardware");
294 settings.beginGroup("device");
296 key_list.emplace_back("vendor");
297 key_list.emplace_back("model");
298 key_list.emplace_back("version");
299 key_list.emplace_back("serial_num");
300 key_list.emplace_back("connection_id");
302 dev_info = device_manager_.get_device_info(device_);
304 for (string& key : key_list) {
305 if (dev_info.count(key))
306 settings.setValue(QString::fromUtf8(key.c_str()),
307 QString::fromUtf8(dev_info.at(key).c_str()));
308 else
309 settings.remove(QString::fromUtf8(key.c_str()));
312 settings.endGroup();
315 shared_ptr<devices::SessionFile> sessionfile_device =
316 dynamic_pointer_cast<devices::SessionFile>(device_);
318 if (sessionfile_device) {
319 settings.setValue("device_type", "sessionfile");
320 settings.beginGroup("device");
321 settings.setValue("filename", QString::fromStdString(
322 sessionfile_device->full_name()));
323 settings.endGroup();
326 shared_ptr<devices::InputFile> inputfile_device =
327 dynamic_pointer_cast<devices::InputFile>(device_);
329 if (inputfile_device) {
330 settings.setValue("device_type", "inputfile");
331 settings.beginGroup("device");
332 inputfile_device->save_meta_to_settings(settings);
333 settings.endGroup();
336 save_setup(settings);
340 void Session::restore_setup(QSettings &settings)
342 // Restore channels
343 for (shared_ptr<data::SignalBase> base : signalbases_) {
344 settings.beginGroup(base->internal_name());
345 base->restore_settings(settings);
346 settings.endGroup();
349 // Restore decoders
350 #ifdef ENABLE_DECODE
351 int decode_signals = settings.value("decode_signals").toInt();
353 for (int i = 0; i < decode_signals; i++) {
354 settings.beginGroup("decode_signal" + QString::number(i));
355 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
356 signal->restore_settings(settings);
357 settings.endGroup();
359 #endif
361 // Restore views
362 int views = settings.value("views").toInt();
364 for (int i = 0; i < views; i++) {
365 settings.beginGroup("view" + QString::number(i));
367 if (i > 0) {
368 views::ViewType type = (views::ViewType)settings.value("type").toInt();
369 add_view(type, this);
370 views_.back()->restore_settings(settings);
371 } else
372 main_view_->restore_settings(settings);
374 settings.endGroup();
377 // Restore meta objects like markers and cursors
378 int meta_objs = settings.value("meta_objs").toInt();
380 for (int i = 0; i < meta_objs; i++) {
381 settings.beginGroup("meta_obj" + QString::number(i));
383 shared_ptr<views::ViewBase> vb;
384 shared_ptr<views::trace::View> tv;
385 if (settings.contains("assoc_view"))
386 vb = views_.at(settings.value("assoc_view").toInt());
388 if (vb)
389 tv = dynamic_pointer_cast<views::trace::View>(vb);
391 const QString type = settings.value("type").toString();
393 if ((type == "time_marker") && tv) {
394 Timestamp ts = GlobalSettings::restore_timestamp(settings, "time");
395 shared_ptr<views::trace::Flag> flag = tv->add_flag(ts);
396 flag->set_text(settings.value("text").toString());
399 if ((type == "selection") && tv) {
400 Timestamp start = GlobalSettings::restore_timestamp(settings, "start_time");
401 Timestamp end = GlobalSettings::restore_timestamp(settings, "end_time");
402 tv->set_cursors(start, end);
403 tv->show_cursors();
406 settings.endGroup();
410 void Session::restore_settings(QSettings &settings)
412 shared_ptr<devices::Device> device;
414 const QString device_type = settings.value("device_type").toString();
416 if (device_type == "hardware") {
417 map<string, string> dev_info;
418 list<string> key_list;
420 // Re-select last used device if possible but only if it's not demo
421 settings.beginGroup("device");
422 key_list.emplace_back("vendor");
423 key_list.emplace_back("model");
424 key_list.emplace_back("version");
425 key_list.emplace_back("serial_num");
426 key_list.emplace_back("connection_id");
428 for (string key : key_list) {
429 const QString k = QString::fromStdString(key);
430 if (!settings.contains(k))
431 continue;
433 const string value = settings.value(k).toString().toStdString();
434 if (!value.empty())
435 dev_info.insert(make_pair(key, value));
438 if (dev_info.count("model") > 0)
439 device = device_manager_.find_device_from_info(dev_info);
441 if (device)
442 set_device(device);
444 settings.endGroup();
447 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
448 if (device_type == "sessionfile") {
449 settings.beginGroup("device");
450 const QString filename = settings.value("filename").toString();
451 settings.endGroup();
453 if (QFileInfo(filename).isReadable()) {
454 device = make_shared<devices::SessionFile>(device_manager_.context(),
455 filename.toStdString());
459 if (device_type == "inputfile") {
460 settings.beginGroup("device");
461 device = make_shared<devices::InputFile>(device_manager_.context(),
462 settings);
463 settings.endGroup();
466 if (device) {
467 set_device(device);
469 start_capture([](QString infoMessage) {
470 // TODO Emulate noquote()
471 qDebug() << "Session error:" << infoMessage; });
473 set_name(QString::fromStdString(
474 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
478 if (device)
479 restore_setup(settings);
482 void Session::select_device(shared_ptr<devices::Device> device)
484 try {
485 if (device)
486 set_device(device);
487 else
488 set_default_device();
489 } catch (const QString &e) {
490 MainWindow::show_session_error(tr("Failed to select device"), e);
494 void Session::set_device(shared_ptr<devices::Device> device)
496 assert(device);
498 // Ensure we are not capturing before setting the device
499 stop_capture();
501 if (device_)
502 device_->close();
504 device_.reset();
506 // Revert name back to default name (e.g. "Session 1") as the data is gone
507 name_ = default_name_;
508 name_changed();
510 // Remove all stored data and reset all views
511 for (shared_ptr<views::ViewBase> view : views_) {
512 view->clear_signalbases();
513 #ifdef ENABLE_DECODE
514 view->clear_decode_signals();
515 #endif
516 view->reset_view_state();
519 for (SignalGroup* group : signal_groups_) {
520 group->clear();
521 delete group;
523 signal_groups_.clear();
525 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
526 d->clear();
528 all_signal_data_.clear();
529 signalbases_.clear();
530 cur_logic_segment_.reset();
532 for (auto& entry : cur_analog_segments_) {
533 shared_ptr<sigrok::Channel>(entry.first).reset();
534 shared_ptr<data::AnalogSegment>(entry.second).reset();
537 logic_data_.reset();
539 signals_changed();
541 device_ = move(device);
543 try {
544 device_->open();
545 } catch (const QString &e) {
546 device_.reset();
547 MainWindow::show_session_error(tr("Failed to open device"), e);
550 if (device_) {
551 device_->session()->add_datafeed_callback([=]
552 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
553 data_feed_in(device, packet);
556 update_signals();
559 device_changed();
562 void Session::set_default_device()
564 const list< shared_ptr<devices::HardwareDevice> > &devices =
565 device_manager_.devices();
567 if (devices.empty())
568 return;
570 // Try and find the demo device and select that by default
571 const auto iter = find_if(devices.begin(), devices.end(),
572 [] (const shared_ptr<devices::HardwareDevice> &d) {
573 return d->hardware_device()->driver()->name() == "demo"; });
574 set_device((iter == devices.end()) ? devices.front() : *iter);
577 bool Session::using_file_device() const
579 shared_ptr<devices::SessionFile> sessionfile_device =
580 dynamic_pointer_cast<devices::SessionFile>(device_);
582 shared_ptr<devices::InputFile> inputfile_device =
583 dynamic_pointer_cast<devices::InputFile>(device_);
585 return (sessionfile_device || inputfile_device);
589 * Convert generic options to data types that are specific to InputFormat.
591 * @param[in] user_spec Vector of tokenized words, string format.
592 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
594 * @return Map of options suitable for InputFormat::create_input().
596 map<string, Glib::VariantBase>
597 Session::input_format_options(vector<string> user_spec,
598 map<string, shared_ptr<Option>> fmt_opts)
600 map<string, Glib::VariantBase> result;
602 for (auto& entry : user_spec) {
604 * Split key=value specs. Accept entries without separator
605 * (for simplified boolean specifications).
607 string key, val;
608 size_t pos = entry.find("=");
609 if (pos == std::string::npos) {
610 key = entry;
611 val = "";
612 } else {
613 key = entry.substr(0, pos);
614 val = entry.substr(pos + 1);
618 * Skip user specifications that are not a member of the
619 * format's set of supported options. Have the text input
620 * spec converted to the required input format specific
621 * data type.
623 auto found = fmt_opts.find(key);
624 if (found == fmt_opts.end())
625 continue;
626 shared_ptr<Option> opt = found->second;
627 result[key] = opt->parse_string(val);
630 return result;
633 void Session::load_init_file(const string &file_name,
634 const string &format, const string &setup_file_name)
636 shared_ptr<InputFormat> input_format;
637 map<string, Glib::VariantBase> input_opts;
639 if (!format.empty()) {
640 const map<string, shared_ptr<InputFormat> > formats =
641 device_manager_.context()->input_formats();
642 auto user_opts = pv::util::split_string(format, ":");
643 string user_name = user_opts.front();
644 user_opts.erase(user_opts.begin());
645 const auto iter = find_if(formats.begin(), formats.end(),
646 [&](const pair<string, shared_ptr<InputFormat> > f) {
647 return f.first == user_name; });
648 if (iter == formats.end()) {
649 MainWindow::show_session_error(tr("Error"),
650 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
651 return;
653 input_format = (*iter).second;
654 input_opts = input_format_options(user_opts,
655 input_format->options());
658 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
659 input_format, input_opts);
662 void Session::load_file(QString file_name, QString setup_file_name,
663 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
665 const QString errorMessage(
666 QString("Failed to load file %1").arg(file_name));
668 // In the absence of a caller's format spec, try to auto detect.
669 // Assume "sigrok session file" upon lookup miss.
670 if (!format)
671 format = device_manager_.context()->input_format_match(file_name.toStdString());
672 try {
673 if (format)
674 set_device(shared_ptr<devices::Device>(
675 new devices::InputFile(
676 device_manager_.context(),
677 file_name.toStdString(),
678 format, options)));
679 else
680 set_device(shared_ptr<devices::Device>(
681 new devices::SessionFile(
682 device_manager_.context(),
683 file_name.toStdString())));
684 } catch (Error& e) {
685 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
686 set_default_device();
687 main_bar_->update_device_list();
688 return;
691 // Use the input file with .pvs extension if no setup file was given
692 if (setup_file_name.isEmpty()) {
693 setup_file_name = file_name;
694 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
695 setup_file_name.append(".pvs");
698 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
699 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
700 restore_setup(settings_storage);
703 main_bar_->update_device_list();
705 start_capture([&, errorMessage](QString infoMessage) {
706 MainWindow::show_session_error(errorMessage, infoMessage); });
708 set_name(QFileInfo(file_name).fileName());
711 Session::capture_state Session::get_capture_state() const
713 lock_guard<mutex> lock(sampling_mutex_);
714 return capture_state_;
717 void Session::start_capture(function<void (const QString)> error_handler)
719 if (!device_) {
720 error_handler(tr("No active device set, can't start acquisition."));
721 return;
724 stop_capture();
726 // Check that at least one channel is enabled
727 const shared_ptr<sigrok::Device> sr_dev = device_->device();
728 if (sr_dev) {
729 const auto channels = sr_dev->channels();
730 if (!any_of(channels.begin(), channels.end(),
731 [](shared_ptr<Channel> channel) {
732 return channel->enabled(); })) {
733 error_handler(tr("No channels enabled."));
734 return;
738 // Clear signal data
739 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
740 d->clear();
742 trigger_list_.clear();
744 // Revert name back to default name (e.g. "Session 1") for real devices
745 // as the (possibly saved) data is gone. File devices keep their name.
746 shared_ptr<devices::HardwareDevice> hw_device =
747 dynamic_pointer_cast< devices::HardwareDevice >(device_);
749 if (hw_device) {
750 name_ = default_name_;
751 name_changed();
754 // Begin the session
755 sampling_thread_ = std::thread(
756 &Session::sample_thread_proc, this, error_handler);
759 void Session::stop_capture()
761 if (get_capture_state() != Stopped)
762 device_->stop();
764 // Check that sampling stopped
765 if (sampling_thread_.joinable())
766 sampling_thread_.join();
769 void Session::register_view(shared_ptr<views::ViewBase> view)
771 if (views_.empty())
772 main_view_ = view;
774 views_.push_back(view);
776 // Add all device signals
777 update_signals();
779 // Add all other signals
780 vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
782 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
783 const int sb_exists = count_if(
784 view_signalbases.cbegin(), view_signalbases.cend(),
785 [&](const shared_ptr<data::SignalBase> &sb) {
786 return sb == signalbase;
789 // Add the signal to the view if it doesn't have it yet
790 if (!sb_exists)
791 switch (signalbase->type()) {
792 case data::SignalBase::AnalogChannel:
793 case data::SignalBase::LogicChannel:
794 case data::SignalBase::MathChannel:
795 view->add_signalbase(signalbase);
796 break;
797 case data::SignalBase::DecodeChannel:
798 #ifdef ENABLE_DECODE
799 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
800 #endif
801 break;
805 signals_changed();
808 void Session::deregister_view(shared_ptr<views::ViewBase> view)
810 views_.erase(std::remove_if(views_.begin(), views_.end(),
811 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
812 views_.end());
814 if (views_.empty()) {
815 main_view_.reset();
817 // Without a view there can be no main bar
818 main_bar_.reset();
822 bool Session::has_view(shared_ptr<views::ViewBase> view)
824 for (shared_ptr<views::ViewBase>& v : views_)
825 if (v == view)
826 return true;
828 return false;
831 double Session::get_samplerate() const
833 double samplerate = 0.0;
835 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
836 assert(d);
837 const vector< shared_ptr<pv::data::Segment> > segments =
838 d->segments();
839 for (const shared_ptr<pv::data::Segment>& s : segments)
840 samplerate = max(samplerate, s->samplerate());
842 // If there is no sample rate given we use samples as unit
843 if (samplerate == 0.0)
844 samplerate = 1.0;
846 return samplerate;
849 uint32_t Session::get_segment_count() const
851 uint32_t value = 0;
853 // Find the highest number of segments
854 for (const shared_ptr<data::SignalData>& data : all_signal_data_)
855 if (data->get_segment_count() > value)
856 value = data->get_segment_count();
858 return value;
861 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
863 vector<util::Timestamp> result;
865 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
866 if (entry.first == segment_id)
867 result.push_back(entry.second);
869 return result;
872 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
874 return signalbases_;
877 void Session::add_generated_signal(shared_ptr<data::SignalBase> signal)
879 signalbases_.push_back(signal);
881 for (shared_ptr<views::ViewBase>& view : views_)
882 view->add_signalbase(signal);
884 update_signals();
887 void Session::remove_generated_signal(shared_ptr<data::SignalBase> signal)
889 if (shutting_down_)
890 return;
892 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
893 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
894 signalbases_.end());
896 for (shared_ptr<views::ViewBase>& view : views_)
897 view->remove_signalbase(signal);
899 update_signals();
902 #ifdef ENABLE_DECODE
903 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
905 shared_ptr<data::DecodeSignal> signal;
907 try {
908 // Create the decode signal
909 signal = make_shared<data::DecodeSignal>(*this);
911 signalbases_.push_back(signal);
913 // Add the decode signal to all views
914 for (shared_ptr<views::ViewBase>& view : views_)
915 view->add_decode_signal(signal);
916 } catch (runtime_error& e) {
917 remove_decode_signal(signal);
918 return nullptr;
921 signals_changed();
923 return signal;
926 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
928 if (shutting_down_)
929 return;
931 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
932 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
933 signalbases_.end());
935 for (shared_ptr<views::ViewBase>& view : views_)
936 view->remove_decode_signal(signal);
938 signals_changed();
940 #endif
942 bool Session::all_segments_complete(uint32_t segment_id) const
944 bool all_complete = true;
946 for (const shared_ptr<data::SignalBase>& base : signalbases_)
947 if (!base->segment_is_complete(segment_id))
948 all_complete = false;
950 return all_complete;
953 MetadataObjManager* Session::metadata_obj_manager()
955 return &metadata_obj_manager_;
958 void Session::set_capture_state(capture_state state)
960 bool changed;
962 if (state == Running)
963 acq_time_.restart();
964 if (state == Stopped)
965 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
968 lock_guard<mutex> lock(sampling_mutex_);
969 changed = capture_state_ != state;
970 capture_state_ = state;
973 if (changed)
974 capture_state_changed(state);
977 void Session::update_signals()
979 if (!device_) {
980 signalbases_.clear();
981 logic_data_.reset();
982 for (shared_ptr<views::ViewBase>& view : views_) {
983 view->clear_signalbases();
984 #ifdef ENABLE_DECODE
985 view->clear_decode_signals();
986 #endif
988 return;
991 lock_guard<recursive_mutex> lock(data_mutex_);
993 const shared_ptr<sigrok::Device> sr_dev = device_->device();
994 if (!sr_dev) {
995 signalbases_.clear();
996 logic_data_.reset();
997 for (shared_ptr<views::ViewBase>& view : views_) {
998 view->clear_signalbases();
999 #ifdef ENABLE_DECODE
1000 view->clear_decode_signals();
1001 #endif
1003 return;
1006 // Detect what data types we will receive
1007 auto channels = sr_dev->channels();
1008 unsigned int logic_channel_count = count_if(
1009 channels.begin(), channels.end(),
1010 [] (shared_ptr<Channel> channel) {
1011 return channel->type() == sigrok::ChannelType::LOGIC; });
1013 // Create a common data container for the logic signalbases
1015 lock_guard<recursive_mutex> data_lock(data_mutex_);
1017 if (logic_channel_count == 0) {
1018 logic_data_.reset();
1019 } else if (!logic_data_ ||
1020 logic_data_->num_channels() != logic_channel_count) {
1021 logic_data_.reset(new data::Logic(logic_channel_count));
1022 assert(logic_data_);
1026 // Create signalbases if necessary
1027 for (auto channel : sr_dev->channels()) {
1029 // Try to find the channel in the list of existing signalbases
1030 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1031 [&](const shared_ptr<SignalBase> &sb) { return sb->channel() == channel; });
1033 // Not found, let's make a signalbase for it
1034 if (iter == signalbases_.cend()) {
1035 shared_ptr<SignalBase> signalbase;
1036 switch(channel->type()->id()) {
1037 case SR_CHANNEL_LOGIC:
1038 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::LogicChannel);
1039 signalbases_.push_back(signalbase);
1041 all_signal_data_.insert(logic_data_);
1042 signalbase->set_data(logic_data_);
1044 connect(this, SIGNAL(capture_state_changed(int)),
1045 signalbase.get(), SLOT(on_capture_state_changed(int)));
1046 break;
1048 case SR_CHANNEL_ANALOG:
1049 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::AnalogChannel);
1050 signalbases_.push_back(signalbase);
1052 shared_ptr<data::Analog> data(new data::Analog());
1053 all_signal_data_.insert(data);
1054 signalbase->set_data(data);
1056 connect(this, SIGNAL(capture_state_changed(int)),
1057 signalbase.get(), SLOT(on_capture_state_changed(int)));
1058 break;
1063 // Create and assign default signal groups if needed
1064 if (signal_groups_.empty()) {
1065 for (auto& entry : sr_dev->channel_groups()) {
1066 const shared_ptr<sigrok::ChannelGroup>& group = entry.second;
1068 if (group->channels().size() <= 1)
1069 continue;
1071 SignalGroup* sg = new SignalGroup(QString::fromStdString(entry.first));
1072 for (const shared_ptr<sigrok::Channel>& channel : group->channels()) {
1073 for (shared_ptr<data::SignalBase> s : signalbases_) {
1074 if (s->channel() == channel) {
1075 sg->append_signal(s);
1076 break;
1080 signal_groups_.emplace_back(sg);
1084 // Update all views
1085 for (shared_ptr<views::ViewBase>& viewbase : views_) {
1086 vector< shared_ptr<SignalBase> > view_signalbases =
1087 viewbase->signalbases();
1089 // Add all non-decode signalbases that don't yet exist in the view
1090 for (shared_ptr<SignalBase>& session_sb : signalbases_) {
1091 if (session_sb->type() == SignalBase::DecodeChannel)
1092 continue;
1094 const auto iter = find_if(view_signalbases.cbegin(), view_signalbases.cend(),
1095 [&](const shared_ptr<SignalBase> &sb) { return sb == session_sb; });
1097 if (iter == view_signalbases.cend())
1098 viewbase->add_signalbase(session_sb);
1101 // Remove all non-decode signalbases that no longer exist
1102 for (shared_ptr<SignalBase>& view_sb : view_signalbases) {
1103 if (view_sb->type() == SignalBase::DecodeChannel)
1104 continue;
1106 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1107 [&](const shared_ptr<SignalBase> &sb) { return sb == view_sb; });
1109 if (iter == signalbases_.cend())
1110 viewbase->remove_signalbase(view_sb);
1114 signals_changed();
1117 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1118 shared_ptr<sigrok::Channel> channel) const
1120 for (shared_ptr<data::SignalBase> sig : signalbases_) {
1121 assert(sig);
1122 if (sig->channel() == channel)
1123 return sig;
1125 return shared_ptr<data::SignalBase>();
1128 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1130 assert(error_handler);
1132 #ifdef ENABLE_FLOW
1133 pipeline_ = Pipeline::create();
1135 source_ = ElementFactory::create_element("filesrc", "source");
1136 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1138 pipeline_->add(source_)->add(sink_);
1139 source_->link(sink_);
1141 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1143 sink_->set_property("emit-signals", TRUE);
1144 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1146 // Get the bus from the pipeline and add a bus watch to the default main context
1147 RefPtr<Bus> bus = pipeline_->get_bus();
1148 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1150 // Start pipeline and Wait until it finished processing
1151 pipeline_done_interrupt_ = false;
1152 pipeline_->set_state(Gst::STATE_PLAYING);
1154 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1155 pipeline_done_cond_.wait(pipeline_done_lock_);
1157 // Let the pipeline free all resources
1158 pipeline_->set_state(Gst::STATE_NULL);
1160 #else
1161 if (!device_)
1162 return;
1164 try {
1165 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1166 } catch (Error& e) {
1167 cur_samplerate_ = 0;
1170 out_of_memory_ = false;
1173 lock_guard<recursive_mutex> lock(data_mutex_);
1174 cur_logic_segment_.reset();
1175 cur_analog_segments_.clear();
1176 for (shared_ptr<data::SignalBase> sb : signalbases_)
1177 sb->clear_sample_data();
1179 highest_segment_id_ = -1;
1180 frame_began_ = false;
1182 try {
1183 device_->start();
1184 } catch (Error& e) {
1185 error_handler(e.what());
1186 return;
1189 set_capture_state(device_->session()->trigger() ?
1190 AwaitingTrigger : Running);
1192 try {
1193 device_->run();
1194 } catch (Error& e) {
1195 error_handler(e.what());
1196 set_capture_state(Stopped);
1197 return;
1198 } catch (QString& e) {
1199 error_handler(e);
1200 set_capture_state(Stopped);
1201 return;
1204 set_capture_state(Stopped);
1206 // Confirm that SR_DF_END was received
1207 if (cur_logic_segment_)
1208 qDebug() << "WARNING: SR_DF_END was not received.";
1209 #endif
1211 // Optimize memory usage
1212 free_unused_memory();
1214 // We now have unsaved data unless we just "captured" from a file
1215 shared_ptr<devices::File> file_device =
1216 dynamic_pointer_cast<devices::File>(device_);
1218 if (!file_device)
1219 data_saved_ = false;
1221 if (out_of_memory_)
1222 error_handler(tr("Out of memory, acquisition stopped."));
1225 void Session::free_unused_memory()
1227 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1228 const vector< shared_ptr<data::Segment> > segments = data->segments();
1230 for (const shared_ptr<data::Segment>& segment : segments)
1231 segment->free_unused_memory();
1235 void Session::signal_new_segment()
1237 int new_segment_id = 0;
1239 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1241 // Determine new frame/segment number, assuming that all
1242 // signals have the same number of frames/segments
1243 if (cur_logic_segment_) {
1244 new_segment_id = logic_data_->get_segment_count() - 1;
1245 } else {
1246 shared_ptr<sigrok::Channel> any_channel =
1247 (*cur_analog_segments_.begin()).first;
1249 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1250 assert(base);
1252 shared_ptr<data::Analog> data(base->analog_data());
1253 assert(data);
1255 new_segment_id = data->get_segment_count() - 1;
1259 if (new_segment_id > highest_segment_id_) {
1260 highest_segment_id_ = new_segment_id;
1261 new_segment(highest_segment_id_);
1265 void Session::signal_segment_completed()
1267 int segment_id = 0;
1269 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1270 // We only care about analog and logic channels, not derived ones
1271 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1272 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1273 break;
1276 if (signalbase->type() == data::SignalBase::LogicChannel) {
1277 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1278 break;
1282 if (segment_id >= 0)
1283 segment_completed(segment_id);
1286 #ifdef ENABLE_FLOW
1287 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1289 (void)bus;
1291 if ((message->get_source() == pipeline_) && \
1292 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1293 pipeline_done_cond_.notify_one();
1295 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1297 return true;
1300 Gst::FlowReturn Session::on_gst_new_sample()
1302 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1303 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1305 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1306 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1307 Gst::MapInfo mapinfo;
1308 buf_mem->map(mapinfo, Gst::MAP_READ);
1310 shared_ptr<sigrok::Packet> logic_packet =
1311 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1313 try {
1314 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1315 } catch (bad_alloc&) {
1316 out_of_memory_ = true;
1317 device_->stop();
1318 buf_mem->unmap(mapinfo);
1319 return Gst::FLOW_ERROR;
1322 buf_mem->unmap(mapinfo);
1325 return Gst::FLOW_OK;
1327 #endif
1329 void Session::feed_in_header()
1331 // Nothing to do here for now
1334 void Session::feed_in_meta(shared_ptr<Meta> meta)
1336 for (auto& entry : meta->config()) {
1337 switch (entry.first->id()) {
1338 case SR_CONF_SAMPLERATE:
1339 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1340 break;
1341 default:
1342 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1343 break;
1347 signals_changed();
1350 void Session::feed_in_trigger()
1352 // The channel containing most samples should be most accurate
1353 uint64_t sample_count = 0;
1356 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1357 assert(d);
1358 uint64_t temp_count = 0;
1360 const vector< shared_ptr<pv::data::Segment> > segments =
1361 d->segments();
1362 for (const shared_ptr<pv::data::Segment> &s : segments)
1363 temp_count += s->get_sample_count();
1365 if (temp_count > sample_count)
1366 sample_count = temp_count;
1370 uint32_t segment_id = 0; // Default segment when no frames are used
1372 // If a frame began, we'd ideally be able to use the highest segment ID for
1373 // the trigger. However, as new segments are only created when logic or
1374 // analog data comes in, this doesn't work if the trigger appears right
1375 // after the beginning of the frame, before any sample data.
1376 // For this reason, we use highest segment ID + 1 if no sample data came in
1377 // yet and the highest segment ID otherwise.
1378 if (frame_began_) {
1379 segment_id = highest_segment_id_;
1380 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1381 segment_id++;
1384 // TODO Create timestamp from segment start time + segment's current sample count
1385 util::Timestamp timestamp = sample_count / get_samplerate();
1386 trigger_list_.emplace_back(segment_id, timestamp);
1387 trigger_event(segment_id, timestamp);
1390 void Session::feed_in_frame_begin()
1392 frame_began_ = true;
1395 void Session::feed_in_frame_end()
1397 if (!frame_began_)
1398 return;
1401 lock_guard<recursive_mutex> lock(data_mutex_);
1403 if (cur_logic_segment_)
1404 cur_logic_segment_->set_complete();
1406 for (auto& entry : cur_analog_segments_) {
1407 shared_ptr<data::AnalogSegment> segment = entry.second;
1408 segment->set_complete();
1411 cur_logic_segment_.reset();
1412 cur_analog_segments_.clear();
1415 frame_began_ = false;
1417 signal_segment_completed();
1420 void Session::feed_in_logic(shared_ptr<sigrok::Logic> logic)
1422 if (logic->data_length() == 0) {
1423 qDebug() << "WARNING: Received logic packet with 0 samples.";
1424 return;
1427 if (logic->unit_size() > 8)
1428 throw QString(tr("Can't handle more than 64 logic channels."));
1430 if (!cur_samplerate_)
1431 try {
1432 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1433 } catch (Error& e) {
1434 // Do nothing
1437 lock_guard<recursive_mutex> lock(data_mutex_);
1439 if (!logic_data_) {
1440 // The only reason logic_data_ would not have been created is
1441 // if it was not possible to determine the signals when the
1442 // device was created.
1443 update_signals();
1446 if (!cur_logic_segment_) {
1447 // This could be the first packet after a trigger
1448 set_capture_state(Running);
1450 // Create a new data segment
1451 cur_logic_segment_ = make_shared<data::LogicSegment>(
1452 *logic_data_, logic_data_->get_segment_count(),
1453 logic->unit_size(), cur_samplerate_);
1454 logic_data_->push_segment(cur_logic_segment_);
1456 signal_new_segment();
1459 cur_logic_segment_->append_payload(logic);
1461 data_received();
1464 void Session::feed_in_analog(shared_ptr<sigrok::Analog> analog)
1466 if (analog->num_samples() == 0) {
1467 qDebug() << "WARNING: Received analog packet with 0 samples.";
1468 return;
1471 if (!cur_samplerate_)
1472 try {
1473 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1474 } catch (Error& e) {
1475 // Do nothing
1478 lock_guard<recursive_mutex> lock(data_mutex_);
1480 const vector<shared_ptr<Channel>> channels = analog->channels();
1481 bool sweep_beginning = false;
1483 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1484 analog->get_data_as_float(data.get());
1486 if (signalbases_.empty())
1487 update_signals();
1489 float *channel_data = data.get();
1490 for (auto& channel : channels) {
1491 shared_ptr<data::AnalogSegment> segment;
1493 // Try to get the segment of the channel
1494 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1495 iterator iter = cur_analog_segments_.find(channel);
1496 if (iter != cur_analog_segments_.end())
1497 segment = (*iter).second;
1498 else {
1499 // If no segment was found, this means we haven't
1500 // created one yet. i.e. this is the first packet
1501 // in the sweep containing this segment.
1502 sweep_beginning = true;
1504 // Find the analog data associated with the channel
1505 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1506 assert(base);
1508 shared_ptr<data::Analog> data(base->analog_data());
1509 assert(data);
1511 // Create a segment, keep it in the maps of channels
1512 segment = make_shared<data::AnalogSegment>(
1513 *data, data->get_segment_count(), cur_samplerate_);
1514 cur_analog_segments_[channel] = segment;
1516 // Push the segment into the analog data.
1517 data->push_segment(segment);
1519 signal_new_segment();
1522 assert(segment);
1524 // Append the samples in the segment
1525 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1526 channels.size());
1529 if (sweep_beginning) {
1530 // This could be the first packet after a trigger
1531 set_capture_state(Running);
1534 data_received();
1537 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1538 shared_ptr<Packet> packet)
1540 (void)device;
1542 assert(device);
1543 assert(device == device_->device());
1544 assert(packet);
1546 switch (packet->type()->id()) {
1547 case SR_DF_HEADER:
1548 feed_in_header();
1549 break;
1551 case SR_DF_META:
1552 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1553 break;
1555 case SR_DF_TRIGGER:
1556 feed_in_trigger();
1557 break;
1559 case SR_DF_LOGIC:
1560 try {
1561 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1562 } catch (bad_alloc&) {
1563 out_of_memory_ = true;
1564 device_->stop();
1566 break;
1568 case SR_DF_ANALOG:
1569 try {
1570 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1571 } catch (bad_alloc&) {
1572 out_of_memory_ = true;
1573 device_->stop();
1575 break;
1577 case SR_DF_FRAME_BEGIN:
1578 feed_in_frame_begin();
1579 break;
1581 case SR_DF_FRAME_END:
1582 feed_in_frame_end();
1583 break;
1585 case SR_DF_END:
1586 // Strictly speaking, this is performed when a frame end marker was
1587 // received, so there's no point doing this again. However, not all
1588 // devices use frames, and for those devices, we need to do it here.
1590 lock_guard<recursive_mutex> lock(data_mutex_);
1592 if (cur_logic_segment_)
1593 cur_logic_segment_->set_complete();
1595 for (auto& entry : cur_analog_segments_) {
1596 shared_ptr<data::AnalogSegment> segment = entry.second;
1597 segment->set_complete();
1600 cur_logic_segment_.reset();
1601 cur_analog_segments_.clear();
1603 break;
1605 default:
1606 break;
1610 void Session::on_data_saved()
1612 data_saved_ = true;
1615 #ifdef ENABLE_DECODE
1616 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1618 assert(decoders.size() > 0);
1620 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1622 if (signal)
1623 for (unsigned int i = 0; i < decoders.size(); i++) {
1624 const srd_decoder* d = decoders[i];
1625 signal->stack_decoder(d, !(i < decoders.size() - 1));
1628 #endif
1630 } // namespace pv