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 settings.setValue("type", view->get_type());
222 view->save_settings(settings);
227 settings.setValue("views", views);
230 void Session::save_settings(QSettings &settings) const
232 map<string, string> dev_info;
233 list<string> key_list;
236 shared_ptr<devices::HardwareDevice> hw_device =
237 dynamic_pointer_cast< devices::HardwareDevice >(device_);
240 settings.setValue("device_type", "hardware");
241 settings.beginGroup("device");
243 key_list.emplace_back("vendor");
244 key_list.emplace_back("model");
245 key_list.emplace_back("version");
246 key_list.emplace_back("serial_num");
247 key_list.emplace_back("connection_id");
249 dev_info = device_manager_.get_device_info(device_);
251 for (string& key : key_list) {
252 if (dev_info.count(key))
253 settings.setValue(QString::fromUtf8(key.c_str()),
254 QString::fromUtf8(dev_info.at(key).c_str()));
256 settings.remove(QString::fromUtf8(key.c_str()));
262 shared_ptr<devices::SessionFile> sessionfile_device =
263 dynamic_pointer_cast<devices::SessionFile>(device_);
265 if (sessionfile_device) {
266 settings.setValue("device_type", "sessionfile");
267 settings.beginGroup("device");
268 settings.setValue("filename", QString::fromStdString(
269 sessionfile_device->full_name()));
273 shared_ptr<devices::InputFile> inputfile_device =
274 dynamic_pointer_cast<devices::InputFile>(device_);
276 if (inputfile_device) {
277 settings.setValue("device_type", "inputfile");
278 settings.beginGroup("device");
279 inputfile_device->save_meta_to_settings(settings);
283 save_setup(settings);
287 void Session::restore_setup(QSettings &settings)
290 for (shared_ptr<data::SignalBase> base : signalbases_) {
291 settings.beginGroup(base->internal_name());
292 base->restore_settings(settings);
298 int decode_signals = settings.value("decode_signals").toInt();
300 for (int i = 0; i < decode_signals; i++) {
301 settings.beginGroup("decode_signal" + QString::number(i));
302 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
303 signal->restore_settings(settings);
309 int views = settings.value("views").toInt();
311 for (int i = 0; i < views; i++) {
312 settings.beginGroup("view" + QString::number(i));
315 views::ViewType type = (views::ViewType)settings.value("type").toInt();
316 add_view(type, this);
317 views_.back()->restore_settings(settings);
319 main_view_->restore_settings(settings);
325 void Session::restore_settings(QSettings &settings)
327 shared_ptr<devices::Device> device;
329 QString device_type = settings.value("device_type").toString();
331 if (device_type == "hardware") {
332 map<string, string> dev_info;
333 list<string> key_list;
335 // Re-select last used device if possible but only if it's not demo
336 settings.beginGroup("device");
337 key_list.emplace_back("vendor");
338 key_list.emplace_back("model");
339 key_list.emplace_back("version");
340 key_list.emplace_back("serial_num");
341 key_list.emplace_back("connection_id");
343 for (string key : key_list) {
344 const QString k = QString::fromStdString(key);
345 if (!settings.contains(k))
348 const string value = settings.value(k).toString().toStdString();
350 dev_info.insert(make_pair(key, value));
353 if (dev_info.count("model") > 0)
354 device = device_manager_.find_device_from_info(dev_info);
362 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
363 if (device_type == "sessionfile") {
364 settings.beginGroup("device");
365 QString filename = settings.value("filename").toString();
368 if (QFileInfo(filename).isReadable()) {
369 device = make_shared<devices::SessionFile>(device_manager_.context(),
370 filename.toStdString());
374 if (device_type == "inputfile") {
375 settings.beginGroup("device");
376 device = make_shared<devices::InputFile>(device_manager_.context(),
384 start_capture([](QString infoMessage) {
385 // TODO Emulate noquote()
386 qDebug() << "Session error:" << infoMessage; });
388 set_name(QString::fromStdString(
389 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
394 restore_setup(settings);
397 void Session::select_device(shared_ptr<devices::Device> device)
403 set_default_device();
404 } catch (const QString &e) {
405 MainWindow::show_session_error(tr("Failed to select device"), e);
409 void Session::set_device(shared_ptr<devices::Device> device)
413 // Ensure we are not capturing before setting the device
421 // Revert name back to default name (e.g. "Session 1") as the data is gone
422 name_ = default_name_;
425 // Remove all stored data and reset all views
426 for (shared_ptr<views::ViewBase> view : views_) {
427 view->clear_signals();
429 view->clear_decode_signals();
431 view->reset_view_state();
433 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
435 all_signal_data_.clear();
436 signalbases_.clear();
437 cur_logic_segment_.reset();
439 for (auto& entry : cur_analog_segments_) {
440 shared_ptr<sigrok::Channel>(entry.first).reset();
441 shared_ptr<data::AnalogSegment>(entry.second).reset();
448 device_ = move(device);
452 } catch (const QString &e) {
454 MainWindow::show_session_error(tr("Failed to open device"), e);
458 device_->session()->add_datafeed_callback([=]
459 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
460 data_feed_in(device, packet);
469 void Session::set_default_device()
471 const list< shared_ptr<devices::HardwareDevice> > &devices =
472 device_manager_.devices();
477 // Try and find the demo device and select that by default
478 const auto iter = find_if(devices.begin(), devices.end(),
479 [] (const shared_ptr<devices::HardwareDevice> &d) {
480 return d->hardware_device()->driver()->name() == "demo"; });
481 set_device((iter == devices.end()) ? devices.front() : *iter);
485 * Convert generic options to data types that are specific to InputFormat.
487 * @param[in] user_spec Vector of tokenized words, string format.
488 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
490 * @return Map of options suitable for InputFormat::create_input().
492 map<string, Glib::VariantBase>
493 Session::input_format_options(vector<string> user_spec,
494 map<string, shared_ptr<Option>> fmt_opts)
496 map<string, Glib::VariantBase> result;
498 for (auto& entry : user_spec) {
500 * Split key=value specs. Accept entries without separator
501 * (for simplified boolean specifications).
504 size_t pos = entry.find("=");
505 if (pos == std::string::npos) {
509 key = entry.substr(0, pos);
510 val = entry.substr(pos + 1);
514 * Skip user specifications that are not a member of the
515 * format's set of supported options. Have the text input
516 * spec converted to the required input format specific
519 auto found = fmt_opts.find(key);
520 if (found == fmt_opts.end())
522 shared_ptr<Option> opt = found->second;
523 result[key] = opt->parse_string(val);
529 void Session::load_init_file(const string &file_name,
530 const string &format, const string &setup_file_name)
532 shared_ptr<InputFormat> input_format;
533 map<string, Glib::VariantBase> input_opts;
535 if (!format.empty()) {
536 const map<string, shared_ptr<InputFormat> > formats =
537 device_manager_.context()->input_formats();
538 auto user_opts = pv::util::split_string(format, ":");
539 string user_name = user_opts.front();
540 user_opts.erase(user_opts.begin());
541 const auto iter = find_if(formats.begin(), formats.end(),
542 [&](const pair<string, shared_ptr<InputFormat> > f) {
543 return f.first == user_name; });
544 if (iter == formats.end()) {
545 MainWindow::show_session_error(tr("Error"),
546 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
549 input_format = (*iter).second;
550 input_opts = input_format_options(user_opts,
551 input_format->options());
554 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
555 input_format, input_opts);
558 void Session::load_file(QString file_name, QString setup_file_name,
559 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
561 const QString errorMessage(
562 QString("Failed to load file %1").arg(file_name));
564 // In the absence of a caller's format spec, try to auto detect.
565 // Assume "sigrok session file" upon lookup miss.
567 format = device_manager_.context()->input_format_match(file_name.toStdString());
570 set_device(shared_ptr<devices::Device>(
571 new devices::InputFile(
572 device_manager_.context(),
573 file_name.toStdString(),
576 set_device(shared_ptr<devices::Device>(
577 new devices::SessionFile(
578 device_manager_.context(),
579 file_name.toStdString())));
581 MainWindow::show_session_error(tr("Failed to load ") + file_name, e.what());
582 set_default_device();
583 main_bar_->update_device_list();
587 // Use the input file with .pvs extension if no setup file was given
588 if (setup_file_name.isEmpty()) {
589 setup_file_name = file_name;
590 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
591 setup_file_name.append(".pvs");
594 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
595 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
596 restore_setup(settings_storage);
599 main_bar_->update_device_list();
601 start_capture([&, errorMessage](QString infoMessage) {
602 MainWindow::show_session_error(errorMessage, infoMessage); });
604 set_name(QFileInfo(file_name).fileName());
607 Session::capture_state Session::get_capture_state() const
609 lock_guard<mutex> lock(sampling_mutex_);
610 return capture_state_;
613 void Session::start_capture(function<void (const QString)> error_handler)
616 error_handler(tr("No active device set, can't start acquisition."));
622 // Check that at least one channel is enabled
623 const shared_ptr<sigrok::Device> sr_dev = device_->device();
625 const auto channels = sr_dev->channels();
626 if (!any_of(channels.begin(), channels.end(),
627 [](shared_ptr<Channel> channel) {
628 return channel->enabled(); })) {
629 error_handler(tr("No channels enabled."));
635 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
638 trigger_list_.clear();
640 // Revert name back to default name (e.g. "Session 1") for real devices
641 // as the (possibly saved) data is gone. File devices keep their name.
642 shared_ptr<devices::HardwareDevice> hw_device =
643 dynamic_pointer_cast< devices::HardwareDevice >(device_);
646 name_ = default_name_;
651 sampling_thread_ = std::thread(
652 &Session::sample_thread_proc, this, error_handler);
655 void Session::stop_capture()
657 if (get_capture_state() != Stopped)
660 // Check that sampling stopped
661 if (sampling_thread_.joinable())
662 sampling_thread_.join();
665 void Session::register_view(shared_ptr<views::ViewBase> view)
667 if (views_.empty()) {
671 views_.push_back(view);
673 // Add all device signals
676 // Add all other signals
677 unordered_set< shared_ptr<data::SignalBase> > view_signalbases =
680 views::trace::View *trace_view =
681 qobject_cast<views::trace::View*>(view.get());
684 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
685 const int sb_exists = count_if(
686 view_signalbases.cbegin(), view_signalbases.cend(),
687 [&](const shared_ptr<data::SignalBase> &sb) {
688 return sb == signalbase;
690 // Add the signal to the view as it doesn't have it yet
692 switch (signalbase->type()) {
693 case data::SignalBase::AnalogChannel:
694 case data::SignalBase::LogicChannel:
695 case data::SignalBase::DecodeChannel:
697 trace_view->add_decode_signal(
698 dynamic_pointer_cast<data::DecodeSignal>(signalbase));
701 case data::SignalBase::MathChannel:
711 void Session::deregister_view(shared_ptr<views::ViewBase> view)
713 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
715 if (views_.empty()) {
718 // Without a view there can be no main bar
723 bool Session::has_view(shared_ptr<views::ViewBase> view)
725 for (shared_ptr<views::ViewBase>& v : views_)
732 double Session::get_samplerate() const
734 double samplerate = 0.0;
736 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
738 const vector< shared_ptr<pv::data::Segment> > segments =
740 for (const shared_ptr<pv::data::Segment>& s : segments)
741 samplerate = max(samplerate, s->samplerate());
743 // If there is no sample rate given we use samples as unit
744 if (samplerate == 0.0)
750 uint32_t Session::get_segment_count() const
754 // Find the highest number of segments
755 for (const shared_ptr<data::SignalData>& data : all_signal_data_)
756 if (data->get_segment_count() > value)
757 value = data->get_segment_count();
762 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
764 vector<util::Timestamp> result;
766 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
767 if (entry.first == segment_id)
768 result.push_back(entry.second);
773 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
778 bool Session::all_segments_complete(uint32_t segment_id) const
780 bool all_complete = true;
782 for (const shared_ptr<data::SignalBase>& base : signalbases_)
783 if (!base->segment_is_complete(segment_id))
784 all_complete = false;
790 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
792 shared_ptr<data::DecodeSignal> signal;
795 // Create the decode signal
796 signal = make_shared<data::DecodeSignal>(*this);
798 signalbases_.insert(signal);
800 // Add the decode signal to all views
801 for (shared_ptr<views::ViewBase>& view : views_)
802 view->add_decode_signal(signal);
803 } catch (runtime_error& e) {
804 remove_decode_signal(signal);
813 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
815 signalbases_.erase(signal);
817 for (shared_ptr<views::ViewBase>& view : views_)
818 view->remove_decode_signal(signal);
824 void Session::set_capture_state(capture_state state)
828 if (state == Running)
830 if (state == Stopped)
831 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
834 lock_guard<mutex> lock(sampling_mutex_);
835 changed = capture_state_ != state;
836 capture_state_ = state;
840 capture_state_changed(state);
843 void Session::update_signals()
846 signalbases_.clear();
848 for (shared_ptr<views::ViewBase>& view : views_) {
849 view->clear_signals();
851 view->clear_decode_signals();
857 lock_guard<recursive_mutex> lock(data_mutex_);
859 const shared_ptr<sigrok::Device> sr_dev = device_->device();
861 signalbases_.clear();
863 for (shared_ptr<views::ViewBase>& view : views_) {
864 view->clear_signals();
866 view->clear_decode_signals();
872 // Detect what data types we will receive
873 auto channels = sr_dev->channels();
874 unsigned int logic_channel_count = count_if(
875 channels.begin(), channels.end(),
876 [] (shared_ptr<Channel> channel) {
877 return channel->type() == sigrok::ChannelType::LOGIC; });
879 // Create data containers for the logic data segments
881 lock_guard<recursive_mutex> data_lock(data_mutex_);
883 if (logic_channel_count == 0) {
885 } else if (!logic_data_ ||
886 logic_data_->num_channels() != logic_channel_count) {
887 logic_data_.reset(new data::Logic(
888 logic_channel_count));
893 // Make the signals list
894 for (shared_ptr<views::ViewBase>& viewbase : views_) {
895 views::trace::View *trace_view =
896 qobject_cast<views::trace::View*>(viewbase.get());
899 unordered_set< shared_ptr<views::trace::Signal> >
900 prev_sigs(trace_view->signals());
901 trace_view->clear_signals();
903 for (auto channel : sr_dev->channels()) {
904 shared_ptr<data::SignalBase> signalbase;
905 shared_ptr<views::trace::Signal> signal;
907 // Find the channel in the old signals
908 const auto iter = find_if(
909 prev_sigs.cbegin(), prev_sigs.cend(),
910 [&](const shared_ptr<views::trace::Signal> &s) {
911 return s->base()->channel() == channel;
913 if (iter != prev_sigs.end()) {
914 // Copy the signal from the old set to the new
916 trace_view->add_signal(signal);
918 // Find the signalbase for this channel if possible
920 for (const shared_ptr<data::SignalBase>& b : signalbases_)
921 if (b->channel() == channel)
924 switch(channel->type()->id()) {
925 case SR_CHANNEL_LOGIC:
927 signalbase = make_shared<data::SignalBase>(channel,
928 data::SignalBase::LogicChannel);
929 signalbases_.insert(signalbase);
931 all_signal_data_.insert(logic_data_);
932 signalbase->set_data(logic_data_);
934 connect(this, SIGNAL(capture_state_changed(int)),
935 signalbase.get(), SLOT(on_capture_state_changed(int)));
938 signal = shared_ptr<views::trace::Signal>(
939 new views::trace::LogicSignal(*this,
940 device_, signalbase));
941 trace_view->add_signal(signal);
944 case SR_CHANNEL_ANALOG:
947 signalbase = make_shared<data::SignalBase>(channel,
948 data::SignalBase::AnalogChannel);
949 signalbases_.insert(signalbase);
951 shared_ptr<data::Analog> data(new data::Analog());
952 all_signal_data_.insert(data);
953 signalbase->set_data(data);
955 connect(this, SIGNAL(capture_state_changed(int)),
956 signalbase.get(), SLOT(on_capture_state_changed(int)));
959 signal = shared_ptr<views::trace::Signal>(
960 new views::trace::AnalogSignal(
962 trace_view->add_signal(signal);
978 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
979 shared_ptr<sigrok::Channel> channel) const
981 for (shared_ptr<data::SignalBase> sig : signalbases_) {
983 if (sig->channel() == channel)
986 return shared_ptr<data::SignalBase>();
989 void Session::sample_thread_proc(function<void (const QString)> error_handler)
991 assert(error_handler);
994 pipeline_ = Pipeline::create();
996 source_ = ElementFactory::create_element("filesrc", "source");
997 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
999 pipeline_->add(source_)->add(sink_);
1000 source_->link(sink_);
1002 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1004 sink_->set_property("emit-signals", TRUE);
1005 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1007 // Get the bus from the pipeline and add a bus watch to the default main context
1008 RefPtr<Bus> bus = pipeline_->get_bus();
1009 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1011 // Start pipeline and Wait until it finished processing
1012 pipeline_done_interrupt_ = false;
1013 pipeline_->set_state(Gst::STATE_PLAYING);
1015 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1016 pipeline_done_cond_.wait(pipeline_done_lock_);
1018 // Let the pipeline free all resources
1019 pipeline_->set_state(Gst::STATE_NULL);
1026 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1027 } catch (Error& e) {
1028 cur_samplerate_ = 0;
1031 out_of_memory_ = false;
1034 lock_guard<recursive_mutex> lock(data_mutex_);
1035 cur_logic_segment_.reset();
1036 cur_analog_segments_.clear();
1038 highest_segment_id_ = -1;
1039 frame_began_ = false;
1043 } catch (Error& e) {
1044 error_handler(e.what());
1048 set_capture_state(device_->session()->trigger() ?
1049 AwaitingTrigger : Running);
1053 } catch (Error& e) {
1054 error_handler(e.what());
1055 set_capture_state(Stopped);
1057 } catch (QString& e) {
1059 set_capture_state(Stopped);
1063 set_capture_state(Stopped);
1065 // Confirm that SR_DF_END was received
1066 if (cur_logic_segment_)
1067 qDebug() << "WARNING: SR_DF_END was not received.";
1070 // Optimize memory usage
1071 free_unused_memory();
1073 // We now have unsaved data unless we just "captured" from a file
1074 shared_ptr<devices::File> file_device =
1075 dynamic_pointer_cast<devices::File>(device_);
1078 data_saved_ = false;
1081 error_handler(tr("Out of memory, acquisition stopped."));
1084 void Session::free_unused_memory()
1086 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1087 const vector< shared_ptr<data::Segment> > segments = data->segments();
1089 for (const shared_ptr<data::Segment>& segment : segments)
1090 segment->free_unused_memory();
1094 void Session::signal_new_segment()
1096 int new_segment_id = 0;
1098 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1100 // Determine new frame/segment number, assuming that all
1101 // signals have the same number of frames/segments
1102 if (cur_logic_segment_) {
1103 new_segment_id = logic_data_->get_segment_count() - 1;
1105 shared_ptr<sigrok::Channel> any_channel =
1106 (*cur_analog_segments_.begin()).first;
1108 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1111 shared_ptr<data::Analog> data(base->analog_data());
1114 new_segment_id = data->get_segment_count() - 1;
1118 if (new_segment_id > highest_segment_id_) {
1119 highest_segment_id_ = new_segment_id;
1120 new_segment(highest_segment_id_);
1124 void Session::signal_segment_completed()
1128 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1129 // We only care about analog and logic channels, not derived ones
1130 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1131 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1135 if (signalbase->type() == data::SignalBase::LogicChannel) {
1136 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1141 if (segment_id >= 0)
1142 segment_completed(segment_id);
1146 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1150 if ((message->get_source() == pipeline_) && \
1151 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1152 pipeline_done_cond_.notify_one();
1154 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1159 Gst::FlowReturn Session::on_gst_new_sample()
1161 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1162 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1164 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1165 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1166 Gst::MapInfo mapinfo;
1167 buf_mem->map(mapinfo, Gst::MAP_READ);
1169 shared_ptr<sigrok::Packet> logic_packet =
1170 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1173 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1174 } catch (bad_alloc&) {
1175 out_of_memory_ = true;
1177 buf_mem->unmap(mapinfo);
1178 return Gst::FLOW_ERROR;
1181 buf_mem->unmap(mapinfo);
1184 return Gst::FLOW_OK;
1188 void Session::feed_in_header()
1190 // Nothing to do here for now
1193 void Session::feed_in_meta(shared_ptr<Meta> meta)
1195 for (auto& entry : meta->config()) {
1196 switch (entry.first->id()) {
1197 case SR_CONF_SAMPLERATE:
1198 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1201 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1209 void Session::feed_in_trigger()
1211 // The channel containing most samples should be most accurate
1212 uint64_t sample_count = 0;
1215 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1217 uint64_t temp_count = 0;
1219 const vector< shared_ptr<pv::data::Segment> > segments =
1221 for (const shared_ptr<pv::data::Segment> &s : segments)
1222 temp_count += s->get_sample_count();
1224 if (temp_count > sample_count)
1225 sample_count = temp_count;
1229 uint32_t segment_id = 0; // Default segment when no frames are used
1231 // If a frame began, we'd ideally be able to use the highest segment ID for
1232 // the trigger. However, as new segments are only created when logic or
1233 // analog data comes in, this doesn't work if the trigger appears right
1234 // after the beginning of the frame, before any sample data.
1235 // For this reason, we use highest segment ID + 1 if no sample data came in
1236 // yet and the highest segment ID otherwise.
1238 segment_id = highest_segment_id_;
1239 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1243 // TODO Create timestamp from segment start time + segment's current sample count
1244 util::Timestamp timestamp = sample_count / get_samplerate();
1245 trigger_list_.emplace_back(segment_id, timestamp);
1246 trigger_event(segment_id, timestamp);
1249 void Session::feed_in_frame_begin()
1251 frame_began_ = true;
1254 void Session::feed_in_frame_end()
1260 lock_guard<recursive_mutex> lock(data_mutex_);
1262 if (cur_logic_segment_)
1263 cur_logic_segment_->set_complete();
1265 for (auto& entry : cur_analog_segments_) {
1266 shared_ptr<data::AnalogSegment> segment = entry.second;
1267 segment->set_complete();
1270 cur_logic_segment_.reset();
1271 cur_analog_segments_.clear();
1274 frame_began_ = false;
1276 signal_segment_completed();
1279 void Session::feed_in_logic(shared_ptr<Logic> logic)
1281 if (logic->data_length() == 0) {
1282 qDebug() << "WARNING: Received logic packet with 0 samples.";
1286 if (logic->unit_size() > 8)
1287 throw QString(tr("Can't handle more than 64 logic channels."));
1289 if (!cur_samplerate_)
1291 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1292 } catch (Error& e) {
1296 lock_guard<recursive_mutex> lock(data_mutex_);
1299 // The only reason logic_data_ would not have been created is
1300 // if it was not possible to determine the signals when the
1301 // device was created.
1305 if (!cur_logic_segment_) {
1306 // This could be the first packet after a trigger
1307 set_capture_state(Running);
1309 // Create a new data segment
1310 cur_logic_segment_ = make_shared<data::LogicSegment>(
1311 *logic_data_, logic_data_->get_segment_count(),
1312 logic->unit_size(), cur_samplerate_);
1313 logic_data_->push_segment(cur_logic_segment_);
1315 signal_new_segment();
1318 cur_logic_segment_->append_payload(logic);
1323 void Session::feed_in_analog(shared_ptr<Analog> analog)
1325 if (analog->num_samples() == 0) {
1326 qDebug() << "WARNING: Received analog packet with 0 samples.";
1330 if (!cur_samplerate_)
1332 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1333 } catch (Error& e) {
1337 lock_guard<recursive_mutex> lock(data_mutex_);
1339 const vector<shared_ptr<Channel>> channels = analog->channels();
1340 bool sweep_beginning = false;
1342 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1343 analog->get_data_as_float(data.get());
1345 if (signalbases_.empty())
1348 float *channel_data = data.get();
1349 for (auto& channel : channels) {
1350 shared_ptr<data::AnalogSegment> segment;
1352 // Try to get the segment of the channel
1353 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1354 iterator iter = cur_analog_segments_.find(channel);
1355 if (iter != cur_analog_segments_.end())
1356 segment = (*iter).second;
1358 // If no segment was found, this means we haven't
1359 // created one yet. i.e. this is the first packet
1360 // in the sweep containing this segment.
1361 sweep_beginning = true;
1363 // Find the analog data associated with the channel
1364 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1367 shared_ptr<data::Analog> data(base->analog_data());
1370 // Create a segment, keep it in the maps of channels
1371 segment = make_shared<data::AnalogSegment>(
1372 *data, data->get_segment_count(), cur_samplerate_);
1373 cur_analog_segments_[channel] = segment;
1375 // Push the segment into the analog data.
1376 data->push_segment(segment);
1378 signal_new_segment();
1383 // Append the samples in the segment
1384 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1388 if (sweep_beginning) {
1389 // This could be the first packet after a trigger
1390 set_capture_state(Running);
1396 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1397 shared_ptr<Packet> packet)
1402 assert(device == device_->device());
1405 switch (packet->type()->id()) {
1411 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1420 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1421 } catch (bad_alloc&) {
1422 out_of_memory_ = true;
1429 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1430 } catch (bad_alloc&) {
1431 out_of_memory_ = true;
1436 case SR_DF_FRAME_BEGIN:
1437 feed_in_frame_begin();
1440 case SR_DF_FRAME_END:
1441 feed_in_frame_end();
1445 // Strictly speaking, this is performed when a frame end marker was
1446 // received, so there's no point doing this again. However, not all
1447 // devices use frames, and for those devices, we need to do it here.
1449 lock_guard<recursive_mutex> lock(data_mutex_);
1451 if (cur_logic_segment_)
1452 cur_logic_segment_->set_complete();
1454 for (auto& entry : cur_analog_segments_) {
1455 shared_ptr<data::AnalogSegment> segment = entry.second;
1456 segment->set_complete();
1459 cur_logic_segment_.reset();
1460 cur_analog_segments_.clear();
1469 void Session::on_data_saved()
1474 #ifdef ENABLE_DECODE
1475 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1477 assert(decoders.size() > 0);
1479 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1482 for (const srd_decoder* d : decoders)
1483 signal->stack_decoder(d);