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/>.
30 #include "devicemanager.hpp"
31 #include "mainwindow.hpp"
32 #include "session.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>
57 #include <gstreamermm.h>
58 #include <libsigrokflow/libsigrokflow.hpp>
62 #include <libsigrokdecode/libsigrokdecode.h>
63 #include "data/decodesignal.hpp"
67 using std::dynamic_pointer_cast;
71 using std::lock_guard;
73 using std::make_shared;
79 using std::recursive_mutex;
80 using std::runtime_error;
81 using std::shared_ptr;
84 using std::unique_lock;
86 using std::unique_ptr;
90 using sigrok::Channel;
91 using sigrok::ConfigKey;
92 using sigrok::DatafeedCallbackFunction;
94 using sigrok::InputFormat;
98 using sigrok::Session;
100 using Glib::VariantBase;
104 using Gst::ElementFactory;
108 using pv::util::Timestamp;
109 using pv::views::trace::Signal;
110 using pv::views::trace::AnalogSignal;
111 using pv::views::trace::LogicSignal;
115 shared_ptr<sigrok::Context> Session::sr_context;
117 Session::Session(DeviceManager &device_manager, QString name) :
118 device_manager_(device_manager),
121 capture_state_(Stopped),
129 // Stop and join to the thread
133 DeviceManager& Session::device_manager()
135 return device_manager_;
138 const DeviceManager& Session::device_manager() const
140 return device_manager_;
143 shared_ptr<sigrok::Session> Session::session() const
146 return shared_ptr<sigrok::Session>();
147 return device_->session();
150 shared_ptr<devices::Device> Session::device() const
155 QString Session::name() const
160 void Session::set_name(QString name)
162 if (default_name_.isEmpty())
163 default_name_ = name;
170 const vector< shared_ptr<views::ViewBase> > Session::views() const
175 shared_ptr<views::ViewBase> Session::main_view() const
180 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
182 main_bar_ = main_bar;
185 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
190 bool Session::data_saved() const
195 void Session::save_setup(QSettings &settings) const
199 // Save channels and decoders
200 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
202 if (base->is_decode_signal()) {
203 settings.beginGroup("decode_signal" + QString::number(i++));
204 base->save_settings(settings);
209 settings.beginGroup(base->internal_name());
210 base->save_settings(settings);
215 settings.setValue("decode_signals", i);
217 // Save view states and their signal settings
218 // Note: main_view must be saved as view0
220 settings.beginGroup("view" + QString::number(i++));
221 main_view_->save_settings(settings);
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);
233 settings.setValue("views", i);
237 for (const shared_ptr<views::ViewBase>& vb : views_) {
238 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(vb);
240 for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
242 const shared_ptr<views::trace::Flag> flag =
243 dynamic_pointer_cast<views::trace::Flag>(time_item);
245 if (!flag->enabled())
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());
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());
271 settings.setValue("meta_objs", i);
274 void Session::save_settings(QSettings &settings) const
276 map<string, string> dev_info;
277 list<string> key_list;
280 shared_ptr<devices::HardwareDevice> hw_device =
281 dynamic_pointer_cast< devices::HardwareDevice >(device_);
284 settings.setValue("device_type", "hardware");
285 settings.beginGroup("device");
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");
293 dev_info = device_manager_.get_device_info(device_);
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()));
300 settings.remove(QString::fromUtf8(key.c_str()));
306 shared_ptr<devices::SessionFile> sessionfile_device =
307 dynamic_pointer_cast<devices::SessionFile>(device_);
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()));
317 shared_ptr<devices::InputFile> inputfile_device =
318 dynamic_pointer_cast<devices::InputFile>(device_);
320 if (inputfile_device) {
321 settings.setValue("device_type", "inputfile");
322 settings.beginGroup("device");
323 inputfile_device->save_meta_to_settings(settings);
327 save_setup(settings);
331 void Session::restore_setup(QSettings &settings)
334 for (shared_ptr<data::SignalBase> base : signalbases_) {
335 settings.beginGroup(base->internal_name());
336 base->restore_settings(settings);
342 int decode_signals = settings.value("decode_signals").toInt();
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);
353 int views = settings.value("views").toInt();
355 for (int i = 0; i < views; i++) {
356 settings.beginGroup("view" + QString::number(i));
359 views::ViewType type = (views::ViewType)settings.value("type").toInt();
360 add_view(type, this);
361 views_.back()->restore_settings(settings);
363 main_view_->restore_settings(settings);
368 // Restore meta objects like markers and cursors
369 int meta_objs = settings.value("meta_objs").toInt();
371 for (int i = 0; i < meta_objs; i++) {
372 settings.beginGroup("meta_obj" + QString::number(i));
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());
380 tv = dynamic_pointer_cast<views::trace::View>(vb);
382 const QString type = settings.value("type").toString();
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());
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);
401 void Session::restore_settings(QSettings &settings)
403 shared_ptr<devices::Device> device;
405 const QString device_type = settings.value("device_type").toString();
407 if (device_type == "hardware") {
408 map<string, string> dev_info;
409 list<string> key_list;
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");
419 for (string key : key_list) {
420 const QString k = QString::fromStdString(key);
421 if (!settings.contains(k))
424 const string value = settings.value(k).toString().toStdString();
426 dev_info.insert(make_pair(key, value));
429 if (dev_info.count("model") > 0)
430 device = device_manager_.find_device_from_info(dev_info);
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();
444 if (QFileInfo(filename).isReadable()) {
445 device = make_shared<devices::SessionFile>(device_manager_.context(),
446 filename.toStdString());
450 if (device_type == "inputfile") {
451 settings.beginGroup("device");
452 device = make_shared<devices::InputFile>(device_manager_.context(),
460 start_capture([](QString infoMessage) {
461 // TODO Emulate noquote()
462 qDebug() << "Session error:" << infoMessage; });
464 set_name(QString::fromStdString(
465 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
470 restore_setup(settings);
473 void Session::select_device(shared_ptr<devices::Device> device)
479 set_default_device();
480 } catch (const QString &e) {
481 MainWindow::show_session_error(tr("Failed to select device"), e);
485 void Session::set_device(shared_ptr<devices::Device> device)
489 // Ensure we are not capturing before setting the device
497 // Revert name back to default name (e.g. "Session 1") as the data is gone
498 name_ = default_name_;
501 // Remove all stored data and reset all views
502 for (shared_ptr<views::ViewBase> view : views_) {
503 view->clear_signals();
505 view->clear_decode_signals();
507 view->reset_view_state();
509 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
511 all_signal_data_.clear();
512 signalbases_.clear();
513 cur_logic_segment_.reset();
515 for (auto& entry : cur_analog_segments_) {
516 shared_ptr<sigrok::Channel>(entry.first).reset();
517 shared_ptr<data::AnalogSegment>(entry.second).reset();
524 device_ = move(device);
528 } catch (const QString &e) {
530 MainWindow::show_session_error(tr("Failed to open device"), e);
534 device_->session()->add_datafeed_callback([=]
535 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
536 data_feed_in(device, packet);
545 void Session::set_default_device()
547 const list< shared_ptr<devices::HardwareDevice> > &devices =
548 device_manager_.devices();
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);
560 bool Session::using_file_device() const
562 shared_ptr<devices::SessionFile> sessionfile_device =
563 dynamic_pointer_cast<devices::SessionFile>(device_);
565 shared_ptr<devices::InputFile> inputfile_device =
566 dynamic_pointer_cast<devices::InputFile>(device_);
568 return (sessionfile_device || inputfile_device);
572 * Convert generic options to data types that are specific to InputFormat.
574 * @param[in] user_spec Vector of tokenized words, string format.
575 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
577 * @return Map of options suitable for InputFormat::create_input().
579 map<string, Glib::VariantBase>
580 Session::input_format_options(vector<string> user_spec,
581 map<string, shared_ptr<Option>> fmt_opts)
583 map<string, Glib::VariantBase> result;
585 for (auto& entry : user_spec) {
587 * Split key=value specs. Accept entries without separator
588 * (for simplified boolean specifications).
591 size_t pos = entry.find("=");
592 if (pos == std::string::npos) {
596 key = entry.substr(0, pos);
597 val = entry.substr(pos + 1);
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
606 auto found = fmt_opts.find(key);
607 if (found == fmt_opts.end())
609 shared_ptr<Option> opt = found->second;
610 result[key] = opt->parse_string(val);
616 void Session::load_init_file(const string &file_name,
617 const string &format, const string &setup_file_name)
619 shared_ptr<InputFormat> input_format;
620 map<string, Glib::VariantBase> input_opts;
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)));
636 input_format = (*iter).second;
637 input_opts = input_format_options(user_opts,
638 input_format->options());
641 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
642 input_format, input_opts);
645 void Session::load_file(QString file_name, QString setup_file_name,
646 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
648 const QString errorMessage(
649 QString("Failed to load file %1").arg(file_name));
651 // In the absence of a caller's format spec, try to auto detect.
652 // Assume "sigrok session file" upon lookup miss.
654 format = device_manager_.context()->input_format_match(file_name.toStdString());
657 set_device(shared_ptr<devices::Device>(
658 new devices::InputFile(
659 device_manager_.context(),
660 file_name.toStdString(),
663 set_device(shared_ptr<devices::Device>(
664 new devices::SessionFile(
665 device_manager_.context(),
666 file_name.toStdString())));
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();
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");
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);
686 main_bar_->update_device_list();
688 start_capture([&, errorMessage](QString infoMessage) {
689 MainWindow::show_session_error(errorMessage, infoMessage); });
691 set_name(QFileInfo(file_name).fileName());
694 Session::capture_state Session::get_capture_state() const
696 lock_guard<mutex> lock(sampling_mutex_);
697 return capture_state_;
700 void Session::start_capture(function<void (const QString)> error_handler)
703 error_handler(tr("No active device set, can't start acquisition."));
709 // Check that at least one channel is enabled
710 const shared_ptr<sigrok::Device> sr_dev = device_->device();
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."));
722 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
725 trigger_list_.clear();
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_);
733 name_ = default_name_;
738 sampling_thread_ = std::thread(
739 &Session::sample_thread_proc, this, error_handler);
742 void Session::stop_capture()
744 if (get_capture_state() != Stopped)
747 // Check that sampling stopped
748 if (sampling_thread_.joinable())
749 sampling_thread_.join();
752 void Session::register_view(shared_ptr<views::ViewBase> view)
757 views_.push_back(view);
759 // Add all device signals
762 // Add all other signals
763 vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
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;
772 // Add the signal to the view if it doesn't have it yet
774 switch (signalbase->type()) {
775 case data::SignalBase::AnalogChannel:
776 case data::SignalBase::LogicChannel:
777 case data::SignalBase::MathChannel:
778 view->add_signalbase(signalbase);
780 case data::SignalBase::DecodeChannel:
782 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
791 void Session::deregister_view(shared_ptr<views::ViewBase> view)
793 views_.erase(std::remove_if(views_.begin(), views_.end(),
794 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
797 if (views_.empty()) {
800 // Without a view there can be no main bar
805 bool Session::has_view(shared_ptr<views::ViewBase> view)
807 for (shared_ptr<views::ViewBase>& v : views_)
814 double Session::get_samplerate() const
816 double samplerate = 0.0;
818 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
820 const vector< shared_ptr<pv::data::Segment> > segments =
822 for (const shared_ptr<pv::data::Segment>& s : segments)
823 samplerate = max(samplerate, s->samplerate());
825 // If there is no sample rate given we use samples as unit
826 if (samplerate == 0.0)
832 uint32_t Session::get_segment_count() const
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();
844 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
846 vector<util::Timestamp> result;
848 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
849 if (entry.first == segment_id)
850 result.push_back(entry.second);
855 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
860 bool Session::all_segments_complete(uint32_t segment_id) const
862 bool all_complete = true;
864 for (const shared_ptr<data::SignalBase>& base : signalbases_)
865 if (!base->segment_is_complete(segment_id))
866 all_complete = false;
872 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
874 shared_ptr<data::DecodeSignal> signal;
877 // Create the decode signal
878 signal = make_shared<data::DecodeSignal>(*this);
880 signalbases_.push_back(signal);
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);
895 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
897 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
898 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
901 for (shared_ptr<views::ViewBase>& view : views_)
902 view->remove_decode_signal(signal);
908 void Session::set_capture_state(capture_state state)
912 if (state == Running)
914 if (state == Stopped)
915 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
918 lock_guard<mutex> lock(sampling_mutex_);
919 changed = capture_state_ != state;
920 capture_state_ = state;
924 capture_state_changed(state);
927 void Session::update_signals()
930 signalbases_.clear();
932 for (shared_ptr<views::ViewBase>& view : views_) {
933 view->clear_signals();
935 view->clear_decode_signals();
941 lock_guard<recursive_mutex> lock(data_mutex_);
943 const shared_ptr<sigrok::Device> sr_dev = device_->device();
945 signalbases_.clear();
947 for (shared_ptr<views::ViewBase>& view : views_) {
948 view->clear_signals();
950 view->clear_decode_signals();
956 // Detect what data types we will receive
957 auto channels = sr_dev->channels();
958 unsigned int logic_channel_count = count_if(
959 channels.begin(), channels.end(),
960 [] (shared_ptr<Channel> channel) {
961 return channel->type() == sigrok::ChannelType::LOGIC; });
963 // Create data containers for the logic data segments
965 lock_guard<recursive_mutex> data_lock(data_mutex_);
967 if (logic_channel_count == 0) {
969 } else if (!logic_data_ ||
970 logic_data_->num_channels() != logic_channel_count) {
971 logic_data_.reset(new data::Logic(
972 logic_channel_count));
977 // Make the signals list
978 for (shared_ptr<views::ViewBase>& viewbase : views_) {
979 views::trace::View *trace_view =
980 qobject_cast<views::trace::View*>(viewbase.get());
983 vector< shared_ptr<Signal> > prev_sigs(trace_view->signals());
984 trace_view->clear_signals();
986 for (auto channel : sr_dev->channels()) {
987 shared_ptr<data::SignalBase> signalbase;
988 shared_ptr<Signal> signal;
990 // Find the channel in the old signals
991 const auto iter = find_if(
992 prev_sigs.cbegin(), prev_sigs.cend(),
993 [&](const shared_ptr<Signal> &s) {
994 return s->base()->channel() == channel;
996 if (iter != prev_sigs.end()) {
997 // Copy the signal from the old set to the new
999 trace_view->add_signal(signal);
1001 // Find the signalbase for this channel if possible
1003 for (const shared_ptr<data::SignalBase>& b : signalbases_)
1004 if (b->channel() == channel)
1007 shared_ptr<Signal> signal;
1009 switch(channel->type()->id()) {
1010 case SR_CHANNEL_LOGIC:
1012 signalbase = make_shared<data::SignalBase>(channel,
1013 data::SignalBase::LogicChannel);
1014 signalbases_.push_back(signalbase);
1016 all_signal_data_.insert(logic_data_);
1017 signalbase->set_data(logic_data_);
1019 connect(this, SIGNAL(capture_state_changed(int)),
1020 signalbase.get(), SLOT(on_capture_state_changed(int)));
1023 signal = shared_ptr<Signal>(new LogicSignal(*this, device_, signalbase));
1026 case SR_CHANNEL_ANALOG:
1029 signalbase = make_shared<data::SignalBase>(channel,
1030 data::SignalBase::AnalogChannel);
1031 signalbases_.push_back(signalbase);
1033 shared_ptr<data::Analog> data(new data::Analog());
1034 all_signal_data_.insert(data);
1035 signalbase->set_data(data);
1037 connect(this, SIGNAL(capture_state_changed(int)),
1038 signalbase.get(), SLOT(on_capture_state_changed(int)));
1041 signal = shared_ptr<Signal>(new AnalogSignal(*this, signalbase));
1050 // New views take their signal settings from the main view
1051 if (!viewbase->is_main_view()) {
1052 shared_ptr<pv::views::trace::View> main_tv =
1053 dynamic_pointer_cast<pv::views::trace::View>(main_view_);
1054 shared_ptr<Signal> main_signal =
1055 main_tv->get_signal_by_signalbase(signalbase);
1056 signal->restore_settings(main_signal->save_settings());
1059 trace_view->add_signal(signal);
1068 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1069 shared_ptr<sigrok::Channel> channel) const
1071 for (shared_ptr<data::SignalBase> sig : signalbases_) {
1073 if (sig->channel() == channel)
1076 return shared_ptr<data::SignalBase>();
1079 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1081 assert(error_handler);
1084 pipeline_ = Pipeline::create();
1086 source_ = ElementFactory::create_element("filesrc", "source");
1087 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1089 pipeline_->add(source_)->add(sink_);
1090 source_->link(sink_);
1092 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1094 sink_->set_property("emit-signals", TRUE);
1095 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1097 // Get the bus from the pipeline and add a bus watch to the default main context
1098 RefPtr<Bus> bus = pipeline_->get_bus();
1099 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1101 // Start pipeline and Wait until it finished processing
1102 pipeline_done_interrupt_ = false;
1103 pipeline_->set_state(Gst::STATE_PLAYING);
1105 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1106 pipeline_done_cond_.wait(pipeline_done_lock_);
1108 // Let the pipeline free all resources
1109 pipeline_->set_state(Gst::STATE_NULL);
1116 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1117 } catch (Error& e) {
1118 cur_samplerate_ = 0;
1121 out_of_memory_ = false;
1124 lock_guard<recursive_mutex> lock(data_mutex_);
1125 cur_logic_segment_.reset();
1126 cur_analog_segments_.clear();
1128 highest_segment_id_ = -1;
1129 frame_began_ = false;
1133 } catch (Error& e) {
1134 error_handler(e.what());
1138 set_capture_state(device_->session()->trigger() ?
1139 AwaitingTrigger : Running);
1143 } catch (Error& e) {
1144 error_handler(e.what());
1145 set_capture_state(Stopped);
1147 } catch (QString& e) {
1149 set_capture_state(Stopped);
1153 set_capture_state(Stopped);
1155 // Confirm that SR_DF_END was received
1156 if (cur_logic_segment_)
1157 qDebug() << "WARNING: SR_DF_END was not received.";
1160 // Optimize memory usage
1161 free_unused_memory();
1163 // We now have unsaved data unless we just "captured" from a file
1164 shared_ptr<devices::File> file_device =
1165 dynamic_pointer_cast<devices::File>(device_);
1168 data_saved_ = false;
1171 error_handler(tr("Out of memory, acquisition stopped."));
1174 void Session::free_unused_memory()
1176 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1177 const vector< shared_ptr<data::Segment> > segments = data->segments();
1179 for (const shared_ptr<data::Segment>& segment : segments)
1180 segment->free_unused_memory();
1184 void Session::signal_new_segment()
1186 int new_segment_id = 0;
1188 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1190 // Determine new frame/segment number, assuming that all
1191 // signals have the same number of frames/segments
1192 if (cur_logic_segment_) {
1193 new_segment_id = logic_data_->get_segment_count() - 1;
1195 shared_ptr<sigrok::Channel> any_channel =
1196 (*cur_analog_segments_.begin()).first;
1198 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1201 shared_ptr<data::Analog> data(base->analog_data());
1204 new_segment_id = data->get_segment_count() - 1;
1208 if (new_segment_id > highest_segment_id_) {
1209 highest_segment_id_ = new_segment_id;
1210 new_segment(highest_segment_id_);
1214 void Session::signal_segment_completed()
1218 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1219 // We only care about analog and logic channels, not derived ones
1220 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1221 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1225 if (signalbase->type() == data::SignalBase::LogicChannel) {
1226 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1231 if (segment_id >= 0)
1232 segment_completed(segment_id);
1236 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1240 if ((message->get_source() == pipeline_) && \
1241 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1242 pipeline_done_cond_.notify_one();
1244 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1249 Gst::FlowReturn Session::on_gst_new_sample()
1251 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1252 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1254 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1255 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1256 Gst::MapInfo mapinfo;
1257 buf_mem->map(mapinfo, Gst::MAP_READ);
1259 shared_ptr<sigrok::Packet> logic_packet =
1260 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1263 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1264 } catch (bad_alloc&) {
1265 out_of_memory_ = true;
1267 buf_mem->unmap(mapinfo);
1268 return Gst::FLOW_ERROR;
1271 buf_mem->unmap(mapinfo);
1274 return Gst::FLOW_OK;
1278 void Session::feed_in_header()
1280 // Nothing to do here for now
1283 void Session::feed_in_meta(shared_ptr<Meta> meta)
1285 for (auto& entry : meta->config()) {
1286 switch (entry.first->id()) {
1287 case SR_CONF_SAMPLERATE:
1288 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1291 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1299 void Session::feed_in_trigger()
1301 // The channel containing most samples should be most accurate
1302 uint64_t sample_count = 0;
1305 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1307 uint64_t temp_count = 0;
1309 const vector< shared_ptr<pv::data::Segment> > segments =
1311 for (const shared_ptr<pv::data::Segment> &s : segments)
1312 temp_count += s->get_sample_count();
1314 if (temp_count > sample_count)
1315 sample_count = temp_count;
1319 uint32_t segment_id = 0; // Default segment when no frames are used
1321 // If a frame began, we'd ideally be able to use the highest segment ID for
1322 // the trigger. However, as new segments are only created when logic or
1323 // analog data comes in, this doesn't work if the trigger appears right
1324 // after the beginning of the frame, before any sample data.
1325 // For this reason, we use highest segment ID + 1 if no sample data came in
1326 // yet and the highest segment ID otherwise.
1328 segment_id = highest_segment_id_;
1329 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1333 // TODO Create timestamp from segment start time + segment's current sample count
1334 util::Timestamp timestamp = sample_count / get_samplerate();
1335 trigger_list_.emplace_back(segment_id, timestamp);
1336 trigger_event(segment_id, timestamp);
1339 void Session::feed_in_frame_begin()
1341 frame_began_ = true;
1344 void Session::feed_in_frame_end()
1350 lock_guard<recursive_mutex> lock(data_mutex_);
1352 if (cur_logic_segment_)
1353 cur_logic_segment_->set_complete();
1355 for (auto& entry : cur_analog_segments_) {
1356 shared_ptr<data::AnalogSegment> segment = entry.second;
1357 segment->set_complete();
1360 cur_logic_segment_.reset();
1361 cur_analog_segments_.clear();
1364 frame_began_ = false;
1366 signal_segment_completed();
1369 void Session::feed_in_logic(shared_ptr<Logic> logic)
1371 if (logic->data_length() == 0) {
1372 qDebug() << "WARNING: Received logic packet with 0 samples.";
1376 if (logic->unit_size() > 8)
1377 throw QString(tr("Can't handle more than 64 logic channels."));
1379 if (!cur_samplerate_)
1381 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1382 } catch (Error& e) {
1386 lock_guard<recursive_mutex> lock(data_mutex_);
1389 // The only reason logic_data_ would not have been created is
1390 // if it was not possible to determine the signals when the
1391 // device was created.
1395 if (!cur_logic_segment_) {
1396 // This could be the first packet after a trigger
1397 set_capture_state(Running);
1399 // Create a new data segment
1400 cur_logic_segment_ = make_shared<data::LogicSegment>(
1401 *logic_data_, logic_data_->get_segment_count(),
1402 logic->unit_size(), cur_samplerate_);
1403 logic_data_->push_segment(cur_logic_segment_);
1405 signal_new_segment();
1408 cur_logic_segment_->append_payload(logic);
1413 void Session::feed_in_analog(shared_ptr<Analog> analog)
1415 if (analog->num_samples() == 0) {
1416 qDebug() << "WARNING: Received analog packet with 0 samples.";
1420 if (!cur_samplerate_)
1422 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1423 } catch (Error& e) {
1427 lock_guard<recursive_mutex> lock(data_mutex_);
1429 const vector<shared_ptr<Channel>> channels = analog->channels();
1430 bool sweep_beginning = false;
1432 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1433 analog->get_data_as_float(data.get());
1435 if (signalbases_.empty())
1438 float *channel_data = data.get();
1439 for (auto& channel : channels) {
1440 shared_ptr<data::AnalogSegment> segment;
1442 // Try to get the segment of the channel
1443 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1444 iterator iter = cur_analog_segments_.find(channel);
1445 if (iter != cur_analog_segments_.end())
1446 segment = (*iter).second;
1448 // If no segment was found, this means we haven't
1449 // created one yet. i.e. this is the first packet
1450 // in the sweep containing this segment.
1451 sweep_beginning = true;
1453 // Find the analog data associated with the channel
1454 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1457 shared_ptr<data::Analog> data(base->analog_data());
1460 // Create a segment, keep it in the maps of channels
1461 segment = make_shared<data::AnalogSegment>(
1462 *data, data->get_segment_count(), cur_samplerate_);
1463 cur_analog_segments_[channel] = segment;
1465 // Push the segment into the analog data.
1466 data->push_segment(segment);
1468 signal_new_segment();
1473 // Append the samples in the segment
1474 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1478 if (sweep_beginning) {
1479 // This could be the first packet after a trigger
1480 set_capture_state(Running);
1486 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1487 shared_ptr<Packet> packet)
1492 assert(device == device_->device());
1495 switch (packet->type()->id()) {
1501 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1510 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1511 } catch (bad_alloc&) {
1512 out_of_memory_ = true;
1519 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1520 } catch (bad_alloc&) {
1521 out_of_memory_ = true;
1526 case SR_DF_FRAME_BEGIN:
1527 feed_in_frame_begin();
1530 case SR_DF_FRAME_END:
1531 feed_in_frame_end();
1535 // Strictly speaking, this is performed when a frame end marker was
1536 // received, so there's no point doing this again. However, not all
1537 // devices use frames, and for those devices, we need to do it here.
1539 lock_guard<recursive_mutex> lock(data_mutex_);
1541 if (cur_logic_segment_)
1542 cur_logic_segment_->set_complete();
1544 for (auto& entry : cur_analog_segments_) {
1545 shared_ptr<data::AnalogSegment> segment = entry.second;
1546 segment->set_complete();
1549 cur_logic_segment_.reset();
1550 cur_analog_segments_.clear();
1559 void Session::on_data_saved()
1564 #ifdef ENABLE_DECODE
1565 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1567 assert(decoders.size() > 0);
1569 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1572 for (unsigned int i = 0; i < decoders.size(); i++) {
1573 const srd_decoder* d = decoders[i];
1574 signal->stack_decoder(d, !(i < decoders.size() - 1));