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"
34 #include "data/analog.hpp"
35 #include "data/analogsegment.hpp"
36 #include "data/decode/decoder.hpp"
37 #include "data/logic.hpp"
38 #include "data/logicsegment.hpp"
39 #include "data/signalbase.hpp"
41 #include "devices/hardwaredevice.hpp"
42 #include "devices/inputfile.hpp"
43 #include "devices/sessionfile.hpp"
45 #include "toolbars/mainbar.hpp"
47 #include "views/trace/analogsignal.hpp"
48 #include "views/trace/decodetrace.hpp"
49 #include "views/trace/logicsignal.hpp"
50 #include "views/trace/signal.hpp"
51 #include "views/trace/view.hpp"
53 #include <libsigrokcxx/libsigrokcxx.hpp>
56 #include <gstreamermm.h>
57 #include <libsigrokflow/libsigrokflow.hpp>
61 #include <libsigrokdecode/libsigrokdecode.h>
62 #include "data/decodesignal.hpp"
66 using std::dynamic_pointer_cast;
69 using std::lock_guard;
72 using std::make_shared;
78 using std::recursive_mutex;
79 using std::runtime_error;
80 using std::shared_ptr;
83 using std::unique_lock;
85 using std::unique_ptr;
86 using std::unordered_set;
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::views::trace::Signal;
109 using pv::views::trace::AnalogSignal;
110 using pv::views::trace::LogicSignal;
114 shared_ptr<sigrok::Context> Session::sr_context;
116 Session::Session(DeviceManager &device_manager, QString name) :
117 device_manager_(device_manager),
120 capture_state_(Stopped),
128 // Stop and join to the thread
132 DeviceManager& Session::device_manager()
134 return device_manager_;
137 const DeviceManager& Session::device_manager() const
139 return device_manager_;
142 shared_ptr<sigrok::Session> Session::session() const
145 return shared_ptr<sigrok::Session>();
146 return device_->session();
149 shared_ptr<devices::Device> Session::device() const
154 QString Session::name() const
159 void Session::set_name(QString name)
161 if (default_name_.isEmpty())
162 default_name_ = name;
169 const list< shared_ptr<views::ViewBase> > Session::views() const
174 shared_ptr<views::ViewBase> Session::main_view() const
179 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
181 main_bar_ = main_bar;
184 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
189 bool Session::data_saved() const
194 void Session::save_setup(QSettings &settings) const
196 int decode_signals = 0, views = 0;
198 // Save channels and decoders
199 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
201 if (base->is_decode_signal()) {
202 settings.beginGroup("decode_signal" + QString::number(decode_signals++));
203 base->save_settings(settings);
208 settings.beginGroup(base->internal_name());
209 base->save_settings(settings);
214 settings.setValue("decode_signals", decode_signals);
216 // Save view states and their signal settings
217 // Note: main_view must be saved as view0
218 settings.beginGroup("view" + QString::number(views++));
219 main_view_->save_settings(settings);
222 for (const shared_ptr<views::ViewBase>& view : views_) {
223 if (view != main_view_) {
224 settings.beginGroup("view" + QString::number(views++));
225 settings.setValue("type", view->get_type());
226 view->save_settings(settings);
231 settings.setValue("views", views);
234 void Session::save_settings(QSettings &settings) const
236 map<string, string> dev_info;
237 list<string> key_list;
240 shared_ptr<devices::HardwareDevice> hw_device =
241 dynamic_pointer_cast< devices::HardwareDevice >(device_);
244 settings.setValue("device_type", "hardware");
245 settings.beginGroup("device");
247 key_list.emplace_back("vendor");
248 key_list.emplace_back("model");
249 key_list.emplace_back("version");
250 key_list.emplace_back("serial_num");
251 key_list.emplace_back("connection_id");
253 dev_info = device_manager_.get_device_info(device_);
255 for (string& key : key_list) {
256 if (dev_info.count(key))
257 settings.setValue(QString::fromUtf8(key.c_str()),
258 QString::fromUtf8(dev_info.at(key).c_str()));
260 settings.remove(QString::fromUtf8(key.c_str()));
266 shared_ptr<devices::SessionFile> sessionfile_device =
267 dynamic_pointer_cast<devices::SessionFile>(device_);
269 if (sessionfile_device) {
270 settings.setValue("device_type", "sessionfile");
271 settings.beginGroup("device");
272 settings.setValue("filename", QString::fromStdString(
273 sessionfile_device->full_name()));
277 shared_ptr<devices::InputFile> inputfile_device =
278 dynamic_pointer_cast<devices::InputFile>(device_);
280 if (inputfile_device) {
281 settings.setValue("device_type", "inputfile");
282 settings.beginGroup("device");
283 inputfile_device->save_meta_to_settings(settings);
287 save_setup(settings);
291 void Session::restore_setup(QSettings &settings)
294 for (shared_ptr<data::SignalBase> base : signalbases_) {
295 settings.beginGroup(base->internal_name());
296 base->restore_settings(settings);
302 int decode_signals = settings.value("decode_signals").toInt();
304 for (int i = 0; i < decode_signals; i++) {
305 settings.beginGroup("decode_signal" + QString::number(i));
306 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
307 signal->restore_settings(settings);
313 int views = settings.value("views").toInt();
315 for (int i = 0; i < views; i++) {
316 settings.beginGroup("view" + QString::number(i));
319 views::ViewType type = (views::ViewType)settings.value("type").toInt();
320 add_view(type, this);
321 views_.back()->restore_settings(settings);
323 main_view_->restore_settings(settings);
329 void Session::restore_settings(QSettings &settings)
331 shared_ptr<devices::Device> device;
333 QString device_type = settings.value("device_type").toString();
335 if (device_type == "hardware") {
336 map<string, string> dev_info;
337 list<string> key_list;
339 // Re-select last used device if possible but only if it's not demo
340 settings.beginGroup("device");
341 key_list.emplace_back("vendor");
342 key_list.emplace_back("model");
343 key_list.emplace_back("version");
344 key_list.emplace_back("serial_num");
345 key_list.emplace_back("connection_id");
347 for (string key : key_list) {
348 const QString k = QString::fromStdString(key);
349 if (!settings.contains(k))
352 const string value = settings.value(k).toString().toStdString();
354 dev_info.insert(make_pair(key, value));
357 if (dev_info.count("model") > 0)
358 device = device_manager_.find_device_from_info(dev_info);
366 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
367 if (device_type == "sessionfile") {
368 settings.beginGroup("device");
369 QString filename = settings.value("filename").toString();
372 if (QFileInfo(filename).isReadable()) {
373 device = make_shared<devices::SessionFile>(device_manager_.context(),
374 filename.toStdString());
378 if (device_type == "inputfile") {
379 settings.beginGroup("device");
380 device = make_shared<devices::InputFile>(device_manager_.context(),
388 start_capture([](QString infoMessage) {
389 // TODO Emulate noquote()
390 qDebug() << "Session error:" << infoMessage; });
392 set_name(QString::fromStdString(
393 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
398 restore_setup(settings);
401 void Session::select_device(shared_ptr<devices::Device> device)
407 set_default_device();
408 } catch (const QString &e) {
409 MainWindow::show_session_error(tr("Failed to select device"), e);
413 void Session::set_device(shared_ptr<devices::Device> device)
417 // Ensure we are not capturing before setting the device
425 // Revert name back to default name (e.g. "Session 1") as the data is gone
426 name_ = default_name_;
429 // Remove all stored data and reset all views
430 for (shared_ptr<views::ViewBase> view : views_) {
431 view->clear_signals();
433 view->clear_decode_signals();
435 view->reset_view_state();
437 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
439 all_signal_data_.clear();
440 signalbases_.clear();
441 cur_logic_segment_.reset();
443 for (auto& entry : cur_analog_segments_) {
444 shared_ptr<sigrok::Channel>(entry.first).reset();
445 shared_ptr<data::AnalogSegment>(entry.second).reset();
452 device_ = move(device);
456 } catch (const QString &e) {
458 MainWindow::show_session_error(tr("Failed to open device"), e);
462 device_->session()->add_datafeed_callback([=]
463 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
464 data_feed_in(device, packet);
473 void Session::set_default_device()
475 const list< shared_ptr<devices::HardwareDevice> > &devices =
476 device_manager_.devices();
481 // Try and find the demo device and select that by default
482 const auto iter = find_if(devices.begin(), devices.end(),
483 [] (const shared_ptr<devices::HardwareDevice> &d) {
484 return d->hardware_device()->driver()->name() == "demo"; });
485 set_device((iter == devices.end()) ? devices.front() : *iter);
488 bool Session::using_file_device() const
490 shared_ptr<devices::SessionFile> sessionfile_device =
491 dynamic_pointer_cast<devices::SessionFile>(device_);
493 shared_ptr<devices::InputFile> inputfile_device =
494 dynamic_pointer_cast<devices::InputFile>(device_);
496 return (sessionfile_device || inputfile_device);
500 * Convert generic options to data types that are specific to InputFormat.
502 * @param[in] user_spec Vector of tokenized words, string format.
503 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
505 * @return Map of options suitable for InputFormat::create_input().
507 map<string, Glib::VariantBase>
508 Session::input_format_options(vector<string> user_spec,
509 map<string, shared_ptr<Option>> fmt_opts)
511 map<string, Glib::VariantBase> result;
513 for (auto& entry : user_spec) {
515 * Split key=value specs. Accept entries without separator
516 * (for simplified boolean specifications).
519 size_t pos = entry.find("=");
520 if (pos == std::string::npos) {
524 key = entry.substr(0, pos);
525 val = entry.substr(pos + 1);
529 * Skip user specifications that are not a member of the
530 * format's set of supported options. Have the text input
531 * spec converted to the required input format specific
534 auto found = fmt_opts.find(key);
535 if (found == fmt_opts.end())
537 shared_ptr<Option> opt = found->second;
538 result[key] = opt->parse_string(val);
544 void Session::load_init_file(const string &file_name,
545 const string &format, const string &setup_file_name)
547 shared_ptr<InputFormat> input_format;
548 map<string, Glib::VariantBase> input_opts;
550 if (!format.empty()) {
551 const map<string, shared_ptr<InputFormat> > formats =
552 device_manager_.context()->input_formats();
553 auto user_opts = pv::util::split_string(format, ":");
554 string user_name = user_opts.front();
555 user_opts.erase(user_opts.begin());
556 const auto iter = find_if(formats.begin(), formats.end(),
557 [&](const pair<string, shared_ptr<InputFormat> > f) {
558 return f.first == user_name; });
559 if (iter == formats.end()) {
560 MainWindow::show_session_error(tr("Error"),
561 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
564 input_format = (*iter).second;
565 input_opts = input_format_options(user_opts,
566 input_format->options());
569 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
570 input_format, input_opts);
573 void Session::load_file(QString file_name, QString setup_file_name,
574 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
576 const QString errorMessage(
577 QString("Failed to load file %1").arg(file_name));
579 // In the absence of a caller's format spec, try to auto detect.
580 // Assume "sigrok session file" upon lookup miss.
582 format = device_manager_.context()->input_format_match(file_name.toStdString());
585 set_device(shared_ptr<devices::Device>(
586 new devices::InputFile(
587 device_manager_.context(),
588 file_name.toStdString(),
591 set_device(shared_ptr<devices::Device>(
592 new devices::SessionFile(
593 device_manager_.context(),
594 file_name.toStdString())));
596 MainWindow::show_session_error(tr("Failed to load ") + file_name, e.what());
597 set_default_device();
598 main_bar_->update_device_list();
602 // Use the input file with .pvs extension if no setup file was given
603 if (setup_file_name.isEmpty()) {
604 setup_file_name = file_name;
605 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
606 setup_file_name.append(".pvs");
609 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
610 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
611 restore_setup(settings_storage);
614 main_bar_->update_device_list();
616 start_capture([&, errorMessage](QString infoMessage) {
617 MainWindow::show_session_error(errorMessage, infoMessage); });
619 set_name(QFileInfo(file_name).fileName());
622 Session::capture_state Session::get_capture_state() const
624 lock_guard<mutex> lock(sampling_mutex_);
625 return capture_state_;
628 void Session::start_capture(function<void (const QString)> error_handler)
631 error_handler(tr("No active device set, can't start acquisition."));
637 // Check that at least one channel is enabled
638 const shared_ptr<sigrok::Device> sr_dev = device_->device();
640 const auto channels = sr_dev->channels();
641 if (!any_of(channels.begin(), channels.end(),
642 [](shared_ptr<Channel> channel) {
643 return channel->enabled(); })) {
644 error_handler(tr("No channels enabled."));
650 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
653 trigger_list_.clear();
655 // Revert name back to default name (e.g. "Session 1") for real devices
656 // as the (possibly saved) data is gone. File devices keep their name.
657 shared_ptr<devices::HardwareDevice> hw_device =
658 dynamic_pointer_cast< devices::HardwareDevice >(device_);
661 name_ = default_name_;
666 sampling_thread_ = std::thread(
667 &Session::sample_thread_proc, this, error_handler);
670 void Session::stop_capture()
672 if (get_capture_state() != Stopped)
675 // Check that sampling stopped
676 if (sampling_thread_.joinable())
677 sampling_thread_.join();
680 void Session::register_view(shared_ptr<views::ViewBase> view)
685 views_.push_back(view);
687 // Add all device signals
690 // Add all other signals
691 unordered_set< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
693 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
694 const int sb_exists = count_if(
695 view_signalbases.cbegin(), view_signalbases.cend(),
696 [&](const shared_ptr<data::SignalBase> &sb) {
697 return sb == signalbase;
700 // Add the signal to the view if it doesn't have it yet
702 switch (signalbase->type()) {
703 case data::SignalBase::AnalogChannel:
704 case data::SignalBase::LogicChannel:
705 case data::SignalBase::MathChannel:
706 view->add_signalbase(signalbase);
708 case data::SignalBase::DecodeChannel:
710 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
719 void Session::deregister_view(shared_ptr<views::ViewBase> view)
721 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
723 if (views_.empty()) {
726 // Without a view there can be no main bar
731 bool Session::has_view(shared_ptr<views::ViewBase> view)
733 for (shared_ptr<views::ViewBase>& v : views_)
740 double Session::get_samplerate() const
742 double samplerate = 0.0;
744 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
746 const vector< shared_ptr<pv::data::Segment> > segments =
748 for (const shared_ptr<pv::data::Segment>& s : segments)
749 samplerate = max(samplerate, s->samplerate());
751 // If there is no sample rate given we use samples as unit
752 if (samplerate == 0.0)
758 uint32_t Session::get_segment_count() const
762 // Find the highest number of segments
763 for (const shared_ptr<data::SignalData>& data : all_signal_data_)
764 if (data->get_segment_count() > value)
765 value = data->get_segment_count();
770 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
772 vector<util::Timestamp> result;
774 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
775 if (entry.first == segment_id)
776 result.push_back(entry.second);
781 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
786 bool Session::all_segments_complete(uint32_t segment_id) const
788 bool all_complete = true;
790 for (const shared_ptr<data::SignalBase>& base : signalbases_)
791 if (!base->segment_is_complete(segment_id))
792 all_complete = false;
798 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
800 shared_ptr<data::DecodeSignal> signal;
803 // Create the decode signal
804 signal = make_shared<data::DecodeSignal>(*this);
806 signalbases_.insert(signal);
808 // Add the decode signal to all views
809 for (shared_ptr<views::ViewBase>& view : views_)
810 view->add_decode_signal(signal);
811 } catch (runtime_error& e) {
812 remove_decode_signal(signal);
821 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
823 signalbases_.erase(signal);
825 for (shared_ptr<views::ViewBase>& view : views_)
826 view->remove_decode_signal(signal);
832 void Session::set_capture_state(capture_state state)
836 if (state == Running)
838 if (state == Stopped)
839 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
842 lock_guard<mutex> lock(sampling_mutex_);
843 changed = capture_state_ != state;
844 capture_state_ = state;
848 capture_state_changed(state);
851 void Session::update_signals()
854 signalbases_.clear();
856 for (shared_ptr<views::ViewBase>& view : views_) {
857 view->clear_signals();
859 view->clear_decode_signals();
865 lock_guard<recursive_mutex> lock(data_mutex_);
867 const shared_ptr<sigrok::Device> sr_dev = device_->device();
869 signalbases_.clear();
871 for (shared_ptr<views::ViewBase>& view : views_) {
872 view->clear_signals();
874 view->clear_decode_signals();
880 // Detect what data types we will receive
881 auto channels = sr_dev->channels();
882 unsigned int logic_channel_count = count_if(
883 channels.begin(), channels.end(),
884 [] (shared_ptr<Channel> channel) {
885 return channel->type() == sigrok::ChannelType::LOGIC; });
887 // Create data containers for the logic data segments
889 lock_guard<recursive_mutex> data_lock(data_mutex_);
891 if (logic_channel_count == 0) {
893 } else if (!logic_data_ ||
894 logic_data_->num_channels() != logic_channel_count) {
895 logic_data_.reset(new data::Logic(
896 logic_channel_count));
901 // Make the signals list
902 for (shared_ptr<views::ViewBase>& viewbase : views_) {
903 views::trace::View *trace_view =
904 qobject_cast<views::trace::View*>(viewbase.get());
907 unordered_set< shared_ptr<Signal> > prev_sigs(trace_view->signals());
908 trace_view->clear_signals();
910 for (auto channel : sr_dev->channels()) {
911 shared_ptr<data::SignalBase> signalbase;
912 shared_ptr<Signal> signal;
914 // Find the channel in the old signals
915 const auto iter = find_if(
916 prev_sigs.cbegin(), prev_sigs.cend(),
917 [&](const shared_ptr<Signal> &s) {
918 return s->base()->channel() == channel;
920 if (iter != prev_sigs.end()) {
921 // Copy the signal from the old set to the new
923 trace_view->add_signal(signal);
925 // Find the signalbase for this channel if possible
927 for (const shared_ptr<data::SignalBase>& b : signalbases_)
928 if (b->channel() == channel)
931 shared_ptr<Signal> signal;
933 switch(channel->type()->id()) {
934 case SR_CHANNEL_LOGIC:
936 signalbase = make_shared<data::SignalBase>(channel,
937 data::SignalBase::LogicChannel);
938 signalbases_.insert(signalbase);
940 all_signal_data_.insert(logic_data_);
941 signalbase->set_data(logic_data_);
943 connect(this, SIGNAL(capture_state_changed(int)),
944 signalbase.get(), SLOT(on_capture_state_changed(int)));
947 signal = shared_ptr<Signal>(new LogicSignal(*this, device_, signalbase));
950 case SR_CHANNEL_ANALOG:
953 signalbase = make_shared<data::SignalBase>(channel,
954 data::SignalBase::AnalogChannel);
955 signalbases_.insert(signalbase);
957 shared_ptr<data::Analog> data(new data::Analog());
958 all_signal_data_.insert(data);
959 signalbase->set_data(data);
961 connect(this, SIGNAL(capture_state_changed(int)),
962 signalbase.get(), SLOT(on_capture_state_changed(int)));
965 signal = shared_ptr<Signal>(new AnalogSignal(*this, signalbase));
974 // New views take their signal settings from the main view
975 if (!viewbase->is_main_view()) {
976 shared_ptr<pv::views::trace::View> main_tv =
977 dynamic_pointer_cast<pv::views::trace::View>(main_view_);
978 shared_ptr<Signal> main_signal =
979 main_tv->get_signal_by_signalbase(signalbase);
980 signal->restore_settings(main_signal->save_settings());
983 trace_view->add_signal(signal);
992 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
993 shared_ptr<sigrok::Channel> channel) const
995 for (shared_ptr<data::SignalBase> sig : signalbases_) {
997 if (sig->channel() == channel)
1000 return shared_ptr<data::SignalBase>();
1003 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1005 assert(error_handler);
1008 pipeline_ = Pipeline::create();
1010 source_ = ElementFactory::create_element("filesrc", "source");
1011 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1013 pipeline_->add(source_)->add(sink_);
1014 source_->link(sink_);
1016 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1018 sink_->set_property("emit-signals", TRUE);
1019 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1021 // Get the bus from the pipeline and add a bus watch to the default main context
1022 RefPtr<Bus> bus = pipeline_->get_bus();
1023 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1025 // Start pipeline and Wait until it finished processing
1026 pipeline_done_interrupt_ = false;
1027 pipeline_->set_state(Gst::STATE_PLAYING);
1029 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1030 pipeline_done_cond_.wait(pipeline_done_lock_);
1032 // Let the pipeline free all resources
1033 pipeline_->set_state(Gst::STATE_NULL);
1040 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1041 } catch (Error& e) {
1042 cur_samplerate_ = 0;
1045 out_of_memory_ = false;
1048 lock_guard<recursive_mutex> lock(data_mutex_);
1049 cur_logic_segment_.reset();
1050 cur_analog_segments_.clear();
1052 highest_segment_id_ = -1;
1053 frame_began_ = false;
1057 } catch (Error& e) {
1058 error_handler(e.what());
1062 set_capture_state(device_->session()->trigger() ?
1063 AwaitingTrigger : Running);
1067 } catch (Error& e) {
1068 error_handler(e.what());
1069 set_capture_state(Stopped);
1071 } catch (QString& e) {
1073 set_capture_state(Stopped);
1077 set_capture_state(Stopped);
1079 // Confirm that SR_DF_END was received
1080 if (cur_logic_segment_)
1081 qDebug() << "WARNING: SR_DF_END was not received.";
1084 // Optimize memory usage
1085 free_unused_memory();
1087 // We now have unsaved data unless we just "captured" from a file
1088 shared_ptr<devices::File> file_device =
1089 dynamic_pointer_cast<devices::File>(device_);
1092 data_saved_ = false;
1095 error_handler(tr("Out of memory, acquisition stopped."));
1098 void Session::free_unused_memory()
1100 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1101 const vector< shared_ptr<data::Segment> > segments = data->segments();
1103 for (const shared_ptr<data::Segment>& segment : segments)
1104 segment->free_unused_memory();
1108 void Session::signal_new_segment()
1110 int new_segment_id = 0;
1112 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1114 // Determine new frame/segment number, assuming that all
1115 // signals have the same number of frames/segments
1116 if (cur_logic_segment_) {
1117 new_segment_id = logic_data_->get_segment_count() - 1;
1119 shared_ptr<sigrok::Channel> any_channel =
1120 (*cur_analog_segments_.begin()).first;
1122 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1125 shared_ptr<data::Analog> data(base->analog_data());
1128 new_segment_id = data->get_segment_count() - 1;
1132 if (new_segment_id > highest_segment_id_) {
1133 highest_segment_id_ = new_segment_id;
1134 new_segment(highest_segment_id_);
1138 void Session::signal_segment_completed()
1142 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1143 // We only care about analog and logic channels, not derived ones
1144 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1145 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1149 if (signalbase->type() == data::SignalBase::LogicChannel) {
1150 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1155 if (segment_id >= 0)
1156 segment_completed(segment_id);
1160 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1164 if ((message->get_source() == pipeline_) && \
1165 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1166 pipeline_done_cond_.notify_one();
1168 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1173 Gst::FlowReturn Session::on_gst_new_sample()
1175 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1176 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1178 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1179 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1180 Gst::MapInfo mapinfo;
1181 buf_mem->map(mapinfo, Gst::MAP_READ);
1183 shared_ptr<sigrok::Packet> logic_packet =
1184 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1187 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1188 } catch (bad_alloc&) {
1189 out_of_memory_ = true;
1191 buf_mem->unmap(mapinfo);
1192 return Gst::FLOW_ERROR;
1195 buf_mem->unmap(mapinfo);
1198 return Gst::FLOW_OK;
1202 void Session::feed_in_header()
1204 // Nothing to do here for now
1207 void Session::feed_in_meta(shared_ptr<Meta> meta)
1209 for (auto& entry : meta->config()) {
1210 switch (entry.first->id()) {
1211 case SR_CONF_SAMPLERATE:
1212 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1215 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1223 void Session::feed_in_trigger()
1225 // The channel containing most samples should be most accurate
1226 uint64_t sample_count = 0;
1229 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1231 uint64_t temp_count = 0;
1233 const vector< shared_ptr<pv::data::Segment> > segments =
1235 for (const shared_ptr<pv::data::Segment> &s : segments)
1236 temp_count += s->get_sample_count();
1238 if (temp_count > sample_count)
1239 sample_count = temp_count;
1243 uint32_t segment_id = 0; // Default segment when no frames are used
1245 // If a frame began, we'd ideally be able to use the highest segment ID for
1246 // the trigger. However, as new segments are only created when logic or
1247 // analog data comes in, this doesn't work if the trigger appears right
1248 // after the beginning of the frame, before any sample data.
1249 // For this reason, we use highest segment ID + 1 if no sample data came in
1250 // yet and the highest segment ID otherwise.
1252 segment_id = highest_segment_id_;
1253 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1257 // TODO Create timestamp from segment start time + segment's current sample count
1258 util::Timestamp timestamp = sample_count / get_samplerate();
1259 trigger_list_.emplace_back(segment_id, timestamp);
1260 trigger_event(segment_id, timestamp);
1263 void Session::feed_in_frame_begin()
1265 frame_began_ = true;
1268 void Session::feed_in_frame_end()
1274 lock_guard<recursive_mutex> lock(data_mutex_);
1276 if (cur_logic_segment_)
1277 cur_logic_segment_->set_complete();
1279 for (auto& entry : cur_analog_segments_) {
1280 shared_ptr<data::AnalogSegment> segment = entry.second;
1281 segment->set_complete();
1284 cur_logic_segment_.reset();
1285 cur_analog_segments_.clear();
1288 frame_began_ = false;
1290 signal_segment_completed();
1293 void Session::feed_in_logic(shared_ptr<Logic> logic)
1295 if (logic->data_length() == 0) {
1296 qDebug() << "WARNING: Received logic packet with 0 samples.";
1300 if (logic->unit_size() > 8)
1301 throw QString(tr("Can't handle more than 64 logic channels."));
1303 if (!cur_samplerate_)
1305 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1306 } catch (Error& e) {
1310 lock_guard<recursive_mutex> lock(data_mutex_);
1313 // The only reason logic_data_ would not have been created is
1314 // if it was not possible to determine the signals when the
1315 // device was created.
1319 if (!cur_logic_segment_) {
1320 // This could be the first packet after a trigger
1321 set_capture_state(Running);
1323 // Create a new data segment
1324 cur_logic_segment_ = make_shared<data::LogicSegment>(
1325 *logic_data_, logic_data_->get_segment_count(),
1326 logic->unit_size(), cur_samplerate_);
1327 logic_data_->push_segment(cur_logic_segment_);
1329 signal_new_segment();
1332 cur_logic_segment_->append_payload(logic);
1337 void Session::feed_in_analog(shared_ptr<Analog> analog)
1339 if (analog->num_samples() == 0) {
1340 qDebug() << "WARNING: Received analog packet with 0 samples.";
1344 if (!cur_samplerate_)
1346 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1347 } catch (Error& e) {
1351 lock_guard<recursive_mutex> lock(data_mutex_);
1353 const vector<shared_ptr<Channel>> channels = analog->channels();
1354 bool sweep_beginning = false;
1356 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1357 analog->get_data_as_float(data.get());
1359 if (signalbases_.empty())
1362 float *channel_data = data.get();
1363 for (auto& channel : channels) {
1364 shared_ptr<data::AnalogSegment> segment;
1366 // Try to get the segment of the channel
1367 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1368 iterator iter = cur_analog_segments_.find(channel);
1369 if (iter != cur_analog_segments_.end())
1370 segment = (*iter).second;
1372 // If no segment was found, this means we haven't
1373 // created one yet. i.e. this is the first packet
1374 // in the sweep containing this segment.
1375 sweep_beginning = true;
1377 // Find the analog data associated with the channel
1378 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1381 shared_ptr<data::Analog> data(base->analog_data());
1384 // Create a segment, keep it in the maps of channels
1385 segment = make_shared<data::AnalogSegment>(
1386 *data, data->get_segment_count(), cur_samplerate_);
1387 cur_analog_segments_[channel] = segment;
1389 // Push the segment into the analog data.
1390 data->push_segment(segment);
1392 signal_new_segment();
1397 // Append the samples in the segment
1398 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1402 if (sweep_beginning) {
1403 // This could be the first packet after a trigger
1404 set_capture_state(Running);
1410 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1411 shared_ptr<Packet> packet)
1416 assert(device == device_->device());
1419 switch (packet->type()->id()) {
1425 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1434 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1435 } catch (bad_alloc&) {
1436 out_of_memory_ = true;
1443 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1444 } catch (bad_alloc&) {
1445 out_of_memory_ = true;
1450 case SR_DF_FRAME_BEGIN:
1451 feed_in_frame_begin();
1454 case SR_DF_FRAME_END:
1455 feed_in_frame_end();
1459 // Strictly speaking, this is performed when a frame end marker was
1460 // received, so there's no point doing this again. However, not all
1461 // devices use frames, and for those devices, we need to do it here.
1463 lock_guard<recursive_mutex> lock(data_mutex_);
1465 if (cur_logic_segment_)
1466 cur_logic_segment_->set_complete();
1468 for (auto& entry : cur_analog_segments_) {
1469 shared_ptr<data::AnalogSegment> segment = entry.second;
1470 segment->set_complete();
1473 cur_logic_segment_.reset();
1474 cur_analog_segments_.clear();
1483 void Session::on_data_saved()
1488 #ifdef ENABLE_DECODE
1489 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1491 assert(decoders.size() > 0);
1493 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1496 for (unsigned int i = 0; i < decoders.size(); i++) {
1497 const srd_decoder* d = decoders[i];
1498 signal->stack_decoder(d, !(i < decoders.size() - 1));