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;
110 shared_ptr<sigrok::Context> Session::sr_context;
112 Session::Session(DeviceManager &device_manager, QString name) :
113 device_manager_(device_manager),
116 capture_state_(Stopped),
124 // Stop and join to the thread
128 DeviceManager& Session::device_manager()
130 return device_manager_;
133 const DeviceManager& Session::device_manager() const
135 return device_manager_;
138 shared_ptr<sigrok::Session> Session::session() const
141 return shared_ptr<sigrok::Session>();
142 return device_->session();
145 shared_ptr<devices::Device> Session::device() const
150 QString Session::name() const
155 void Session::set_name(QString name)
157 if (default_name_.isEmpty())
158 default_name_ = name;
165 const list< shared_ptr<views::ViewBase> > Session::views() const
170 shared_ptr<views::ViewBase> Session::main_view() const
175 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
177 main_bar_ = main_bar;
180 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
185 bool Session::data_saved() const
190 void Session::save_setup(QSettings &settings) const
192 int decode_signals = 0, views = 0;
194 // Save channels and decoders
195 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
197 if (base->is_decode_signal()) {
198 settings.beginGroup("decode_signal" + QString::number(decode_signals++));
199 base->save_settings(settings);
204 settings.beginGroup(base->internal_name());
205 base->save_settings(settings);
210 settings.setValue("decode_signals", decode_signals);
212 // Save view states and their signal settings
213 // Note: main_view must be saved as view0
214 settings.beginGroup("view" + QString::number(views++));
215 main_view_->save_settings(settings);
218 for (const shared_ptr<views::ViewBase>& view : views_) {
219 if (view != main_view_) {
220 settings.beginGroup("view" + QString::number(views++));
221 view->save_settings(settings);
226 settings.setValue("views", views);
229 void Session::save_settings(QSettings &settings) const
231 map<string, string> dev_info;
232 list<string> key_list;
235 shared_ptr<devices::HardwareDevice> hw_device =
236 dynamic_pointer_cast< devices::HardwareDevice >(device_);
239 settings.setValue("device_type", "hardware");
240 settings.beginGroup("device");
242 key_list.emplace_back("vendor");
243 key_list.emplace_back("model");
244 key_list.emplace_back("version");
245 key_list.emplace_back("serial_num");
246 key_list.emplace_back("connection_id");
248 dev_info = device_manager_.get_device_info(device_);
250 for (string& key : key_list) {
251 if (dev_info.count(key))
252 settings.setValue(QString::fromUtf8(key.c_str()),
253 QString::fromUtf8(dev_info.at(key).c_str()));
255 settings.remove(QString::fromUtf8(key.c_str()));
261 shared_ptr<devices::SessionFile> sessionfile_device =
262 dynamic_pointer_cast<devices::SessionFile>(device_);
264 if (sessionfile_device) {
265 settings.setValue("device_type", "sessionfile");
266 settings.beginGroup("device");
267 settings.setValue("filename", QString::fromStdString(
268 sessionfile_device->full_name()));
272 shared_ptr<devices::InputFile> inputfile_device =
273 dynamic_pointer_cast<devices::InputFile>(device_);
275 if (inputfile_device) {
276 settings.setValue("device_type", "inputfile");
277 settings.beginGroup("device");
278 inputfile_device->save_meta_to_settings(settings);
282 save_setup(settings);
286 void Session::restore_setup(QSettings &settings)
289 for (shared_ptr<data::SignalBase> base : signalbases_) {
290 settings.beginGroup(base->internal_name());
291 base->restore_settings(settings);
297 int decode_signals = settings.value("decode_signals").toInt();
299 for (int i = 0; i < decode_signals; i++) {
300 settings.beginGroup("decode_signal" + QString::number(i));
301 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
302 signal->restore_settings(settings);
308 int views = settings.value("views").toInt();
310 for (int i = 0; i < views; i++) {
311 settings.beginGroup("view" + QString::number(i));
314 views::ViewType type = (views::ViewType)settings.value("type").toInt();
315 add_view(name_, type, this);
316 views_.back()->restore_settings(settings);
318 main_view_->restore_settings(settings);
324 void Session::restore_settings(QSettings &settings)
326 shared_ptr<devices::Device> device;
328 QString device_type = settings.value("device_type").toString();
330 if (device_type == "hardware") {
331 map<string, string> dev_info;
332 list<string> key_list;
334 // Re-select last used device if possible but only if it's not demo
335 settings.beginGroup("device");
336 key_list.emplace_back("vendor");
337 key_list.emplace_back("model");
338 key_list.emplace_back("version");
339 key_list.emplace_back("serial_num");
340 key_list.emplace_back("connection_id");
342 for (string key : key_list) {
343 const QString k = QString::fromStdString(key);
344 if (!settings.contains(k))
347 const string value = settings.value(k).toString().toStdString();
349 dev_info.insert(make_pair(key, value));
352 if (dev_info.count("model") > 0)
353 device = device_manager_.find_device_from_info(dev_info);
361 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
362 if (device_type == "sessionfile") {
363 settings.beginGroup("device");
364 QString filename = settings.value("filename").toString();
367 if (QFileInfo(filename).isReadable()) {
368 device = make_shared<devices::SessionFile>(device_manager_.context(),
369 filename.toStdString());
373 if (device_type == "inputfile") {
374 settings.beginGroup("device");
375 device = make_shared<devices::InputFile>(device_manager_.context(),
383 start_capture([](QString infoMessage) {
384 // TODO Emulate noquote()
385 qDebug() << "Session error:" << infoMessage; });
387 set_name(QString::fromStdString(
388 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
393 restore_setup(settings);
396 void Session::select_device(shared_ptr<devices::Device> device)
402 set_default_device();
403 } catch (const QString &e) {
404 MainWindow::show_session_error(tr("Failed to select device"), e);
408 void Session::set_device(shared_ptr<devices::Device> device)
412 // Ensure we are not capturing before setting the device
420 // Revert name back to default name (e.g. "Session 1") as the data is gone
421 name_ = default_name_;
424 // Remove all stored data and reset all views
425 for (shared_ptr<views::ViewBase> view : views_) {
426 view->clear_signals();
428 view->clear_decode_signals();
430 view->reset_view_state();
432 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
434 all_signal_data_.clear();
435 signalbases_.clear();
436 cur_logic_segment_.reset();
438 for (auto& entry : cur_analog_segments_) {
439 shared_ptr<sigrok::Channel>(entry.first).reset();
440 shared_ptr<data::AnalogSegment>(entry.second).reset();
447 device_ = move(device);
451 } catch (const QString &e) {
453 MainWindow::show_session_error(tr("Failed to open device"), e);
457 device_->session()->add_datafeed_callback([=]
458 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
459 data_feed_in(device, packet);
468 void Session::set_default_device()
470 const list< shared_ptr<devices::HardwareDevice> > &devices =
471 device_manager_.devices();
476 // Try and find the demo device and select that by default
477 const auto iter = find_if(devices.begin(), devices.end(),
478 [] (const shared_ptr<devices::HardwareDevice> &d) {
479 return d->hardware_device()->driver()->name() == "demo"; });
480 set_device((iter == devices.end()) ? devices.front() : *iter);
484 * Convert generic options to data types that are specific to InputFormat.
486 * @param[in] user_spec Vector of tokenized words, string format.
487 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
489 * @return Map of options suitable for InputFormat::create_input().
491 map<string, Glib::VariantBase>
492 Session::input_format_options(vector<string> user_spec,
493 map<string, shared_ptr<Option>> fmt_opts)
495 map<string, Glib::VariantBase> result;
497 for (auto& entry : user_spec) {
499 * Split key=value specs. Accept entries without separator
500 * (for simplified boolean specifications).
503 size_t pos = entry.find("=");
504 if (pos == std::string::npos) {
508 key = entry.substr(0, pos);
509 val = entry.substr(pos + 1);
513 * Skip user specifications that are not a member of the
514 * format's set of supported options. Have the text input
515 * spec converted to the required input format specific
518 auto found = fmt_opts.find(key);
519 if (found == fmt_opts.end())
521 shared_ptr<Option> opt = found->second;
522 result[key] = opt->parse_string(val);
528 void Session::load_init_file(const string &file_name,
529 const string &format, const string &setup_file_name)
531 shared_ptr<InputFormat> input_format;
532 map<string, Glib::VariantBase> input_opts;
534 if (!format.empty()) {
535 const map<string, shared_ptr<InputFormat> > formats =
536 device_manager_.context()->input_formats();
537 auto user_opts = pv::util::split_string(format, ":");
538 string user_name = user_opts.front();
539 user_opts.erase(user_opts.begin());
540 const auto iter = find_if(formats.begin(), formats.end(),
541 [&](const pair<string, shared_ptr<InputFormat> > f) {
542 return f.first == user_name; });
543 if (iter == formats.end()) {
544 MainWindow::show_session_error(tr("Error"),
545 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
548 input_format = (*iter).second;
549 input_opts = input_format_options(user_opts,
550 input_format->options());
553 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
554 input_format, input_opts);
557 void Session::load_file(QString file_name, QString setup_file_name,
558 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
560 const QString errorMessage(
561 QString("Failed to load file %1").arg(file_name));
563 // In the absence of a caller's format spec, try to auto detect.
564 // Assume "sigrok session file" upon lookup miss.
566 format = device_manager_.context()->input_format_match(file_name.toStdString());
569 set_device(shared_ptr<devices::Device>(
570 new devices::InputFile(
571 device_manager_.context(),
572 file_name.toStdString(),
575 set_device(shared_ptr<devices::Device>(
576 new devices::SessionFile(
577 device_manager_.context(),
578 file_name.toStdString())));
580 MainWindow::show_session_error(tr("Failed to load ") + file_name, e.what());
581 set_default_device();
582 main_bar_->update_device_list();
586 // Use the input file with .pvs extension if no setup file was given
587 if (setup_file_name.isEmpty()) {
588 setup_file_name = file_name;
589 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
590 setup_file_name.append(".pvs");
593 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
594 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
595 restore_setup(settings_storage);
598 main_bar_->update_device_list();
600 start_capture([&, errorMessage](QString infoMessage) {
601 MainWindow::show_session_error(errorMessage, infoMessage); });
603 set_name(QFileInfo(file_name).fileName());
606 Session::capture_state Session::get_capture_state() const
608 lock_guard<mutex> lock(sampling_mutex_);
609 return capture_state_;
612 void Session::start_capture(function<void (const QString)> error_handler)
615 error_handler(tr("No active device set, can't start acquisition."));
621 // Check that at least one channel is enabled
622 const shared_ptr<sigrok::Device> sr_dev = device_->device();
624 const auto channels = sr_dev->channels();
625 if (!any_of(channels.begin(), channels.end(),
626 [](shared_ptr<Channel> channel) {
627 return channel->enabled(); })) {
628 error_handler(tr("No channels enabled."));
634 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
637 trigger_list_.clear();
639 // Revert name back to default name (e.g. "Session 1") for real devices
640 // as the (possibly saved) data is gone. File devices keep their name.
641 shared_ptr<devices::HardwareDevice> hw_device =
642 dynamic_pointer_cast< devices::HardwareDevice >(device_);
645 name_ = default_name_;
650 sampling_thread_ = std::thread(
651 &Session::sample_thread_proc, this, error_handler);
654 void Session::stop_capture()
656 if (get_capture_state() != Stopped)
659 // Check that sampling stopped
660 if (sampling_thread_.joinable())
661 sampling_thread_.join();
664 void Session::register_view(shared_ptr<views::ViewBase> view)
666 if (views_.empty()) {
670 views_.push_back(view);
672 // Add all device signals
675 // Add all other signals
676 unordered_set< shared_ptr<data::SignalBase> > view_signalbases =
679 views::trace::View *trace_view =
680 qobject_cast<views::trace::View*>(view.get());
683 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
684 const int sb_exists = count_if(
685 view_signalbases.cbegin(), view_signalbases.cend(),
686 [&](const shared_ptr<data::SignalBase> &sb) {
687 return sb == signalbase;
689 // Add the signal to the view as it doesn't have it yet
691 switch (signalbase->type()) {
692 case data::SignalBase::AnalogChannel:
693 case data::SignalBase::LogicChannel:
694 case data::SignalBase::DecodeChannel:
696 trace_view->add_decode_signal(
697 dynamic_pointer_cast<data::DecodeSignal>(signalbase));
700 case data::SignalBase::MathChannel:
710 void Session::deregister_view(shared_ptr<views::ViewBase> view)
712 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
714 if (views_.empty()) {
717 // Without a view there can be no main bar
722 bool Session::has_view(shared_ptr<views::ViewBase> view)
724 for (shared_ptr<views::ViewBase>& v : views_)
731 double Session::get_samplerate() const
733 double samplerate = 0.0;
735 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
737 const vector< shared_ptr<pv::data::Segment> > segments =
739 for (const shared_ptr<pv::data::Segment>& s : segments)
740 samplerate = max(samplerate, s->samplerate());
742 // If there is no sample rate given we use samples as unit
743 if (samplerate == 0.0)
749 uint32_t Session::get_segment_count() const
753 // Find the highest number of segments
754 for (const shared_ptr<data::SignalData>& data : all_signal_data_)
755 if (data->get_segment_count() > value)
756 value = data->get_segment_count();
761 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
763 vector<util::Timestamp> result;
765 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
766 if (entry.first == segment_id)
767 result.push_back(entry.second);
772 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
777 bool Session::all_segments_complete(uint32_t segment_id) const
779 bool all_complete = true;
781 for (const shared_ptr<data::SignalBase>& base : signalbases_)
782 if (!base->segment_is_complete(segment_id))
783 all_complete = false;
789 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
791 shared_ptr<data::DecodeSignal> signal;
794 // Create the decode signal
795 signal = make_shared<data::DecodeSignal>(*this);
797 signalbases_.insert(signal);
799 // Add the decode signal to all views
800 for (shared_ptr<views::ViewBase>& view : views_)
801 view->add_decode_signal(signal);
802 } catch (runtime_error& e) {
803 remove_decode_signal(signal);
812 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
814 signalbases_.erase(signal);
816 for (shared_ptr<views::ViewBase>& view : views_)
817 view->remove_decode_signal(signal);
823 void Session::set_capture_state(capture_state state)
827 if (state == Running)
829 if (state == Stopped)
830 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
833 lock_guard<mutex> lock(sampling_mutex_);
834 changed = capture_state_ != state;
835 capture_state_ = state;
839 capture_state_changed(state);
842 void Session::update_signals()
845 signalbases_.clear();
847 for (shared_ptr<views::ViewBase>& view : views_) {
848 view->clear_signals();
850 view->clear_decode_signals();
856 lock_guard<recursive_mutex> lock(data_mutex_);
858 const shared_ptr<sigrok::Device> sr_dev = device_->device();
860 signalbases_.clear();
862 for (shared_ptr<views::ViewBase>& view : views_) {
863 view->clear_signals();
865 view->clear_decode_signals();
871 // Detect what data types we will receive
872 auto channels = sr_dev->channels();
873 unsigned int logic_channel_count = count_if(
874 channels.begin(), channels.end(),
875 [] (shared_ptr<Channel> channel) {
876 return channel->type() == sigrok::ChannelType::LOGIC; });
878 // Create data containers for the logic data segments
880 lock_guard<recursive_mutex> data_lock(data_mutex_);
882 if (logic_channel_count == 0) {
884 } else if (!logic_data_ ||
885 logic_data_->num_channels() != logic_channel_count) {
886 logic_data_.reset(new data::Logic(
887 logic_channel_count));
892 // Make the signals list
893 for (shared_ptr<views::ViewBase>& viewbase : views_) {
894 views::trace::View *trace_view =
895 qobject_cast<views::trace::View*>(viewbase.get());
898 unordered_set< shared_ptr<views::trace::Signal> >
899 prev_sigs(trace_view->signals());
900 trace_view->clear_signals();
902 for (auto channel : sr_dev->channels()) {
903 shared_ptr<data::SignalBase> signalbase;
904 shared_ptr<views::trace::Signal> signal;
906 // Find the channel in the old signals
907 const auto iter = find_if(
908 prev_sigs.cbegin(), prev_sigs.cend(),
909 [&](const shared_ptr<views::trace::Signal> &s) {
910 return s->base()->channel() == channel;
912 if (iter != prev_sigs.end()) {
913 // Copy the signal from the old set to the new
915 trace_view->add_signal(signal);
917 // Find the signalbase for this channel if possible
919 for (const shared_ptr<data::SignalBase>& b : signalbases_)
920 if (b->channel() == channel)
923 switch(channel->type()->id()) {
924 case SR_CHANNEL_LOGIC:
926 signalbase = make_shared<data::SignalBase>(channel,
927 data::SignalBase::LogicChannel);
928 signalbases_.insert(signalbase);
930 all_signal_data_.insert(logic_data_);
931 signalbase->set_data(logic_data_);
933 connect(this, SIGNAL(capture_state_changed(int)),
934 signalbase.get(), SLOT(on_capture_state_changed(int)));
937 signal = shared_ptr<views::trace::Signal>(
938 new views::trace::LogicSignal(*this,
939 device_, signalbase));
940 trace_view->add_signal(signal);
943 case SR_CHANNEL_ANALOG:
946 signalbase = make_shared<data::SignalBase>(channel,
947 data::SignalBase::AnalogChannel);
948 signalbases_.insert(signalbase);
950 shared_ptr<data::Analog> data(new data::Analog());
951 all_signal_data_.insert(data);
952 signalbase->set_data(data);
954 connect(this, SIGNAL(capture_state_changed(int)),
955 signalbase.get(), SLOT(on_capture_state_changed(int)));
958 signal = shared_ptr<views::trace::Signal>(
959 new views::trace::AnalogSignal(
961 trace_view->add_signal(signal);
977 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
978 shared_ptr<sigrok::Channel> channel) const
980 for (shared_ptr<data::SignalBase> sig : signalbases_) {
982 if (sig->channel() == channel)
985 return shared_ptr<data::SignalBase>();
988 void Session::sample_thread_proc(function<void (const QString)> error_handler)
990 assert(error_handler);
993 pipeline_ = Pipeline::create();
995 source_ = ElementFactory::create_element("filesrc", "source");
996 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
998 pipeline_->add(source_)->add(sink_);
999 source_->link(sink_);
1001 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1003 sink_->set_property("emit-signals", TRUE);
1004 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1006 // Get the bus from the pipeline and add a bus watch to the default main context
1007 RefPtr<Bus> bus = pipeline_->get_bus();
1008 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1010 // Start pipeline and Wait until it finished processing
1011 pipeline_done_interrupt_ = false;
1012 pipeline_->set_state(Gst::STATE_PLAYING);
1014 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1015 pipeline_done_cond_.wait(pipeline_done_lock_);
1017 // Let the pipeline free all resources
1018 pipeline_->set_state(Gst::STATE_NULL);
1025 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1026 } catch (Error& e) {
1027 cur_samplerate_ = 0;
1030 out_of_memory_ = false;
1033 lock_guard<recursive_mutex> lock(data_mutex_);
1034 cur_logic_segment_.reset();
1035 cur_analog_segments_.clear();
1037 highest_segment_id_ = -1;
1038 frame_began_ = false;
1042 } catch (Error& e) {
1043 error_handler(e.what());
1047 set_capture_state(device_->session()->trigger() ?
1048 AwaitingTrigger : Running);
1052 } catch (Error& e) {
1053 error_handler(e.what());
1054 set_capture_state(Stopped);
1056 } catch (QString& e) {
1058 set_capture_state(Stopped);
1062 set_capture_state(Stopped);
1064 // Confirm that SR_DF_END was received
1065 if (cur_logic_segment_)
1066 qDebug() << "WARNING: SR_DF_END was not received.";
1069 // Optimize memory usage
1070 free_unused_memory();
1072 // We now have unsaved data unless we just "captured" from a file
1073 shared_ptr<devices::File> file_device =
1074 dynamic_pointer_cast<devices::File>(device_);
1077 data_saved_ = false;
1080 error_handler(tr("Out of memory, acquisition stopped."));
1083 void Session::free_unused_memory()
1085 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1086 const vector< shared_ptr<data::Segment> > segments = data->segments();
1088 for (const shared_ptr<data::Segment>& segment : segments)
1089 segment->free_unused_memory();
1093 void Session::signal_new_segment()
1095 int new_segment_id = 0;
1097 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1099 // Determine new frame/segment number, assuming that all
1100 // signals have the same number of frames/segments
1101 if (cur_logic_segment_) {
1102 new_segment_id = logic_data_->get_segment_count() - 1;
1104 shared_ptr<sigrok::Channel> any_channel =
1105 (*cur_analog_segments_.begin()).first;
1107 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1110 shared_ptr<data::Analog> data(base->analog_data());
1113 new_segment_id = data->get_segment_count() - 1;
1117 if (new_segment_id > highest_segment_id_) {
1118 highest_segment_id_ = new_segment_id;
1119 new_segment(highest_segment_id_);
1123 void Session::signal_segment_completed()
1127 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1128 // We only care about analog and logic channels, not derived ones
1129 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1130 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1134 if (signalbase->type() == data::SignalBase::LogicChannel) {
1135 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1140 if (segment_id >= 0)
1141 segment_completed(segment_id);
1145 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1149 if ((message->get_source() == pipeline_) && \
1150 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1151 pipeline_done_cond_.notify_one();
1153 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1158 Gst::FlowReturn Session::on_gst_new_sample()
1160 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1161 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1163 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1164 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1165 Gst::MapInfo mapinfo;
1166 buf_mem->map(mapinfo, Gst::MAP_READ);
1168 shared_ptr<sigrok::Packet> logic_packet =
1169 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1172 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1173 } catch (bad_alloc&) {
1174 out_of_memory_ = true;
1176 buf_mem->unmap(mapinfo);
1177 return Gst::FLOW_ERROR;
1180 buf_mem->unmap(mapinfo);
1183 return Gst::FLOW_OK;
1187 void Session::feed_in_header()
1189 // Nothing to do here for now
1192 void Session::feed_in_meta(shared_ptr<Meta> meta)
1194 for (auto& entry : meta->config()) {
1195 switch (entry.first->id()) {
1196 case SR_CONF_SAMPLERATE:
1197 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1200 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1208 void Session::feed_in_trigger()
1210 // The channel containing most samples should be most accurate
1211 uint64_t sample_count = 0;
1214 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1216 uint64_t temp_count = 0;
1218 const vector< shared_ptr<pv::data::Segment> > segments =
1220 for (const shared_ptr<pv::data::Segment> &s : segments)
1221 temp_count += s->get_sample_count();
1223 if (temp_count > sample_count)
1224 sample_count = temp_count;
1228 uint32_t segment_id = 0; // Default segment when no frames are used
1230 // If a frame began, we'd ideally be able to use the highest segment ID for
1231 // the trigger. However, as new segments are only created when logic or
1232 // analog data comes in, this doesn't work if the trigger appears right
1233 // after the beginning of the frame, before any sample data.
1234 // For this reason, we use highest segment ID + 1 if no sample data came in
1235 // yet and the highest segment ID otherwise.
1237 segment_id = highest_segment_id_;
1238 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1242 // TODO Create timestamp from segment start time + segment's current sample count
1243 util::Timestamp timestamp = sample_count / get_samplerate();
1244 trigger_list_.emplace_back(segment_id, timestamp);
1245 trigger_event(segment_id, timestamp);
1248 void Session::feed_in_frame_begin()
1250 frame_began_ = true;
1253 void Session::feed_in_frame_end()
1259 lock_guard<recursive_mutex> lock(data_mutex_);
1261 if (cur_logic_segment_)
1262 cur_logic_segment_->set_complete();
1264 for (auto& entry : cur_analog_segments_) {
1265 shared_ptr<data::AnalogSegment> segment = entry.second;
1266 segment->set_complete();
1269 cur_logic_segment_.reset();
1270 cur_analog_segments_.clear();
1273 frame_began_ = false;
1275 signal_segment_completed();
1278 void Session::feed_in_logic(shared_ptr<Logic> logic)
1280 if (logic->data_length() == 0) {
1281 qDebug() << "WARNING: Received logic packet with 0 samples.";
1285 if (logic->unit_size() > 8)
1286 throw QString(tr("Can't handle more than 64 logic channels."));
1288 if (!cur_samplerate_)
1290 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1291 } catch (Error& e) {
1295 lock_guard<recursive_mutex> lock(data_mutex_);
1298 // The only reason logic_data_ would not have been created is
1299 // if it was not possible to determine the signals when the
1300 // device was created.
1304 if (!cur_logic_segment_) {
1305 // This could be the first packet after a trigger
1306 set_capture_state(Running);
1308 // Create a new data segment
1309 cur_logic_segment_ = make_shared<data::LogicSegment>(
1310 *logic_data_, logic_data_->get_segment_count(),
1311 logic->unit_size(), cur_samplerate_);
1312 logic_data_->push_segment(cur_logic_segment_);
1314 signal_new_segment();
1317 cur_logic_segment_->append_payload(logic);
1322 void Session::feed_in_analog(shared_ptr<Analog> analog)
1324 if (analog->num_samples() == 0) {
1325 qDebug() << "WARNING: Received analog packet with 0 samples.";
1329 if (!cur_samplerate_)
1331 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1332 } catch (Error& e) {
1336 lock_guard<recursive_mutex> lock(data_mutex_);
1338 const vector<shared_ptr<Channel>> channels = analog->channels();
1339 bool sweep_beginning = false;
1341 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1342 analog->get_data_as_float(data.get());
1344 if (signalbases_.empty())
1347 float *channel_data = data.get();
1348 for (auto& channel : channels) {
1349 shared_ptr<data::AnalogSegment> segment;
1351 // Try to get the segment of the channel
1352 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1353 iterator iter = cur_analog_segments_.find(channel);
1354 if (iter != cur_analog_segments_.end())
1355 segment = (*iter).second;
1357 // If no segment was found, this means we haven't
1358 // created one yet. i.e. this is the first packet
1359 // in the sweep containing this segment.
1360 sweep_beginning = true;
1362 // Find the analog data associated with the channel
1363 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1366 shared_ptr<data::Analog> data(base->analog_data());
1369 // Create a segment, keep it in the maps of channels
1370 segment = make_shared<data::AnalogSegment>(
1371 *data, data->get_segment_count(), cur_samplerate_);
1372 cur_analog_segments_[channel] = segment;
1374 // Push the segment into the analog data.
1375 data->push_segment(segment);
1377 signal_new_segment();
1382 // Append the samples in the segment
1383 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1387 if (sweep_beginning) {
1388 // This could be the first packet after a trigger
1389 set_capture_state(Running);
1395 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1396 shared_ptr<Packet> packet)
1401 assert(device == device_->device());
1404 switch (packet->type()->id()) {
1410 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1419 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1420 } catch (bad_alloc&) {
1421 out_of_memory_ = true;
1428 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1429 } catch (bad_alloc&) {
1430 out_of_memory_ = true;
1435 case SR_DF_FRAME_BEGIN:
1436 feed_in_frame_begin();
1439 case SR_DF_FRAME_END:
1440 feed_in_frame_end();
1444 // Strictly speaking, this is performed when a frame end marker was
1445 // received, so there's no point doing this again. However, not all
1446 // devices use frames, and for those devices, we need to do it here.
1448 lock_guard<recursive_mutex> lock(data_mutex_);
1450 if (cur_logic_segment_)
1451 cur_logic_segment_->set_complete();
1453 for (auto& entry : cur_analog_segments_) {
1454 shared_ptr<data::AnalogSegment> segment = entry.second;
1455 segment->set_complete();
1458 cur_logic_segment_.reset();
1459 cur_analog_segments_.clear();
1468 void Session::on_data_saved()
1473 #ifdef ENABLE_DECODE
1474 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1476 assert(decoders.size() > 0);
1478 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1481 for (const srd_decoder* d : decoders)
1482 signal->stack_decoder(d);