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::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;
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),
123 capture_state_(Stopped),
131 shutting_down_ = true;
133 // Stop and join to the thread
136 for (SignalGroup* group : signal_groups_) {
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
155 return shared_ptr<sigrok::Session>();
156 return device_->session();
159 shared_ptr<devices::Device> Session::device() const
164 QString Session::name() const
169 void Session::set_name(QString name)
171 if (default_name_.isEmpty())
172 default_name_ = name;
179 QString Session::save_path() const
184 void Session::set_save_path(QString path)
189 const vector< shared_ptr<views::ViewBase> > Session::views() const
194 shared_ptr<views::ViewBase> Session::main_view() const
199 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
201 main_bar_ = main_bar;
204 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
209 bool Session::data_saved() const
214 void Session::save_setup(QSettings &settings) const
218 // Save channels and decoders
219 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
221 if (base->is_decode_signal()) {
222 settings.beginGroup("decode_signal" + QString::number(i++));
223 base->save_settings(settings);
228 settings.beginGroup(base->internal_name());
229 base->save_settings(settings);
234 settings.setValue("decode_signals", i);
236 // Save view states and their signal settings
237 // Note: main_view must be saved as view0
239 settings.beginGroup("view" + QString::number(i++));
240 main_view_->save_settings(settings);
243 for (const shared_ptr<views::ViewBase>& view : views_) {
244 if (view != main_view_) {
245 settings.beginGroup("view" + QString::number(i++));
246 settings.setValue("type", view->get_type());
247 view->save_settings(settings);
252 settings.setValue("views", i);
256 for (const shared_ptr<views::ViewBase>& vb : views_) {
257 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(vb);
259 for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
261 const shared_ptr<views::trace::Flag> flag =
262 dynamic_pointer_cast<views::trace::Flag>(time_item);
264 if (!flag->enabled())
267 settings.beginGroup("meta_obj" + QString::number(i++));
268 settings.setValue("type", "time_marker");
269 settings.setValue("assoc_view", view_id);
270 GlobalSettings::store_timestamp(settings, "time", flag->time());
271 settings.setValue("text", flag->get_text());
276 if (tv->cursors_shown()) {
277 settings.beginGroup("meta_obj" + QString::number(i++));
278 settings.setValue("type", "selection");
279 settings.setValue("assoc_view", view_id);
280 const shared_ptr<views::trace::CursorPair> cp = tv->cursors();
281 GlobalSettings::store_timestamp(settings, "start_time", cp->first()->time());
282 GlobalSettings::store_timestamp(settings, "end_time", cp->second()->time());
290 settings.setValue("meta_objs", i);
293 void Session::save_settings(QSettings &settings) const
295 map<string, string> dev_info;
296 list<string> key_list;
299 shared_ptr<devices::HardwareDevice> hw_device =
300 dynamic_pointer_cast< devices::HardwareDevice >(device_);
303 settings.setValue("device_type", "hardware");
304 settings.beginGroup("device");
306 key_list.emplace_back("vendor");
307 key_list.emplace_back("model");
308 key_list.emplace_back("version");
309 key_list.emplace_back("serial_num");
310 key_list.emplace_back("connection_id");
312 dev_info = device_manager_.get_device_info(device_);
314 for (string& key : key_list) {
315 if (dev_info.count(key))
316 settings.setValue(QString::fromUtf8(key.c_str()),
317 QString::fromUtf8(dev_info.at(key).c_str()));
319 settings.remove(QString::fromUtf8(key.c_str()));
325 shared_ptr<devices::SessionFile> sessionfile_device =
326 dynamic_pointer_cast<devices::SessionFile>(device_);
328 if (sessionfile_device) {
329 settings.setValue("device_type", "sessionfile");
330 settings.beginGroup("device");
331 settings.setValue("filename", QString::fromStdString(
332 sessionfile_device->full_name()));
336 shared_ptr<devices::InputFile> inputfile_device =
337 dynamic_pointer_cast<devices::InputFile>(device_);
339 if (inputfile_device) {
340 settings.setValue("device_type", "inputfile");
341 settings.beginGroup("device");
342 inputfile_device->save_meta_to_settings(settings);
346 save_setup(settings);
350 void Session::restore_setup(QSettings &settings)
353 for (shared_ptr<data::SignalBase> base : signalbases_) {
354 settings.beginGroup(base->internal_name());
355 base->restore_settings(settings);
361 int decode_signals = settings.value("decode_signals").toInt();
363 for (int i = 0; i < decode_signals; i++) {
364 settings.beginGroup("decode_signal" + QString::number(i));
365 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
366 signal->restore_settings(settings);
372 int views = settings.value("views").toInt();
374 for (int i = 0; i < views; i++) {
375 settings.beginGroup("view" + QString::number(i));
378 views::ViewType type = (views::ViewType)settings.value("type").toInt();
379 add_view(type, this);
380 views_.back()->restore_settings(settings);
382 main_view_->restore_settings(settings);
387 // Restore meta objects like markers and cursors
388 int meta_objs = settings.value("meta_objs").toInt();
390 for (int i = 0; i < meta_objs; i++) {
391 settings.beginGroup("meta_obj" + QString::number(i));
393 shared_ptr<views::ViewBase> vb;
394 shared_ptr<views::trace::View> tv;
395 if (settings.contains("assoc_view"))
396 vb = views_.at(settings.value("assoc_view").toInt());
399 tv = dynamic_pointer_cast<views::trace::View>(vb);
401 const QString type = settings.value("type").toString();
403 if ((type == "time_marker") && tv) {
404 Timestamp ts = GlobalSettings::restore_timestamp(settings, "time");
405 shared_ptr<views::trace::Flag> flag = tv->add_flag(ts);
406 flag->set_text(settings.value("text").toString());
409 if ((type == "selection") && tv) {
410 Timestamp start = GlobalSettings::restore_timestamp(settings, "start_time");
411 Timestamp end = GlobalSettings::restore_timestamp(settings, "end_time");
412 tv->set_cursors(start, end);
420 void Session::restore_settings(QSettings &settings)
422 shared_ptr<devices::Device> device;
424 const QString device_type = settings.value("device_type").toString();
426 if (device_type == "hardware") {
427 map<string, string> dev_info;
428 list<string> key_list;
430 // Re-select last used device if possible but only if it's not demo
431 settings.beginGroup("device");
432 key_list.emplace_back("vendor");
433 key_list.emplace_back("model");
434 key_list.emplace_back("version");
435 key_list.emplace_back("serial_num");
436 key_list.emplace_back("connection_id");
438 for (string key : key_list) {
439 const QString k = QString::fromStdString(key);
440 if (!settings.contains(k))
443 const string value = settings.value(k).toString().toStdString();
445 dev_info.insert(make_pair(key, value));
448 if (dev_info.count("model") > 0)
449 device = device_manager_.find_device_from_info(dev_info);
459 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
460 if (device_type == "sessionfile") {
461 settings.beginGroup("device");
462 filename = settings.value("filename").toString();
465 if (QFileInfo(filename).isReadable())
466 device = make_shared<devices::SessionFile>(device_manager_.context(),
467 filename.toStdString());
470 if (device_type == "inputfile") {
471 settings.beginGroup("device");
472 device = make_shared<devices::InputFile>(device_manager_.context(),
480 start_capture([](QString infoMessage) {
481 // TODO Emulate noquote()
482 qDebug() << "Session error:" << infoMessage; });
484 set_name(QString::fromStdString(
485 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
487 if (!filename.isEmpty()) {
488 // Only set the save path if we load an srzip file
489 if (device_type == "sessionfile")
490 set_save_path(QFileInfo(filename).absolutePath());
492 set_name(QFileInfo(filename).fileName());
498 restore_setup(settings);
501 void Session::select_device(shared_ptr<devices::Device> device)
507 set_default_device();
508 } catch (const QString &e) {
509 MainWindow::show_session_error(tr("Failed to select device"), e);
513 void Session::set_device(shared_ptr<devices::Device> device)
517 // Ensure we are not capturing before setting the device
525 // Revert name back to default name (e.g. "Session 1") as the data is gone
526 name_ = default_name_;
529 // Remove all stored data and reset all views
530 for (shared_ptr<views::ViewBase> view : views_) {
531 view->clear_signalbases();
533 view->clear_decode_signals();
535 view->reset_view_state();
538 for (SignalGroup* group : signal_groups_) {
542 signal_groups_.clear();
544 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
547 all_signal_data_.clear();
548 signalbases_.clear();
549 cur_logic_segment_.reset();
551 for (auto& entry : cur_analog_segments_) {
552 shared_ptr<sigrok::Channel>(entry.first).reset();
553 shared_ptr<data::AnalogSegment>(entry.second).reset();
560 device_ = move(device);
564 } catch (const QString &e) {
566 MainWindow::show_session_error(tr("Failed to open device"), e);
570 device_->session()->add_datafeed_callback([=]
571 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
572 data_feed_in(device, packet);
581 void Session::set_default_device()
583 const list< shared_ptr<devices::HardwareDevice> > &devices =
584 device_manager_.devices();
589 // Try and find the demo device and select that by default
590 const auto iter = find_if(devices.begin(), devices.end(),
591 [] (const shared_ptr<devices::HardwareDevice> &d) {
592 return d->hardware_device()->driver()->name() == "demo"; });
593 set_device((iter == devices.end()) ? devices.front() : *iter);
596 bool Session::using_file_device() const
598 shared_ptr<devices::SessionFile> sessionfile_device =
599 dynamic_pointer_cast<devices::SessionFile>(device_);
601 shared_ptr<devices::InputFile> inputfile_device =
602 dynamic_pointer_cast<devices::InputFile>(device_);
604 return (sessionfile_device || inputfile_device);
608 * Convert generic options to data types that are specific to InputFormat.
610 * @param[in] user_spec Vector of tokenized words, string format.
611 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
613 * @return Map of options suitable for InputFormat::create_input().
615 map<string, Glib::VariantBase>
616 Session::input_format_options(vector<string> user_spec,
617 map<string, shared_ptr<Option>> fmt_opts)
619 map<string, Glib::VariantBase> result;
621 for (auto& entry : user_spec) {
623 * Split key=value specs. Accept entries without separator
624 * (for simplified boolean specifications).
627 size_t pos = entry.find("=");
628 if (pos == std::string::npos) {
632 key = entry.substr(0, pos);
633 val = entry.substr(pos + 1);
637 * Skip user specifications that are not a member of the
638 * format's set of supported options. Have the text input
639 * spec converted to the required input format specific
642 auto found = fmt_opts.find(key);
643 if (found == fmt_opts.end()) {
644 qCritical() << "Supplied input option" << QString::fromStdString(key) <<
645 "is not a valid option for this input module, it will be ignored!";
649 shared_ptr<Option> opt = found->second;
650 result[key] = opt->parse_string(val);
656 void Session::load_init_file(const string &file_name,
657 const string &format, const string &setup_file_name)
659 shared_ptr<InputFormat> input_format;
660 map<string, Glib::VariantBase> input_opts;
662 if (!format.empty()) {
663 const map<string, shared_ptr<InputFormat> > formats =
664 device_manager_.context()->input_formats();
665 auto user_opts = pv::util::split_string(format, ":");
666 string user_name = user_opts.front();
667 user_opts.erase(user_opts.begin());
668 const auto iter = find_if(formats.begin(), formats.end(),
669 [&](const pair<string, shared_ptr<InputFormat> > f) {
670 return f.first == user_name; });
671 if (iter == formats.end()) {
672 MainWindow::show_session_error(tr("Error"),
673 tr("Unexpected input format: %1").arg(QString::fromStdString(format)));
676 input_format = (*iter).second;
677 input_opts = input_format_options(user_opts,
678 input_format->options());
681 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
682 input_format, input_opts);
685 void Session::load_file(QString file_name, QString setup_file_name,
686 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
688 const QString errorMessage(
689 QString("Failed to load file %1").arg(file_name));
691 // In the absence of a caller's format spec, try to auto detect.
692 // Assume "sigrok session file" upon lookup miss.
694 format = device_manager_.context()->input_format_match(file_name.toStdString());
697 set_device(shared_ptr<devices::Device>(
698 new devices::InputFile(
699 device_manager_.context(),
700 file_name.toStdString(),
703 set_device(shared_ptr<devices::Device>(
704 new devices::SessionFile(
705 device_manager_.context(),
706 file_name.toStdString())));
708 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
709 set_default_device();
710 main_bar_->update_device_list();
714 // Use the input file with .pvs extension if no setup file was given
715 if (setup_file_name.isEmpty()) {
716 setup_file_name = file_name;
717 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
718 setup_file_name.append(".pvs");
721 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
722 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
723 restore_setup(settings_storage);
726 main_bar_->update_device_list();
728 start_capture([&, errorMessage](QString infoMessage) {
729 MainWindow::show_session_error(errorMessage, infoMessage); });
731 // Only set save path if we loaded an srzip file
732 if (dynamic_pointer_cast<devices::SessionFile>(device_))
733 set_save_path(QFileInfo(file_name).absolutePath());
735 set_name(QFileInfo(file_name).fileName());
738 Session::capture_state Session::get_capture_state() const
740 lock_guard<mutex> lock(sampling_mutex_);
741 return capture_state_;
744 void Session::start_capture(function<void (const QString)> error_handler)
747 error_handler(tr("No active device set, can't start acquisition."));
753 // Check that at least one channel is enabled
754 const shared_ptr<sigrok::Device> sr_dev = device_->device();
756 const auto channels = sr_dev->channels();
757 if (!any_of(channels.begin(), channels.end(),
758 [](shared_ptr<Channel> channel) {
759 return channel->enabled(); })) {
760 error_handler(tr("No channels enabled."));
766 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
769 trigger_list_.clear();
771 // Revert name back to default name (e.g. "Session 1") for real devices
772 // as the (possibly saved) data is gone. File devices keep their name.
773 shared_ptr<devices::HardwareDevice> hw_device =
774 dynamic_pointer_cast< devices::HardwareDevice >(device_);
777 name_ = default_name_;
782 sampling_thread_ = std::thread(
783 &Session::sample_thread_proc, this, error_handler);
786 void Session::stop_capture()
788 if (get_capture_state() != Stopped)
791 // Check that sampling stopped
792 if (sampling_thread_.joinable())
793 sampling_thread_.join();
796 void Session::register_view(shared_ptr<views::ViewBase> view)
801 views_.push_back(view);
803 // Add all device signals
806 // Add all other signals
807 vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
809 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
810 const int sb_exists = count_if(
811 view_signalbases.cbegin(), view_signalbases.cend(),
812 [&](const shared_ptr<data::SignalBase> &sb) {
813 return sb == signalbase;
816 // Add the signal to the view if it doesn't have it yet
818 switch (signalbase->type()) {
819 case data::SignalBase::AnalogChannel:
820 case data::SignalBase::LogicChannel:
821 case data::SignalBase::MathChannel:
822 view->add_signalbase(signalbase);
824 case data::SignalBase::DecodeChannel:
826 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
835 void Session::deregister_view(shared_ptr<views::ViewBase> view)
837 views_.erase(std::remove_if(views_.begin(), views_.end(),
838 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
841 if (views_.empty()) {
844 // Without a view there can be no main bar
849 bool Session::has_view(shared_ptr<views::ViewBase> view)
851 for (shared_ptr<views::ViewBase>& v : views_)
858 double Session::get_samplerate() const
860 double samplerate = 0.0;
862 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
864 const vector< shared_ptr<pv::data::Segment> > segments =
866 for (const shared_ptr<pv::data::Segment>& s : segments)
867 samplerate = max(samplerate, s->samplerate());
869 // If there is no sample rate given we use samples as unit
870 if (samplerate == 0.0)
876 uint32_t Session::get_segment_count() const
880 // Find the highest number of segments
881 for (const shared_ptr<data::SignalData>& data : all_signal_data_)
882 if (data->get_segment_count() > value)
883 value = data->get_segment_count();
888 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
890 vector<util::Timestamp> result;
892 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
893 if (entry.first == segment_id)
894 result.push_back(entry.second);
899 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
904 void Session::add_generated_signal(shared_ptr<data::SignalBase> signal)
906 signalbases_.push_back(signal);
908 for (shared_ptr<views::ViewBase>& view : views_)
909 view->add_signalbase(signal);
914 void Session::remove_generated_signal(shared_ptr<data::SignalBase> signal)
919 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
920 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
923 for (shared_ptr<views::ViewBase>& view : views_)
924 view->remove_signalbase(signal);
930 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
932 shared_ptr<data::DecodeSignal> signal;
935 // Create the decode signal
936 signal = make_shared<data::DecodeSignal>(*this);
938 signalbases_.push_back(signal);
940 // Add the decode signal to all views
941 for (shared_ptr<views::ViewBase>& view : views_)
942 view->add_decode_signal(signal);
943 } catch (runtime_error& e) {
944 remove_decode_signal(signal);
953 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
958 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
959 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
962 for (shared_ptr<views::ViewBase>& view : views_)
963 view->remove_decode_signal(signal);
969 bool Session::all_segments_complete(uint32_t segment_id) const
971 bool all_complete = true;
973 for (const shared_ptr<data::SignalBase>& base : signalbases_)
974 if (!base->segment_is_complete(segment_id))
975 all_complete = false;
980 MetadataObjManager* Session::metadata_obj_manager()
982 return &metadata_obj_manager_;
985 void Session::set_capture_state(capture_state state)
989 if (state == Running)
991 if (state == Stopped)
992 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
995 lock_guard<mutex> lock(sampling_mutex_);
996 changed = capture_state_ != state;
997 capture_state_ = state;
1001 capture_state_changed(state);
1004 void Session::update_signals()
1007 signalbases_.clear();
1008 logic_data_.reset();
1009 for (shared_ptr<views::ViewBase>& view : views_) {
1010 view->clear_signalbases();
1011 #ifdef ENABLE_DECODE
1012 view->clear_decode_signals();
1018 lock_guard<recursive_mutex> lock(data_mutex_);
1020 const shared_ptr<sigrok::Device> sr_dev = device_->device();
1022 signalbases_.clear();
1023 logic_data_.reset();
1024 for (shared_ptr<views::ViewBase>& view : views_) {
1025 view->clear_signalbases();
1026 #ifdef ENABLE_DECODE
1027 view->clear_decode_signals();
1033 // Detect what data types we will receive
1034 auto channels = sr_dev->channels();
1035 unsigned int logic_channel_count = count_if(
1036 channels.begin(), channels.end(),
1037 [] (shared_ptr<Channel> channel) {
1038 return channel->type() == sigrok::ChannelType::LOGIC; });
1040 // Create a common data container for the logic signalbases
1042 lock_guard<recursive_mutex> data_lock(data_mutex_);
1044 if (logic_channel_count == 0) {
1045 logic_data_.reset();
1046 } else if (!logic_data_ ||
1047 logic_data_->num_channels() != logic_channel_count) {
1048 logic_data_.reset(new data::Logic(logic_channel_count));
1049 assert(logic_data_);
1053 // Create signalbases if necessary
1054 for (auto channel : sr_dev->channels()) {
1056 // Try to find the channel in the list of existing signalbases
1057 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1058 [&](const shared_ptr<SignalBase> &sb) { return sb->channel() == channel; });
1060 // Not found, let's make a signalbase for it
1061 if (iter == signalbases_.cend()) {
1062 shared_ptr<SignalBase> signalbase;
1063 switch(channel->type()->id()) {
1064 case SR_CHANNEL_LOGIC:
1065 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::LogicChannel);
1066 signalbases_.push_back(signalbase);
1068 all_signal_data_.insert(logic_data_);
1069 signalbase->set_data(logic_data_);
1071 connect(this, SIGNAL(capture_state_changed(int)),
1072 signalbase.get(), SLOT(on_capture_state_changed(int)));
1075 case SR_CHANNEL_ANALOG:
1076 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::AnalogChannel);
1077 signalbases_.push_back(signalbase);
1079 shared_ptr<data::Analog> data(new data::Analog());
1080 all_signal_data_.insert(data);
1081 signalbase->set_data(data);
1083 connect(this, SIGNAL(capture_state_changed(int)),
1084 signalbase.get(), SLOT(on_capture_state_changed(int)));
1090 // Create and assign default signal groups if needed
1091 if (signal_groups_.empty()) {
1092 for (auto& entry : sr_dev->channel_groups()) {
1093 const shared_ptr<sigrok::ChannelGroup>& group = entry.second;
1095 if (group->channels().size() <= 1)
1098 SignalGroup* sg = new SignalGroup(QString::fromStdString(entry.first));
1099 for (const shared_ptr<sigrok::Channel>& channel : group->channels()) {
1100 for (shared_ptr<data::SignalBase> s : signalbases_) {
1101 if (s->channel() == channel) {
1102 sg->append_signal(s);
1107 signal_groups_.emplace_back(sg);
1112 for (shared_ptr<views::ViewBase>& viewbase : views_) {
1113 vector< shared_ptr<SignalBase> > view_signalbases =
1114 viewbase->signalbases();
1116 // Add all non-decode signalbases that don't yet exist in the view
1117 for (shared_ptr<SignalBase>& session_sb : signalbases_) {
1118 if (session_sb->type() == SignalBase::DecodeChannel)
1121 const auto iter = find_if(view_signalbases.cbegin(), view_signalbases.cend(),
1122 [&](const shared_ptr<SignalBase> &sb) { return sb == session_sb; });
1124 if (iter == view_signalbases.cend())
1125 viewbase->add_signalbase(session_sb);
1128 // Remove all non-decode signalbases that no longer exist
1129 for (shared_ptr<SignalBase>& view_sb : view_signalbases) {
1130 if (view_sb->type() == SignalBase::DecodeChannel)
1133 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1134 [&](const shared_ptr<SignalBase> &sb) { return sb == view_sb; });
1136 if (iter == signalbases_.cend())
1137 viewbase->remove_signalbase(view_sb);
1144 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1145 shared_ptr<sigrok::Channel> channel) const
1147 for (shared_ptr<data::SignalBase> sig : signalbases_) {
1149 if (sig->channel() == channel)
1152 return shared_ptr<data::SignalBase>();
1155 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1157 assert(error_handler);
1160 pipeline_ = Pipeline::create();
1162 source_ = ElementFactory::create_element("filesrc", "source");
1163 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1165 pipeline_->add(source_)->add(sink_);
1166 source_->link(sink_);
1168 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1170 sink_->set_property("emit-signals", TRUE);
1171 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1173 // Get the bus from the pipeline and add a bus watch to the default main context
1174 RefPtr<Bus> bus = pipeline_->get_bus();
1175 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1177 // Start pipeline and Wait until it finished processing
1178 pipeline_done_interrupt_ = false;
1179 pipeline_->set_state(Gst::STATE_PLAYING);
1181 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1182 pipeline_done_cond_.wait(pipeline_done_lock_);
1184 // Let the pipeline free all resources
1185 pipeline_->set_state(Gst::STATE_NULL);
1192 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1193 } catch (Error& e) {
1194 cur_samplerate_ = 0;
1197 out_of_memory_ = false;
1200 lock_guard<recursive_mutex> lock(data_mutex_);
1201 cur_logic_segment_.reset();
1202 cur_analog_segments_.clear();
1203 for (shared_ptr<data::SignalBase> sb : signalbases_)
1204 sb->clear_sample_data();
1206 highest_segment_id_ = -1;
1207 frame_began_ = false;
1211 } catch (Error& e) {
1212 error_handler(e.what());
1216 set_capture_state(device_->session()->trigger() ?
1217 AwaitingTrigger : Running);
1221 } catch (Error& e) {
1222 error_handler(e.what());
1223 set_capture_state(Stopped);
1225 } catch (QString& e) {
1227 set_capture_state(Stopped);
1231 set_capture_state(Stopped);
1233 // Confirm that SR_DF_END was received
1234 if (cur_logic_segment_)
1235 qDebug() << "WARNING: SR_DF_END was not received.";
1238 // Optimize memory usage
1239 free_unused_memory();
1241 // We now have unsaved data unless we just "captured" from a file
1242 shared_ptr<devices::File> file_device =
1243 dynamic_pointer_cast<devices::File>(device_);
1246 data_saved_ = false;
1249 error_handler(tr("Out of memory, acquisition stopped."));
1252 void Session::free_unused_memory()
1254 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1255 const vector< shared_ptr<data::Segment> > segments = data->segments();
1257 for (const shared_ptr<data::Segment>& segment : segments)
1258 segment->free_unused_memory();
1262 void Session::signal_new_segment()
1264 int new_segment_id = 0;
1266 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1268 // Determine new frame/segment number, assuming that all
1269 // signals have the same number of frames/segments
1270 if (cur_logic_segment_) {
1271 new_segment_id = logic_data_->get_segment_count() - 1;
1273 shared_ptr<sigrok::Channel> any_channel =
1274 (*cur_analog_segments_.begin()).first;
1276 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1279 shared_ptr<data::Analog> data(base->analog_data());
1282 new_segment_id = data->get_segment_count() - 1;
1286 if (new_segment_id > highest_segment_id_) {
1287 highest_segment_id_ = new_segment_id;
1288 new_segment(highest_segment_id_);
1292 void Session::signal_segment_completed()
1296 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1297 // We only care about analog and logic channels, not derived ones
1298 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1299 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1303 if (signalbase->type() == data::SignalBase::LogicChannel) {
1304 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1309 if (segment_id >= 0)
1310 segment_completed(segment_id);
1314 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1318 if ((message->get_source() == pipeline_) && \
1319 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1320 pipeline_done_cond_.notify_one();
1322 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1327 Gst::FlowReturn Session::on_gst_new_sample()
1329 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1330 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1332 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1333 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1334 Gst::MapInfo mapinfo;
1335 buf_mem->map(mapinfo, Gst::MAP_READ);
1337 shared_ptr<sigrok::Packet> logic_packet =
1338 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1341 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1342 } catch (bad_alloc&) {
1343 out_of_memory_ = true;
1345 buf_mem->unmap(mapinfo);
1346 return Gst::FLOW_ERROR;
1349 buf_mem->unmap(mapinfo);
1352 return Gst::FLOW_OK;
1356 void Session::feed_in_header()
1358 // Nothing to do here for now
1361 void Session::feed_in_meta(shared_ptr<Meta> meta)
1363 for (auto& entry : meta->config()) {
1364 switch (entry.first->id()) {
1365 case SR_CONF_SAMPLERATE:
1366 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1369 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1377 void Session::feed_in_trigger()
1379 // The channel containing most samples should be most accurate
1380 uint64_t sample_count = 0;
1383 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1385 uint64_t temp_count = 0;
1387 const vector< shared_ptr<pv::data::Segment> > segments =
1389 for (const shared_ptr<pv::data::Segment> &s : segments)
1390 temp_count += s->get_sample_count();
1392 if (temp_count > sample_count)
1393 sample_count = temp_count;
1397 uint32_t segment_id = 0; // Default segment when no frames are used
1399 // If a frame began, we'd ideally be able to use the highest segment ID for
1400 // the trigger. However, as new segments are only created when logic or
1401 // analog data comes in, this doesn't work if the trigger appears right
1402 // after the beginning of the frame, before any sample data.
1403 // For this reason, we use highest segment ID + 1 if no sample data came in
1404 // yet and the highest segment ID otherwise.
1406 segment_id = highest_segment_id_;
1407 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1411 // TODO Create timestamp from segment start time + segment's current sample count
1412 util::Timestamp timestamp = sample_count / get_samplerate();
1413 trigger_list_.emplace_back(segment_id, timestamp);
1414 trigger_event(segment_id, timestamp);
1417 void Session::feed_in_frame_begin()
1419 frame_began_ = true;
1422 void Session::feed_in_frame_end()
1428 lock_guard<recursive_mutex> lock(data_mutex_);
1430 if (cur_logic_segment_)
1431 cur_logic_segment_->set_complete();
1433 for (auto& entry : cur_analog_segments_) {
1434 shared_ptr<data::AnalogSegment> segment = entry.second;
1435 segment->set_complete();
1438 cur_logic_segment_.reset();
1439 cur_analog_segments_.clear();
1442 frame_began_ = false;
1444 signal_segment_completed();
1447 void Session::feed_in_logic(shared_ptr<sigrok::Logic> logic)
1449 if (logic->data_length() == 0) {
1450 qDebug() << "WARNING: Received logic packet with 0 samples.";
1454 if (logic->unit_size() > 8)
1455 throw QString(tr("Can't handle more than 64 logic channels."));
1457 if (!cur_samplerate_)
1459 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1460 } catch (Error& e) {
1464 lock_guard<recursive_mutex> lock(data_mutex_);
1467 // The only reason logic_data_ would not have been created is
1468 // if it was not possible to determine the signals when the
1469 // device was created.
1473 if (!cur_logic_segment_) {
1474 // This could be the first packet after a trigger
1475 set_capture_state(Running);
1477 // Create a new data segment
1478 cur_logic_segment_ = make_shared<data::LogicSegment>(
1479 *logic_data_, logic_data_->get_segment_count(),
1480 logic->unit_size(), cur_samplerate_);
1481 logic_data_->push_segment(cur_logic_segment_);
1483 signal_new_segment();
1486 cur_logic_segment_->append_payload(logic);
1491 void Session::feed_in_analog(shared_ptr<sigrok::Analog> analog)
1493 if (analog->num_samples() == 0) {
1494 qDebug() << "WARNING: Received analog packet with 0 samples.";
1498 if (!cur_samplerate_)
1500 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1501 } catch (Error& e) {
1505 lock_guard<recursive_mutex> lock(data_mutex_);
1507 const vector<shared_ptr<Channel>> channels = analog->channels();
1508 bool sweep_beginning = false;
1510 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1511 analog->get_data_as_float(data.get());
1513 if (signalbases_.empty())
1516 float *channel_data = data.get();
1517 for (auto& channel : channels) {
1518 shared_ptr<data::AnalogSegment> segment;
1520 // Try to get the segment of the channel
1521 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1522 iterator iter = cur_analog_segments_.find(channel);
1523 if (iter != cur_analog_segments_.end())
1524 segment = (*iter).second;
1526 // If no segment was found, this means we haven't
1527 // created one yet. i.e. this is the first packet
1528 // in the sweep containing this segment.
1529 sweep_beginning = true;
1531 // Find the analog data associated with the channel
1532 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1535 shared_ptr<data::Analog> data(base->analog_data());
1538 // Create a segment, keep it in the maps of channels
1539 segment = make_shared<data::AnalogSegment>(
1540 *data, data->get_segment_count(), cur_samplerate_);
1541 cur_analog_segments_[channel] = segment;
1543 // Push the segment into the analog data.
1544 data->push_segment(segment);
1546 signal_new_segment();
1551 // Append the samples in the segment
1552 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1556 if (sweep_beginning) {
1557 // This could be the first packet after a trigger
1558 set_capture_state(Running);
1564 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1565 shared_ptr<Packet> packet)
1570 assert(device == device_->device());
1573 switch (packet->type()->id()) {
1579 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1588 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1589 } catch (bad_alloc&) {
1590 out_of_memory_ = true;
1597 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1598 } catch (bad_alloc&) {
1599 out_of_memory_ = true;
1604 case SR_DF_FRAME_BEGIN:
1605 feed_in_frame_begin();
1608 case SR_DF_FRAME_END:
1609 feed_in_frame_end();
1613 // Strictly speaking, this is performed when a frame end marker was
1614 // received, so there's no point doing this again. However, not all
1615 // devices use frames, and for those devices, we need to do it here.
1617 lock_guard<recursive_mutex> lock(data_mutex_);
1619 if (cur_logic_segment_)
1620 cur_logic_segment_->set_complete();
1622 for (auto& entry : cur_analog_segments_) {
1623 shared_ptr<data::AnalogSegment> segment = entry.second;
1624 segment->set_complete();
1627 cur_logic_segment_.reset();
1628 cur_analog_segments_.clear();
1637 void Session::on_data_saved()
1642 #ifdef ENABLE_DECODE
1643 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1645 assert(decoders.size() > 0);
1647 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1650 for (unsigned int i = 0; i < decoders.size(); i++) {
1651 const srd_decoder* d = decoders[i];
1652 signal->stack_decoder(d, !(i < decoders.size() - 1));