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/>.
31 #include "devicemanager.hpp"
32 #include "mainwindow.hpp"
33 #include "session.hpp"
36 #include "data/analog.hpp"
37 #include "data/analogsegment.hpp"
38 #include "data/decode/decoder.hpp"
39 #include "data/logic.hpp"
40 #include "data/logicsegment.hpp"
41 #include "data/mathsignal.hpp"
42 #include "data/signalbase.hpp"
44 #include "devices/hardwaredevice.hpp"
45 #include "devices/inputfile.hpp"
46 #include "devices/sessionfile.hpp"
48 #include "toolbars/mainbar.hpp"
50 #include "views/trace/analogsignal.hpp"
51 #include "views/trace/decodetrace.hpp"
52 #include "views/trace/logicsignal.hpp"
53 #include "views/trace/signal.hpp"
54 #include "views/trace/view.hpp"
56 #include <libsigrokcxx/libsigrokcxx.hpp>
59 #include <gstreamermm.h>
60 #include <libsigrokflow/libsigrokflow.hpp>
64 #include <libsigrokdecode/libsigrokdecode.h>
65 #include "data/decodesignal.hpp"
69 using std::dynamic_pointer_cast;
73 using std::lock_guard;
75 using std::make_shared;
81 using std::recursive_mutex;
82 using std::runtime_error;
83 using std::shared_ptr;
86 using std::unique_lock;
88 using std::unique_ptr;
92 using sigrok::Channel;
93 using sigrok::ConfigKey;
94 using sigrok::DatafeedCallbackFunction;
96 using sigrok::InputFormat;
100 using sigrok::Session;
102 using Glib::VariantBase;
106 using Gst::ElementFactory;
110 using pv::data::SignalGroup;
111 using pv::util::Timestamp;
112 using pv::views::trace::Signal;
113 using pv::views::trace::AnalogSignal;
114 using pv::views::trace::LogicSignal;
118 shared_ptr<sigrok::Context> Session::sr_context;
120 Session::Session(DeviceManager &device_manager, QString name) :
121 shutting_down_(false),
122 device_manager_(device_manager),
125 capture_state_(Stopped),
129 // Use this name also for the QObject instance
130 setObjectName(name_);
135 shutting_down_ = true;
137 // Stop and join to the thread
140 for (SignalGroup* group : signal_groups_) {
146 DeviceManager& Session::device_manager()
148 return device_manager_;
151 const DeviceManager& Session::device_manager() const
153 return device_manager_;
156 shared_ptr<sigrok::Session> Session::session() const
159 return shared_ptr<sigrok::Session>();
160 return device_->session();
163 shared_ptr<devices::Device> Session::device() const
168 QString Session::name() const
173 void Session::set_name(QString name)
175 if (default_name_.isEmpty())
176 default_name_ = name;
180 // Use this name also for the QObject instance
181 setObjectName(name_);
186 QString Session::save_path() const
191 void Session::set_save_path(QString path)
196 const vector< shared_ptr<views::ViewBase> > Session::views() const
201 shared_ptr<views::ViewBase> Session::main_view() const
206 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
208 main_bar_ = main_bar;
211 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
216 bool Session::data_saved() const
221 void Session::save_setup(QSettings &settings) const
224 int decode_signal_count = 0;
225 int gen_signal_count = 0;
227 // Save channels and decoders
228 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
230 if (base->is_decode_signal()) {
231 settings.beginGroup("decode_signal" + QString::number(decode_signal_count++));
232 base->save_settings(settings);
236 if (base->is_generated()) {
237 settings.beginGroup("generated_signal" + QString::number(gen_signal_count++));
238 settings.setValue("type", base->type());
239 base->save_settings(settings);
242 settings.beginGroup(base->internal_name());
243 base->save_settings(settings);
248 settings.setValue("decode_signals", decode_signal_count);
249 settings.setValue("generated_signals", gen_signal_count);
251 // Save view states and their signal settings
252 // Note: main_view must be saved as view0
254 settings.beginGroup("view" + QString::number(i++));
255 main_view_->save_settings(settings);
258 for (const shared_ptr<views::ViewBase>& view : views_) {
259 if (view != main_view_) {
260 settings.beginGroup("view" + QString::number(i++));
261 settings.setValue("type", view->get_type());
262 view->save_settings(settings);
267 settings.setValue("views", i);
271 for (const shared_ptr<views::ViewBase>& vb : views_) {
272 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(vb);
274 for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
276 const shared_ptr<views::trace::Flag> flag =
277 dynamic_pointer_cast<views::trace::Flag>(time_item);
279 if (!flag->enabled())
282 settings.beginGroup("meta_obj" + QString::number(i++));
283 settings.setValue("type", "time_marker");
284 settings.setValue("assoc_view", view_id);
285 GlobalSettings::store_timestamp(settings, "time", flag->time());
286 settings.setValue("text", flag->get_text());
291 if (tv->cursors_shown()) {
292 settings.beginGroup("meta_obj" + QString::number(i++));
293 settings.setValue("type", "selection");
294 settings.setValue("assoc_view", view_id);
295 const shared_ptr<views::trace::CursorPair> cp = tv->cursors();
296 GlobalSettings::store_timestamp(settings, "start_time", cp->first()->time());
297 GlobalSettings::store_timestamp(settings, "end_time", cp->second()->time());
305 settings.setValue("meta_objs", i);
308 void Session::save_settings(QSettings &settings) const
310 map<string, string> dev_info;
311 list<string> key_list;
314 shared_ptr<devices::HardwareDevice> hw_device =
315 dynamic_pointer_cast< devices::HardwareDevice >(device_);
318 settings.setValue("device_type", "hardware");
319 settings.beginGroup("device");
321 key_list.emplace_back("vendor");
322 key_list.emplace_back("model");
323 key_list.emplace_back("version");
324 key_list.emplace_back("serial_num");
325 key_list.emplace_back("connection_id");
327 dev_info = device_manager_.get_device_info(device_);
329 for (string& key : key_list) {
330 if (dev_info.count(key))
331 settings.setValue(QString::fromUtf8(key.c_str()),
332 QString::fromUtf8(dev_info.at(key).c_str()));
334 settings.remove(QString::fromUtf8(key.c_str()));
340 // Having saved the data to srzip overrides the current device. This is
341 // a crappy hack around the fact that saving e.g. an imported file to
342 // srzip would require changing the underlying libsigrok device
343 if (!save_path_.isEmpty()) {
344 QFileInfo fi = QFileInfo(QDir(save_path_), name_);
345 settings.setValue("device_type", "sessionfile");
346 settings.beginGroup("device");
347 settings.setValue("filename", fi.absoluteFilePath());
350 shared_ptr<devices::SessionFile> sessionfile_device =
351 dynamic_pointer_cast<devices::SessionFile>(device_);
353 if (sessionfile_device) {
354 settings.setValue("device_type", "sessionfile");
355 settings.beginGroup("device");
356 settings.setValue("filename", QString::fromStdString(
357 sessionfile_device->full_name()));
361 shared_ptr<devices::InputFile> inputfile_device =
362 dynamic_pointer_cast<devices::InputFile>(device_);
364 if (inputfile_device) {
365 settings.setValue("device_type", "inputfile");
366 settings.beginGroup("device");
367 inputfile_device->save_meta_to_settings(settings);
372 save_setup(settings);
376 void Session::restore_setup(QSettings &settings)
379 for (shared_ptr<data::SignalBase> base : signalbases_) {
380 settings.beginGroup(base->internal_name());
381 base->restore_settings(settings);
385 // Restore generated signals
386 int gen_signal_count = settings.value("generated_signals").toInt();
388 for (int i = 0; i < gen_signal_count; i++) {
389 settings.beginGroup("generated_signal" + QString::number(i));
390 SignalBase::ChannelType type = (SignalBase::ChannelType)settings.value("type").toInt();
391 shared_ptr<data::SignalBase> signal;
393 if (type == SignalBase::MathChannel)
394 signal = make_shared<data::MathSignal>(*this);
396 qWarning() << tr("Can't restore generated signal of unknown type %1 (%2)") \
398 .arg(settings.value("name").toString());
401 add_generated_signal(signal);
402 signal->restore_settings(settings);
410 int decode_signal_count = settings.value("decode_signals").toInt();
412 for (int i = 0; i < decode_signal_count; i++) {
413 settings.beginGroup("decode_signal" + QString::number(i));
414 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
415 signal->restore_settings(settings);
421 int views = settings.value("views").toInt();
423 for (int i = 0; i < views; i++) {
424 settings.beginGroup("view" + QString::number(i));
427 views::ViewType type = (views::ViewType)settings.value("type").toInt();
428 add_view(type, this);
429 views_.back()->restore_settings(settings);
431 main_view_->restore_settings(settings);
436 // Restore meta objects like markers and cursors
437 int meta_objs = settings.value("meta_objs").toInt();
439 for (int i = 0; i < meta_objs; i++) {
440 settings.beginGroup("meta_obj" + QString::number(i));
442 shared_ptr<views::ViewBase> vb;
443 shared_ptr<views::trace::View> tv;
444 if (settings.contains("assoc_view"))
445 vb = views_.at(settings.value("assoc_view").toInt());
448 tv = dynamic_pointer_cast<views::trace::View>(vb);
450 const QString type = settings.value("type").toString();
452 if ((type == "time_marker") && tv) {
453 Timestamp ts = GlobalSettings::restore_timestamp(settings, "time");
454 shared_ptr<views::trace::Flag> flag = tv->add_flag(ts);
455 flag->set_text(settings.value("text").toString());
458 if ((type == "selection") && tv) {
459 Timestamp start = GlobalSettings::restore_timestamp(settings, "start_time");
460 Timestamp end = GlobalSettings::restore_timestamp(settings, "end_time");
461 tv->set_cursors(start, end);
469 void Session::restore_settings(QSettings &settings)
471 shared_ptr<devices::Device> device;
473 const QString device_type = settings.value("device_type").toString();
475 if (device_type == "hardware") {
476 map<string, string> dev_info;
477 list<string> key_list;
479 // Re-select last used device if possible but only if it's not demo
480 settings.beginGroup("device");
481 key_list.emplace_back("vendor");
482 key_list.emplace_back("model");
483 key_list.emplace_back("version");
484 key_list.emplace_back("serial_num");
485 key_list.emplace_back("connection_id");
487 for (string key : key_list) {
488 const QString k = QString::fromStdString(key);
489 if (!settings.contains(k))
492 const string value = settings.value(k).toString().toStdString();
494 dev_info.insert(make_pair(key, value));
497 if (dev_info.count("model") > 0)
498 device = device_manager_.find_device_from_info(dev_info);
506 restore_setup(settings);
510 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
511 if (device_type == "sessionfile") {
512 settings.beginGroup("device");
513 filename = settings.value("filename").toString();
516 if (QFileInfo(filename).isReadable())
517 device = make_shared<devices::SessionFile>(device_manager_.context(),
518 filename.toStdString());
521 if (device_type == "inputfile") {
522 settings.beginGroup("device");
523 device = make_shared<devices::InputFile>(device_manager_.context(),
531 restore_setup(settings);
533 start_capture([](QString infoMessage) {
534 // TODO Emulate noquote()
535 qDebug() << "Session error:" << infoMessage; });
537 set_name(QString::fromStdString(
538 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
540 if (!filename.isEmpty()) {
541 // Only set the save path if we load an srzip file
542 if (device_type == "sessionfile")
543 set_save_path(QFileInfo(filename).absolutePath());
545 set_name(QFileInfo(filename).fileName());
551 void Session::select_device(shared_ptr<devices::Device> device)
557 set_default_device();
558 } catch (const QString &e) {
559 MainWindow::show_session_error(tr("Failed to select device"), e);
563 void Session::set_device(shared_ptr<devices::Device> device)
567 // Ensure we are not capturing before setting the device
575 // Revert name back to default name (e.g. "Session 1") as the data is gone
576 name_ = default_name_;
579 // Remove all stored data and reset all views
580 for (shared_ptr<views::ViewBase> view : views_) {
581 view->clear_signalbases();
583 view->clear_decode_signals();
585 view->reset_view_state();
588 for (SignalGroup* group : signal_groups_) {
592 signal_groups_.clear();
594 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
597 all_signal_data_.clear();
598 signalbases_.clear();
599 cur_logic_segment_.reset();
601 for (auto& entry : cur_analog_segments_) {
602 shared_ptr<sigrok::Channel>(entry.first).reset();
603 shared_ptr<data::AnalogSegment>(entry.second).reset();
610 device_ = move(device);
614 } catch (const QString &e) {
616 MainWindow::show_session_error(tr("Failed to open device"), e);
617 } catch (const sigrok::Error &e) {
619 MainWindow::show_session_error(tr("Failed to open device"), QString(e.what()));
623 device_->session()->add_datafeed_callback([=]
624 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
625 data_feed_in(device, packet);
634 void Session::set_default_device()
636 const list< shared_ptr<devices::HardwareDevice> > &devices =
637 device_manager_.devices();
642 // Try and find the demo device and select that by default
643 const auto iter = find_if(devices.begin(), devices.end(),
644 [] (const shared_ptr<devices::HardwareDevice> &d) {
645 return d->hardware_device()->driver()->name() == "demo"; });
646 set_device((iter == devices.end()) ? devices.front() : *iter);
649 bool Session::using_file_device() const
651 shared_ptr<devices::SessionFile> sessionfile_device =
652 dynamic_pointer_cast<devices::SessionFile>(device_);
654 shared_ptr<devices::InputFile> inputfile_device =
655 dynamic_pointer_cast<devices::InputFile>(device_);
657 return (sessionfile_device || inputfile_device);
661 * Convert generic options to data types that are specific to InputFormat.
663 * @param[in] user_spec Vector of tokenized words, string format.
664 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
666 * @return Map of options suitable for InputFormat::create_input().
668 map<string, Glib::VariantBase>
669 Session::input_format_options(vector<string> user_spec,
670 map<string, shared_ptr<Option>> fmt_opts)
672 map<string, Glib::VariantBase> result;
674 for (auto& entry : user_spec) {
676 * Split key=value specs. Accept entries without separator
677 * (for simplified boolean specifications).
680 size_t pos = entry.find("=");
681 if (pos == std::string::npos) {
685 key = entry.substr(0, pos);
686 val = entry.substr(pos + 1);
690 * Skip user specifications that are not a member of the
691 * format's set of supported options. Have the text input
692 * spec converted to the required input format specific
695 auto found = fmt_opts.find(key);
696 if (found == fmt_opts.end()) {
697 qCritical() << "Supplied input option" << QString::fromStdString(key) <<
698 "is not a valid option for this input module, it will be ignored!";
702 shared_ptr<Option> opt = found->second;
703 result[key] = opt->parse_string(val);
709 void Session::load_init_file(const string &file_name,
710 const string &format, const string &setup_file_name)
712 shared_ptr<InputFormat> input_format;
713 map<string, Glib::VariantBase> input_opts;
715 if (!format.empty()) {
716 const map<string, shared_ptr<InputFormat> > formats =
717 device_manager_.context()->input_formats();
718 auto user_opts = pv::util::split_string(format, ":");
719 string user_name = user_opts.front();
720 user_opts.erase(user_opts.begin());
721 const auto iter = find_if(formats.begin(), formats.end(),
722 [&](const pair<string, shared_ptr<InputFormat> > f) {
723 return f.first == user_name; });
724 if (iter == formats.end()) {
725 MainWindow::show_session_error(tr("Error"),
726 tr("Unexpected input format: %1").arg(QString::fromStdString(format)));
729 input_format = (*iter).second;
730 input_opts = input_format_options(user_opts,
731 input_format->options());
734 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
735 input_format, input_opts);
738 void Session::load_file(QString file_name, QString setup_file_name,
739 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
741 const QString errorMessage(
742 QString("Failed to load file %1").arg(file_name));
744 // In the absence of a caller's format spec, try to auto detect.
745 // Assume "sigrok session file" upon lookup miss.
747 format = device_manager_.context()->input_format_match(file_name.toStdString());
750 set_device(shared_ptr<devices::Device>(
751 new devices::InputFile(
752 device_manager_.context(),
753 file_name.toStdString(),
756 set_device(shared_ptr<devices::Device>(
757 new devices::SessionFile(
758 device_manager_.context(),
759 file_name.toStdString())));
761 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
766 MainWindow::show_session_error(errorMessage, "");
770 // Use the input file with .pvs extension if no setup file was given
771 if (setup_file_name.isEmpty()) {
772 setup_file_name = file_name;
773 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
774 setup_file_name.append(".pvs");
777 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
778 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
779 restore_setup(settings_storage);
782 main_bar_->update_device_list();
784 start_capture([&, errorMessage](QString infoMessage) {
785 Q_EMIT session_error_raised(errorMessage, infoMessage); });
787 // Only set save path if we loaded an srzip file
788 if (dynamic_pointer_cast<devices::SessionFile>(device_))
789 set_save_path(QFileInfo(file_name).absolutePath());
791 set_name(QFileInfo(file_name).fileName());
794 Session::capture_state Session::get_capture_state() const
796 lock_guard<mutex> lock(sampling_mutex_);
797 return capture_state_;
800 void Session::start_capture(function<void (const QString)> error_handler)
803 error_handler(tr("No active device set, can't start acquisition."));
809 // Check that at least one channel is enabled
810 const shared_ptr<sigrok::Device> sr_dev = device_->device();
812 const auto channels = sr_dev->channels();
813 if (!any_of(channels.begin(), channels.end(),
814 [](shared_ptr<Channel> channel) {
815 return channel->enabled(); })) {
816 error_handler(tr("No channels enabled."));
822 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
825 trigger_list_.clear();
826 segment_sample_count_.clear();
828 // Revert name back to default name (e.g. "Session 1") for real devices
829 // as the (possibly saved) data is gone. File devices keep their name.
830 shared_ptr<devices::HardwareDevice> hw_device =
831 dynamic_pointer_cast< devices::HardwareDevice >(device_);
834 name_ = default_name_;
838 acq_start_time_ = Glib::DateTime::create_now_local();
841 sampling_thread_ = std::thread(&Session::sample_thread_proc, this, error_handler);
844 void Session::stop_capture()
846 if (get_capture_state() != Stopped)
849 // Check that sampling stopped
850 if (sampling_thread_.joinable())
851 sampling_thread_.join();
854 void Session::register_view(shared_ptr<views::ViewBase> view)
859 views_.push_back(view);
861 // Add all device signals
864 // Add all other signals
865 vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
867 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
868 const int sb_exists = count_if(
869 view_signalbases.cbegin(), view_signalbases.cend(),
870 [&](const shared_ptr<data::SignalBase> &sb) {
871 return sb == signalbase;
874 // Add the signal to the view if it doesn't have it yet
876 switch (signalbase->type()) {
877 case data::SignalBase::AnalogChannel:
878 case data::SignalBase::LogicChannel:
879 case data::SignalBase::MathChannel:
880 view->add_signalbase(signalbase);
882 case data::SignalBase::DecodeChannel:
884 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
893 void Session::deregister_view(shared_ptr<views::ViewBase> view)
895 views_.erase(std::remove_if(views_.begin(), views_.end(),
896 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
899 if (views_.empty()) {
902 // Without a view there can be no main bar
907 bool Session::has_view(shared_ptr<views::ViewBase> view)
909 for (shared_ptr<views::ViewBase>& v : views_)
916 double Session::get_samplerate() const
918 double samplerate = 0.0;
920 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
922 const vector< shared_ptr<pv::data::Segment> > segments =
924 for (const shared_ptr<pv::data::Segment>& s : segments)
925 samplerate = max(samplerate, s->samplerate());
927 // If there is no sample rate given we use samples as unit
928 if (samplerate == 0.0)
934 Glib::DateTime Session::get_acquisition_start_time() const
936 return acq_start_time_;
939 uint32_t Session::get_highest_segment_id() const
941 return highest_segment_id_;
944 uint64_t Session::get_segment_sample_count(uint32_t segment_id) const
946 if (segment_id < segment_sample_count_.size())
947 return segment_sample_count_[segment_id];
952 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
954 vector<util::Timestamp> result;
956 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
957 if (entry.first == segment_id)
958 result.push_back(entry.second);
963 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
968 uint32_t Session::get_signal_count(data::SignalBase::ChannelType type) const
970 return count_if(signalbases_.begin(), signalbases_.end(),
971 [&] (shared_ptr<SignalBase> sb) { return sb->type() == type; });
974 uint32_t Session::get_next_signal_index(data::SignalBase::ChannelType type)
976 next_index_list_[type]++;
977 return next_index_list_[type];
980 void Session::add_generated_signal(shared_ptr<data::SignalBase> signal)
982 signalbases_.push_back(signal);
984 for (shared_ptr<views::ViewBase>& view : views_)
985 view->add_signalbase(signal);
990 void Session::remove_generated_signal(shared_ptr<data::SignalBase> signal)
995 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
996 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
999 for (shared_ptr<views::ViewBase>& view : views_)
1000 view->remove_signalbase(signal);
1005 #ifdef ENABLE_DECODE
1006 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
1008 shared_ptr<data::DecodeSignal> signal;
1011 // Create the decode signal
1012 signal = make_shared<data::DecodeSignal>(*this);
1014 signalbases_.push_back(signal);
1016 // Add the decode signal to all views
1017 for (shared_ptr<views::ViewBase>& view : views_)
1018 view->add_decode_signal(signal);
1019 } catch (runtime_error& e) {
1020 remove_decode_signal(signal);
1029 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
1034 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
1035 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
1036 signalbases_.end());
1038 for (shared_ptr<views::ViewBase>& view : views_)
1039 view->remove_decode_signal(signal);
1045 bool Session::all_segments_complete(uint32_t segment_id) const
1047 bool all_complete = true;
1049 for (const shared_ptr<data::SignalBase>& base : signalbases_)
1050 if (!base->segment_is_complete(segment_id))
1051 all_complete = false;
1053 return all_complete;
1056 MetadataObjManager* Session::metadata_obj_manager()
1058 return &metadata_obj_manager_;
1061 void Session::set_capture_state(capture_state state)
1063 if (state == capture_state_)
1066 if (state == Running)
1067 acq_time_.restart();
1068 if (state == Stopped)
1069 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
1072 lock_guard<mutex> lock(sampling_mutex_);
1073 capture_state_ = state;
1076 capture_state_changed(state);
1079 void Session::update_signals()
1082 signalbases_.clear();
1083 logic_data_.reset();
1084 for (shared_ptr<views::ViewBase>& view : views_) {
1085 view->clear_signalbases();
1086 #ifdef ENABLE_DECODE
1087 view->clear_decode_signals();
1093 lock_guard<recursive_mutex> lock(data_mutex_);
1095 const shared_ptr<sigrok::Device> sr_dev = device_->device();
1097 signalbases_.clear();
1098 logic_data_.reset();
1099 for (shared_ptr<views::ViewBase>& view : views_) {
1100 view->clear_signalbases();
1101 #ifdef ENABLE_DECODE
1102 view->clear_decode_signals();
1108 // Detect what data types we will receive
1109 auto channels = sr_dev->channels();
1110 unsigned int logic_channel_count = count_if(
1111 channels.begin(), channels.end(),
1112 [] (shared_ptr<Channel> channel) {
1113 return channel->type() == sigrok::ChannelType::LOGIC; });
1115 // Create a common data container for the logic signalbases
1117 lock_guard<recursive_mutex> data_lock(data_mutex_);
1119 if (logic_channel_count == 0) {
1120 logic_data_.reset();
1121 } else if (!logic_data_ ||
1122 logic_data_->num_channels() != logic_channel_count) {
1123 logic_data_.reset(new data::Logic(logic_channel_count));
1124 assert(logic_data_);
1128 // Create signalbases if necessary
1129 for (auto channel : sr_dev->channels()) {
1131 // Try to find the channel in the list of existing signalbases
1132 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1133 [&](const shared_ptr<SignalBase> &sb) { return sb->channel() == channel; });
1135 // Not found, let's make a signalbase for it
1136 if (iter == signalbases_.cend()) {
1137 shared_ptr<SignalBase> signalbase;
1138 switch(channel->type()->id()) {
1139 case SR_CHANNEL_LOGIC:
1140 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::LogicChannel);
1141 signalbases_.push_back(signalbase);
1143 all_signal_data_.insert(logic_data_);
1144 signalbase->set_data(logic_data_);
1146 connect(this, SIGNAL(capture_state_changed(int)),
1147 signalbase.get(), SLOT(on_capture_state_changed(int)));
1150 case SR_CHANNEL_ANALOG:
1151 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::AnalogChannel);
1152 signalbases_.push_back(signalbase);
1154 shared_ptr<data::Analog> data(new data::Analog());
1155 all_signal_data_.insert(data);
1156 signalbase->set_data(data);
1158 connect(this, SIGNAL(capture_state_changed(int)),
1159 signalbase.get(), SLOT(on_capture_state_changed(int)));
1165 // Create and assign default signal groups if needed
1166 if (signal_groups_.empty()) {
1167 for (auto& entry : sr_dev->channel_groups()) {
1168 const shared_ptr<sigrok::ChannelGroup>& group = entry.second;
1170 if (group->channels().size() <= 1)
1173 SignalGroup* sg = new SignalGroup(QString::fromStdString(entry.first));
1174 for (const shared_ptr<sigrok::Channel>& channel : group->channels()) {
1175 for (shared_ptr<data::SignalBase> s : signalbases_) {
1176 if (s->channel() == channel) {
1177 sg->append_signal(s);
1182 signal_groups_.emplace_back(sg);
1187 for (shared_ptr<views::ViewBase>& viewbase : views_) {
1188 vector< shared_ptr<SignalBase> > view_signalbases =
1189 viewbase->signalbases();
1191 // Add all non-decode signalbases that don't yet exist in the view
1192 for (shared_ptr<SignalBase>& session_sb : signalbases_) {
1193 if (session_sb->type() == SignalBase::DecodeChannel)
1196 const auto iter = find_if(view_signalbases.cbegin(), view_signalbases.cend(),
1197 [&](const shared_ptr<SignalBase> &sb) { return sb == session_sb; });
1199 if (iter == view_signalbases.cend())
1200 viewbase->add_signalbase(session_sb);
1203 // Remove all non-decode signalbases that no longer exist
1204 for (shared_ptr<SignalBase>& view_sb : view_signalbases) {
1205 if (view_sb->type() == SignalBase::DecodeChannel)
1208 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1209 [&](const shared_ptr<SignalBase> &sb) { return sb == view_sb; });
1211 if (iter == signalbases_.cend())
1212 viewbase->remove_signalbase(view_sb);
1219 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1220 shared_ptr<sigrok::Channel> channel) const
1222 for (shared_ptr<data::SignalBase> sig : signalbases_) {
1224 if (sig->channel() == channel)
1227 return shared_ptr<data::SignalBase>();
1230 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1232 assert(error_handler);
1235 pipeline_ = Pipeline::create();
1237 source_ = ElementFactory::create_element("filesrc", "source");
1238 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1240 pipeline_->add(source_)->add(sink_);
1241 source_->link(sink_);
1243 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1245 sink_->set_property("emit-signals", TRUE);
1246 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1248 // Get the bus from the pipeline and add a bus watch to the default main context
1249 RefPtr<Bus> bus = pipeline_->get_bus();
1250 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1252 // Start pipeline and Wait until it finished processing
1253 pipeline_done_interrupt_ = false;
1254 pipeline_->set_state(Gst::STATE_PLAYING);
1256 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1257 pipeline_done_cond_.wait(pipeline_done_lock_);
1259 // Let the pipeline free all resources
1260 pipeline_->set_state(Gst::STATE_NULL);
1267 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1268 } catch (Error& e) {
1269 cur_samplerate_ = 0;
1272 out_of_memory_ = false;
1275 lock_guard<recursive_mutex> lock(data_mutex_);
1276 cur_logic_segment_.reset();
1277 cur_analog_segments_.clear();
1278 for (shared_ptr<data::SignalBase> sb : signalbases_)
1279 sb->clear_sample_data();
1281 highest_segment_id_ = -1;
1282 frame_began_ = false;
1286 } catch (Error& e) {
1287 error_handler(e.what());
1291 set_capture_state(device_->session()->trigger() ?
1292 AwaitingTrigger : Running);
1296 } catch (Error& e) {
1297 error_handler(e.what());
1298 set_capture_state(Stopped);
1300 } catch (QString& e) {
1302 set_capture_state(Stopped);
1306 set_capture_state(Stopped);
1308 // Confirm that SR_DF_END was received
1309 if (cur_logic_segment_)
1310 qDebug() << "WARNING: SR_DF_END was not received.";
1313 // Optimize memory usage
1314 free_unused_memory();
1316 // We now have unsaved data unless we just "captured" from a file
1317 shared_ptr<devices::File> file_device =
1318 dynamic_pointer_cast<devices::File>(device_);
1321 data_saved_ = false;
1324 error_handler(tr("Out of memory, acquisition stopped."));
1327 void Session::free_unused_memory()
1329 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1330 const vector< shared_ptr<data::Segment> > segments = data->segments();
1332 for (const shared_ptr<data::Segment>& segment : segments)
1333 segment->free_unused_memory();
1337 void Session::signal_new_segment()
1339 int new_segment_id = 0;
1341 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1343 // Determine new frame/segment number, assuming that all
1344 // signals have the same number of frames/segments
1345 if (cur_logic_segment_) {
1346 new_segment_id = logic_data_->get_segment_count() - 1;
1348 shared_ptr<sigrok::Channel> any_channel =
1349 (*cur_analog_segments_.begin()).first;
1351 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1354 shared_ptr<data::Analog> data(base->analog_data());
1357 new_segment_id = data->get_segment_count() - 1;
1361 if (new_segment_id > highest_segment_id_) {
1362 highest_segment_id_ = new_segment_id;
1363 segment_sample_count_.emplace_back(0);
1364 new_segment(highest_segment_id_);
1368 void Session::signal_segment_completed()
1372 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1373 // We only care about analog and logic channels, not derived ones
1374 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1375 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1379 if (signalbase->type() == data::SignalBase::LogicChannel) {
1380 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1385 if (segment_id >= 0)
1386 segment_completed(segment_id);
1390 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1394 if ((message->get_source() == pipeline_) && \
1395 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1396 pipeline_done_cond_.notify_one();
1398 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1403 Gst::FlowReturn Session::on_gst_new_sample()
1405 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1406 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1408 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1409 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1410 Gst::MapInfo mapinfo;
1411 buf_mem->map(mapinfo, Gst::MAP_READ);
1413 shared_ptr<sigrok::Packet> logic_packet =
1414 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1417 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1418 } catch (bad_alloc&) {
1419 out_of_memory_ = true;
1421 buf_mem->unmap(mapinfo);
1422 return Gst::FLOW_ERROR;
1425 buf_mem->unmap(mapinfo);
1428 return Gst::FLOW_OK;
1432 void Session::feed_in_header()
1434 // Nothing to do here for now
1437 void Session::feed_in_meta(shared_ptr<Meta> meta)
1439 for (auto& entry : meta->config()) {
1440 switch (entry.first->id()) {
1441 case SR_CONF_SAMPLERATE:
1442 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1445 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1453 void Session::feed_in_trigger()
1455 // The channel containing most samples should be most accurate
1456 uint64_t sample_count = 0;
1459 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1461 uint64_t temp_count = 0;
1463 const vector< shared_ptr<pv::data::Segment> > segments =
1465 for (const shared_ptr<pv::data::Segment> &s : segments)
1466 temp_count += s->get_sample_count();
1468 if (temp_count > sample_count)
1469 sample_count = temp_count;
1473 uint32_t segment_id = 0; // Default segment when no frames are used
1475 // If a frame began, we'd ideally be able to use the highest segment ID for
1476 // the trigger. However, as new segments are only created when logic or
1477 // analog data comes in, this doesn't work if the trigger appears right
1478 // after the beginning of the frame, before any sample data.
1479 // For this reason, we use highest segment ID + 1 if no sample data came in
1480 // yet and the highest segment ID otherwise.
1482 segment_id = highest_segment_id_;
1483 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1487 // TODO Create timestamp from segment start time + segment's current sample count
1488 util::Timestamp timestamp = sample_count / get_samplerate();
1489 trigger_list_.emplace_back(segment_id, timestamp);
1490 trigger_event(segment_id, timestamp);
1493 void Session::feed_in_frame_begin()
1495 frame_began_ = true;
1498 void Session::feed_in_frame_end()
1504 lock_guard<recursive_mutex> lock(data_mutex_);
1506 if (cur_logic_segment_)
1507 cur_logic_segment_->set_complete();
1509 for (auto& entry : cur_analog_segments_) {
1510 shared_ptr<data::AnalogSegment> segment = entry.second;
1511 segment->set_complete();
1514 cur_logic_segment_.reset();
1515 cur_analog_segments_.clear();
1518 frame_began_ = false;
1520 signal_segment_completed();
1523 void Session::feed_in_logic(shared_ptr<sigrok::Logic> logic)
1525 if (logic->data_length() == 0) {
1526 qDebug() << "WARNING: Received logic packet with 0 samples.";
1530 if (logic->unit_size() > 8)
1531 throw QString(tr("Can't handle more than 64 logic channels."));
1533 if (!cur_samplerate_)
1535 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1536 } catch (Error& e) {
1540 lock_guard<recursive_mutex> lock(data_mutex_);
1543 // The only reason logic_data_ would not have been created is
1544 // if it was not possible to determine the signals when the
1545 // device was created.
1549 if (!cur_logic_segment_) {
1550 // This could be the first packet after a trigger
1551 set_capture_state(Running);
1553 // Create a new data segment
1554 cur_logic_segment_ = make_shared<data::LogicSegment>(
1555 *logic_data_, logic_data_->get_segment_count(),
1556 logic->unit_size(), cur_samplerate_);
1557 logic_data_->push_segment(cur_logic_segment_);
1559 signal_new_segment();
1562 cur_logic_segment_->append_payload(logic);
1564 segment_sample_count_[highest_segment_id_] =
1565 max(segment_sample_count_[highest_segment_id_], cur_logic_segment_->get_sample_count());
1570 void Session::feed_in_analog(shared_ptr<sigrok::Analog> analog)
1572 if (analog->num_samples() == 0) {
1573 qDebug() << "WARNING: Received analog packet with 0 samples.";
1577 if (!cur_samplerate_)
1579 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1580 } catch (Error& e) {
1584 lock_guard<recursive_mutex> lock(data_mutex_);
1586 const vector<shared_ptr<Channel>> channels = analog->channels();
1587 bool sweep_beginning = false;
1589 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1590 analog->get_data_as_float(data.get());
1592 if (signalbases_.empty())
1595 float *channel_data = data.get();
1596 for (auto& channel : channels) {
1597 shared_ptr<data::AnalogSegment> segment;
1599 // Try to get the segment of the channel
1600 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1601 iterator iter = cur_analog_segments_.find(channel);
1602 if (iter != cur_analog_segments_.end())
1603 segment = (*iter).second;
1605 // If no segment was found, this means we haven't
1606 // created one yet. i.e. this is the first packet
1607 // in the sweep containing this segment.
1608 sweep_beginning = true;
1610 // Find the analog data associated with the channel
1611 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1614 shared_ptr<data::Analog> data(base->analog_data());
1617 // Create a segment, keep it in the maps of channels
1618 segment = make_shared<data::AnalogSegment>(
1619 *data, data->get_segment_count(), cur_samplerate_);
1620 cur_analog_segments_[channel] = segment;
1622 // Push the segment into the analog data.
1623 data->push_segment(segment);
1625 signal_new_segment();
1630 // Append the samples in the segment
1631 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1634 segment_sample_count_[highest_segment_id_] =
1635 max(segment_sample_count_[highest_segment_id_], segment->get_sample_count());
1638 if (sweep_beginning) {
1639 // This could be the first packet after a trigger
1640 set_capture_state(Running);
1646 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1647 shared_ptr<Packet> packet)
1652 assert(device == device_->device());
1655 switch (packet->type()->id()) {
1661 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1670 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1671 } catch (bad_alloc&) {
1672 out_of_memory_ = true;
1679 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1680 } catch (bad_alloc&) {
1681 out_of_memory_ = true;
1686 case SR_DF_FRAME_BEGIN:
1687 feed_in_frame_begin();
1690 case SR_DF_FRAME_END:
1691 feed_in_frame_end();
1695 // Strictly speaking, this is performed when a frame end marker was
1696 // received, so there's no point doing this again. However, not all
1697 // devices use frames, and for those devices, we need to do it here.
1699 lock_guard<recursive_mutex> lock(data_mutex_);
1701 if (cur_logic_segment_)
1702 cur_logic_segment_->set_complete();
1704 for (auto& entry : cur_analog_segments_) {
1705 shared_ptr<data::AnalogSegment> segment = entry.second;
1706 segment->set_complete();
1709 cur_logic_segment_.reset();
1710 cur_analog_segments_.clear();
1719 void Session::on_data_saved()
1724 #ifdef ENABLE_DECODE
1725 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1727 assert(decoders.size() > 0);
1729 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1732 for (unsigned int i = 0; i < decoders.size(); i++) {
1733 const srd_decoder* d = decoders[i];
1734 signal->stack_decoder(d, !(i < decoders.size() - 1));