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 <libsigrokdecode/libsigrokdecode.h>
57 #include "data/decodesignal.hpp"
61 using std::dynamic_pointer_cast;
64 using std::lock_guard;
67 using std::make_shared;
73 using std::recursive_mutex;
74 using std::runtime_error;
75 using std::shared_ptr;
77 using std::unique_ptr;
78 using std::unordered_set;
82 using sigrok::Channel;
83 using sigrok::ConfigKey;
84 using sigrok::DatafeedCallbackFunction;
86 using sigrok::InputFormat;
90 using sigrok::Session;
92 using Glib::VariantBase;
96 shared_ptr<sigrok::Context> Session::sr_context;
98 Session::Session(DeviceManager &device_manager, QString name) :
99 device_manager_(device_manager),
102 capture_state_(Stopped),
110 // Stop and join to the thread
114 DeviceManager& Session::device_manager()
116 return device_manager_;
119 const DeviceManager& Session::device_manager() const
121 return device_manager_;
124 shared_ptr<sigrok::Session> Session::session() const
127 return shared_ptr<sigrok::Session>();
128 return device_->session();
131 shared_ptr<devices::Device> Session::device() const
136 QString Session::name() const
141 void Session::set_name(QString name)
143 if (default_name_.isEmpty())
144 default_name_ = name;
151 const list< shared_ptr<views::ViewBase> > Session::views() const
156 shared_ptr<views::ViewBase> Session::main_view() const
161 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
163 main_bar_ = main_bar;
166 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
171 bool Session::data_saved() const
176 void Session::save_settings(QSettings &settings) const
178 map<string, string> dev_info;
179 list<string> key_list;
180 int decode_signals = 0, views = 0;
183 shared_ptr<devices::HardwareDevice> hw_device =
184 dynamic_pointer_cast< devices::HardwareDevice >(device_);
187 settings.setValue("device_type", "hardware");
188 settings.beginGroup("device");
190 key_list.emplace_back("vendor");
191 key_list.emplace_back("model");
192 key_list.emplace_back("version");
193 key_list.emplace_back("serial_num");
194 key_list.emplace_back("connection_id");
196 dev_info = device_manager_.get_device_info(device_);
198 for (string key : key_list) {
199 if (dev_info.count(key))
200 settings.setValue(QString::fromUtf8(key.c_str()),
201 QString::fromUtf8(dev_info.at(key).c_str()));
203 settings.remove(QString::fromUtf8(key.c_str()));
209 shared_ptr<devices::SessionFile> sessionfile_device =
210 dynamic_pointer_cast<devices::SessionFile>(device_);
212 if (sessionfile_device) {
213 settings.setValue("device_type", "sessionfile");
214 settings.beginGroup("device");
215 settings.setValue("filename", QString::fromStdString(
216 sessionfile_device->full_name()));
220 shared_ptr<devices::InputFile> inputfile_device =
221 dynamic_pointer_cast<devices::InputFile>(device_);
223 if (inputfile_device) {
224 settings.setValue("device_type", "inputfile");
225 settings.beginGroup("device");
226 inputfile_device->save_meta_to_settings(settings);
230 // Save channels and decoders
231 for (shared_ptr<data::SignalBase> base : signalbases_) {
233 if (base->is_decode_signal()) {
234 settings.beginGroup("decode_signal" + QString::number(decode_signals++));
235 base->save_settings(settings);
240 settings.beginGroup(base->internal_name());
241 base->save_settings(settings);
246 settings.setValue("decode_signals", decode_signals);
248 // Save view states and their signal settings
249 // Note: main_view must be saved as view0
250 settings.beginGroup("view" + QString::number(views++));
251 main_view_->save_settings(settings);
254 for (shared_ptr<views::ViewBase> view : views_) {
255 if (view != main_view_) {
256 settings.beginGroup("view" + QString::number(views++));
257 view->save_settings(settings);
262 settings.setValue("views", views);
266 void Session::restore_settings(QSettings &settings)
268 shared_ptr<devices::Device> device;
270 QString device_type = settings.value("device_type").toString();
272 if (device_type == "hardware") {
273 map<string, string> dev_info;
274 list<string> key_list;
276 // Re-select last used device if possible but only if it's not demo
277 settings.beginGroup("device");
278 key_list.emplace_back("vendor");
279 key_list.emplace_back("model");
280 key_list.emplace_back("version");
281 key_list.emplace_back("serial_num");
282 key_list.emplace_back("connection_id");
284 for (string key : key_list) {
285 const QString k = QString::fromStdString(key);
286 if (!settings.contains(k))
289 const string value = settings.value(k).toString().toStdString();
291 dev_info.insert(make_pair(key, value));
294 if (dev_info.count("model") > 0)
295 device = device_manager_.find_device_from_info(dev_info);
303 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
304 if (device_type == "sessionfile") {
305 settings.beginGroup("device");
306 QString filename = settings.value("filename").toString();
309 if (QFileInfo(filename).isReadable()) {
310 device = make_shared<devices::SessionFile>(device_manager_.context(),
311 filename.toStdString());
315 if (device_type == "inputfile") {
316 settings.beginGroup("device");
317 device = make_shared<devices::InputFile>(device_manager_.context(),
325 start_capture([](QString infoMessage) {
326 // TODO Emulate noquote()
327 qDebug() << "Session error:" << infoMessage; });
329 set_name(QString::fromStdString(
330 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
336 for (shared_ptr<data::SignalBase> base : signalbases_) {
337 settings.beginGroup(base->internal_name());
338 base->restore_settings(settings);
344 int decode_signals = settings.value("decode_signals").toInt();
346 for (int i = 0; i < decode_signals; i++) {
347 settings.beginGroup("decode_signal" + QString::number(i));
348 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
349 signal->restore_settings(settings);
355 int views = settings.value("views").toInt();
357 for (int i = 0; i < views; i++) {
358 settings.beginGroup("view" + QString::number(i));
361 views::ViewType type = (views::ViewType)settings.value("type").toInt();
362 add_view(name_, type, this);
363 views_.back()->restore_settings(settings);
365 main_view_->restore_settings(settings);
372 void Session::select_device(shared_ptr<devices::Device> device)
378 set_default_device();
379 } catch (const QString &e) {
380 MainWindow::show_session_error(tr("Failed to select device"), e);
384 void Session::set_device(shared_ptr<devices::Device> device)
388 // Ensure we are not capturing before setting the device
396 // Revert name back to default name (e.g. "Session 1") as the data is gone
397 name_ = default_name_;
400 // Remove all stored data
401 for (shared_ptr<views::ViewBase> view : views_) {
402 view->clear_signals();
404 view->clear_decode_signals();
407 for (const shared_ptr<data::SignalData> d : all_signal_data_)
409 all_signal_data_.clear();
410 signalbases_.clear();
411 cur_logic_segment_.reset();
413 for (auto entry : cur_analog_segments_) {
414 shared_ptr<sigrok::Channel>(entry.first).reset();
415 shared_ptr<data::AnalogSegment>(entry.second).reset();
422 device_ = move(device);
426 } catch (const QString &e) {
428 MainWindow::show_session_error(tr("Failed to open device"), e);
432 device_->session()->add_datafeed_callback([=]
433 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
434 data_feed_in(device, packet);
443 void Session::set_default_device()
445 const list< shared_ptr<devices::HardwareDevice> > &devices =
446 device_manager_.devices();
451 // Try and find the demo device and select that by default
452 const auto iter = find_if(devices.begin(), devices.end(),
453 [] (const shared_ptr<devices::HardwareDevice> &d) {
454 return d->hardware_device()->driver()->name() == "demo"; });
455 set_device((iter == devices.end()) ? devices.front() : *iter);
459 * Convert generic options to data types that are specific to InputFormat.
461 * @param[in] user_spec Vector of tokenized words, string format.
462 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
464 * @return Map of options suitable for InputFormat::create_input().
466 map<string, Glib::VariantBase>
467 Session::input_format_options(vector<string> user_spec,
468 map<string, shared_ptr<Option>> fmt_opts)
470 map<string, Glib::VariantBase> result;
472 for (auto entry : user_spec) {
474 * Split key=value specs. Accept entries without separator
475 * (for simplified boolean specifications).
478 size_t pos = entry.find("=");
479 if (pos == std::string::npos) {
483 key = entry.substr(0, pos);
484 val = entry.substr(pos + 1);
488 * Skip user specifications that are not a member of the
489 * format's set of supported options. Have the text input
490 * spec converted to the required input format specific
493 auto found = fmt_opts.find(key);
494 if (found == fmt_opts.end())
496 shared_ptr<Option> opt = found->second;
497 result[key] = opt->parse_string(val);
503 void Session::load_init_file(const string &file_name, const string &format)
505 shared_ptr<InputFormat> input_format;
506 map<string, Glib::VariantBase> input_opts;
508 if (!format.empty()) {
509 const map<string, shared_ptr<InputFormat> > formats =
510 device_manager_.context()->input_formats();
511 auto user_opts = pv::util::split_string(format, ":");
512 string user_name = user_opts.front();
513 user_opts.erase(user_opts.begin());
514 const auto iter = find_if(formats.begin(), formats.end(),
515 [&](const pair<string, shared_ptr<InputFormat> > f) {
516 return f.first == user_name; });
517 if (iter == formats.end()) {
518 MainWindow::show_session_error(tr("Error"),
519 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
522 input_format = (*iter).second;
523 input_opts = input_format_options(user_opts,
524 input_format->options());
527 load_file(QString::fromStdString(file_name), input_format, input_opts);
530 void Session::load_file(QString file_name,
531 shared_ptr<sigrok::InputFormat> format,
532 const map<string, Glib::VariantBase> &options)
534 const QString errorMessage(
535 QString("Failed to load file %1").arg(file_name));
537 // In the absence of a caller's format spec, try to auto detect.
538 // Assume "sigrok session file" upon lookup miss.
540 format = device_manager_.context()->input_format_match(file_name.toStdString());
543 set_device(shared_ptr<devices::Device>(
544 new devices::InputFile(
545 device_manager_.context(),
546 file_name.toStdString(),
549 set_device(shared_ptr<devices::Device>(
550 new devices::SessionFile(
551 device_manager_.context(),
552 file_name.toStdString())));
554 MainWindow::show_session_error(tr("Failed to load ") + file_name, e.what());
555 set_default_device();
556 main_bar_->update_device_list();
560 main_bar_->update_device_list();
562 start_capture([&, errorMessage](QString infoMessage) {
563 MainWindow::show_session_error(errorMessage, infoMessage); });
565 set_name(QFileInfo(file_name).fileName());
568 Session::capture_state Session::get_capture_state() const
570 lock_guard<mutex> lock(sampling_mutex_);
571 return capture_state_;
574 void Session::start_capture(function<void (const QString)> error_handler)
577 error_handler(tr("No active device set, can't start acquisition."));
583 // Check that at least one channel is enabled
584 const shared_ptr<sigrok::Device> sr_dev = device_->device();
586 const auto channels = sr_dev->channels();
587 if (!any_of(channels.begin(), channels.end(),
588 [](shared_ptr<Channel> channel) {
589 return channel->enabled(); })) {
590 error_handler(tr("No channels enabled."));
596 for (const shared_ptr<data::SignalData> d : all_signal_data_)
599 trigger_list_.clear();
601 // Revert name back to default name (e.g. "Session 1") for real devices
602 // as the (possibly saved) data is gone. File devices keep their name.
603 shared_ptr<devices::HardwareDevice> hw_device =
604 dynamic_pointer_cast< devices::HardwareDevice >(device_);
607 name_ = default_name_;
612 sampling_thread_ = std::thread(
613 &Session::sample_thread_proc, this, error_handler);
616 void Session::stop_capture()
618 if (get_capture_state() != Stopped)
621 // Check that sampling stopped
622 if (sampling_thread_.joinable())
623 sampling_thread_.join();
626 void Session::register_view(shared_ptr<views::ViewBase> view)
628 if (views_.empty()) {
632 views_.push_back(view);
634 // Add all device signals
637 // Add all other signals
638 unordered_set< shared_ptr<data::SignalBase> > view_signalbases =
641 views::trace::View *trace_view =
642 qobject_cast<views::trace::View*>(view.get());
645 for (shared_ptr<data::SignalBase> signalbase : signalbases_) {
646 const int sb_exists = count_if(
647 view_signalbases.cbegin(), view_signalbases.cend(),
648 [&](const shared_ptr<data::SignalBase> &sb) {
649 return sb == signalbase;
651 // Add the signal to the view as it doesn't have it yet
653 switch (signalbase->type()) {
654 case data::SignalBase::AnalogChannel:
655 case data::SignalBase::LogicChannel:
656 case data::SignalBase::DecodeChannel:
658 trace_view->add_decode_signal(
659 dynamic_pointer_cast<data::DecodeSignal>(signalbase));
662 case data::SignalBase::MathChannel:
672 void Session::deregister_view(shared_ptr<views::ViewBase> view)
674 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
676 if (views_.empty()) {
679 // Without a view there can be no main bar
684 bool Session::has_view(shared_ptr<views::ViewBase> view)
686 for (shared_ptr<views::ViewBase> v : views_)
693 double Session::get_samplerate() const
695 double samplerate = 0.0;
697 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
699 const vector< shared_ptr<pv::data::Segment> > segments =
701 for (const shared_ptr<pv::data::Segment> &s : segments)
702 samplerate = max(samplerate, s->samplerate());
704 // If there is no sample rate given we use samples as unit
705 if (samplerate == 0.0)
711 uint32_t Session::get_segment_count() const
715 // Find the highest number of segments
716 for (shared_ptr<data::SignalData> data : all_signal_data_)
717 if (data->get_segment_count() > value)
718 value = data->get_segment_count();
723 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
725 vector<util::Timestamp> result;
727 for (pair<uint32_t, util::Timestamp> entry : trigger_list_)
728 if (entry.first == segment_id)
729 result.push_back(entry.second);
734 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
739 bool Session::all_segments_complete(uint32_t segment_id) const
741 bool all_complete = true;
743 for (shared_ptr<data::SignalBase> base : signalbases_)
744 if (!base->segment_is_complete(segment_id))
745 all_complete = false;
751 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
753 shared_ptr<data::DecodeSignal> signal;
756 // Create the decode signal
757 signal = make_shared<data::DecodeSignal>(*this);
759 signalbases_.insert(signal);
761 // Add the decode signal to all views
762 for (shared_ptr<views::ViewBase> view : views_)
763 view->add_decode_signal(signal);
764 } catch (runtime_error& e) {
765 remove_decode_signal(signal);
774 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
776 signalbases_.erase(signal);
778 for (shared_ptr<views::ViewBase> view : views_)
779 view->remove_decode_signal(signal);
785 void Session::set_capture_state(capture_state state)
790 lock_guard<mutex> lock(sampling_mutex_);
791 changed = capture_state_ != state;
792 capture_state_ = state;
796 capture_state_changed(state);
799 void Session::update_signals()
802 signalbases_.clear();
804 for (shared_ptr<views::ViewBase> view : views_) {
805 view->clear_signals();
807 view->clear_decode_signals();
813 lock_guard<recursive_mutex> lock(data_mutex_);
815 const shared_ptr<sigrok::Device> sr_dev = device_->device();
817 signalbases_.clear();
819 for (shared_ptr<views::ViewBase> view : views_) {
820 view->clear_signals();
822 view->clear_decode_signals();
828 // Detect what data types we will receive
829 auto channels = sr_dev->channels();
830 unsigned int logic_channel_count = count_if(
831 channels.begin(), channels.end(),
832 [] (shared_ptr<Channel> channel) {
833 return channel->type() == sigrok::ChannelType::LOGIC; });
835 // Create data containers for the logic data segments
837 lock_guard<recursive_mutex> data_lock(data_mutex_);
839 if (logic_channel_count == 0) {
841 } else if (!logic_data_ ||
842 logic_data_->num_channels() != logic_channel_count) {
843 logic_data_.reset(new data::Logic(
844 logic_channel_count));
849 // Make the signals list
850 for (shared_ptr<views::ViewBase> viewbase : views_) {
851 views::trace::View *trace_view =
852 qobject_cast<views::trace::View*>(viewbase.get());
855 unordered_set< shared_ptr<views::trace::Signal> >
856 prev_sigs(trace_view->signals());
857 trace_view->clear_signals();
859 for (auto channel : sr_dev->channels()) {
860 shared_ptr<data::SignalBase> signalbase;
861 shared_ptr<views::trace::Signal> signal;
863 // Find the channel in the old signals
864 const auto iter = find_if(
865 prev_sigs.cbegin(), prev_sigs.cend(),
866 [&](const shared_ptr<views::trace::Signal> &s) {
867 return s->base()->channel() == channel;
869 if (iter != prev_sigs.end()) {
870 // Copy the signal from the old set to the new
872 trace_view->add_signal(signal);
874 // Find the signalbase for this channel if possible
876 for (const shared_ptr<data::SignalBase> b : signalbases_)
877 if (b->channel() == channel)
880 switch(channel->type()->id()) {
881 case SR_CHANNEL_LOGIC:
883 signalbase = make_shared<data::SignalBase>(channel,
884 data::SignalBase::LogicChannel);
885 signalbases_.insert(signalbase);
887 all_signal_data_.insert(logic_data_);
888 signalbase->set_data(logic_data_);
890 connect(this, SIGNAL(capture_state_changed(int)),
891 signalbase.get(), SLOT(on_capture_state_changed(int)));
894 signal = shared_ptr<views::trace::Signal>(
895 new views::trace::LogicSignal(*this,
896 device_, signalbase));
897 trace_view->add_signal(signal);
900 case SR_CHANNEL_ANALOG:
903 signalbase = make_shared<data::SignalBase>(channel,
904 data::SignalBase::AnalogChannel);
905 signalbases_.insert(signalbase);
907 shared_ptr<data::Analog> data(new data::Analog());
908 all_signal_data_.insert(data);
909 signalbase->set_data(data);
911 connect(this, SIGNAL(capture_state_changed(int)),
912 signalbase.get(), SLOT(on_capture_state_changed(int)));
915 signal = shared_ptr<views::trace::Signal>(
916 new views::trace::AnalogSignal(
918 trace_view->add_signal(signal);
934 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
935 shared_ptr<sigrok::Channel> channel) const
937 for (shared_ptr<data::SignalBase> sig : signalbases_) {
939 if (sig->channel() == channel)
942 return shared_ptr<data::SignalBase>();
945 void Session::sample_thread_proc(function<void (const QString)> error_handler)
947 assert(error_handler);
952 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
954 out_of_memory_ = false;
957 lock_guard<recursive_mutex> lock(data_mutex_);
958 cur_logic_segment_.reset();
959 cur_analog_segments_.clear();
961 highest_segment_id_ = -1;
962 frame_began_ = false;
967 error_handler(e.what());
971 set_capture_state(device_->session()->trigger() ?
972 AwaitingTrigger : Running);
977 error_handler(e.what());
978 set_capture_state(Stopped);
982 set_capture_state(Stopped);
984 // Confirm that SR_DF_END was received
985 if (cur_logic_segment_)
986 qDebug() << "WARNING: SR_DF_END was not received.";
988 // Optimize memory usage
989 free_unused_memory();
991 // We now have unsaved data unless we just "captured" from a file
992 shared_ptr<devices::File> file_device =
993 dynamic_pointer_cast<devices::File>(device_);
999 error_handler(tr("Out of memory, acquisition stopped."));
1002 void Session::free_unused_memory()
1004 for (shared_ptr<data::SignalData> data : all_signal_data_) {
1005 const vector< shared_ptr<data::Segment> > segments = data->segments();
1007 for (shared_ptr<data::Segment> segment : segments) {
1008 segment->free_unused_memory();
1013 void Session::signal_new_segment()
1015 int new_segment_id = 0;
1017 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1019 // Determine new frame/segment number, assuming that all
1020 // signals have the same number of frames/segments
1021 if (cur_logic_segment_) {
1022 new_segment_id = logic_data_->get_segment_count() - 1;
1024 shared_ptr<sigrok::Channel> any_channel =
1025 (*cur_analog_segments_.begin()).first;
1027 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1030 shared_ptr<data::Analog> data(base->analog_data());
1033 new_segment_id = data->get_segment_count() - 1;
1037 if (new_segment_id > highest_segment_id_) {
1038 highest_segment_id_ = new_segment_id;
1039 new_segment(highest_segment_id_);
1043 void Session::signal_segment_completed()
1047 for (shared_ptr<data::SignalBase> signalbase : signalbases_) {
1048 // We only care about analog and logic channels, not derived ones
1049 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1050 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1054 if (signalbase->type() == data::SignalBase::LogicChannel) {
1055 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1060 if (segment_id >= 0)
1061 segment_completed(segment_id);
1064 void Session::feed_in_header()
1066 // Nothing to do here for now
1069 void Session::feed_in_meta(shared_ptr<Meta> meta)
1071 for (auto entry : meta->config()) {
1072 switch (entry.first->id()) {
1073 case SR_CONF_SAMPLERATE:
1074 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1077 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1085 void Session::feed_in_trigger()
1087 // The channel containing most samples should be most accurate
1088 uint64_t sample_count = 0;
1091 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
1093 uint64_t temp_count = 0;
1095 const vector< shared_ptr<pv::data::Segment> > segments =
1097 for (const shared_ptr<pv::data::Segment> &s : segments)
1098 temp_count += s->get_sample_count();
1100 if (temp_count > sample_count)
1101 sample_count = temp_count;
1105 uint32_t segment_id = 0; // Default segment when no frames are used
1107 // If a frame began, we'd ideally be able to use the highest segment ID for
1108 // the trigger. However, as new segments are only created when logic or
1109 // analog data comes in, this doesn't work if the trigger appears right
1110 // after the beginning of the frame, before any sample data.
1111 // For this reason, we use highest segment ID + 1 if no sample data came in
1112 // yet and the highest segment ID otherwise.
1114 segment_id = highest_segment_id_;
1115 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1119 // TODO Create timestamp from segment start time + segment's current sample count
1120 util::Timestamp timestamp = sample_count / get_samplerate();
1121 trigger_list_.emplace_back(segment_id, timestamp);
1122 trigger_event(segment_id, timestamp);
1125 void Session::feed_in_frame_begin()
1127 frame_began_ = true;
1130 void Session::feed_in_frame_end()
1136 lock_guard<recursive_mutex> lock(data_mutex_);
1138 if (cur_logic_segment_)
1139 cur_logic_segment_->set_complete();
1141 for (auto entry : cur_analog_segments_) {
1142 shared_ptr<data::AnalogSegment> segment = entry.second;
1143 segment->set_complete();
1146 cur_logic_segment_.reset();
1147 cur_analog_segments_.clear();
1150 frame_began_ = false;
1152 signal_segment_completed();
1155 void Session::feed_in_logic(shared_ptr<Logic> logic)
1157 if (logic->data_length() == 0) {
1158 qDebug() << "WARNING: Received logic packet with 0 samples.";
1162 if (!cur_samplerate_)
1163 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1165 lock_guard<recursive_mutex> lock(data_mutex_);
1168 // The only reason logic_data_ would not have been created is
1169 // if it was not possible to determine the signals when the
1170 // device was created.
1174 if (!cur_logic_segment_) {
1175 // This could be the first packet after a trigger
1176 set_capture_state(Running);
1178 // Create a new data segment
1179 cur_logic_segment_ = make_shared<data::LogicSegment>(
1180 *logic_data_, logic_data_->get_segment_count(),
1181 logic->unit_size(), cur_samplerate_);
1182 logic_data_->push_segment(cur_logic_segment_);
1184 signal_new_segment();
1187 cur_logic_segment_->append_payload(logic);
1192 void Session::feed_in_analog(shared_ptr<Analog> analog)
1194 if (analog->num_samples() == 0) {
1195 qDebug() << "WARNING: Received analog packet with 0 samples.";
1199 if (!cur_samplerate_)
1200 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1202 lock_guard<recursive_mutex> lock(data_mutex_);
1204 const vector<shared_ptr<Channel>> channels = analog->channels();
1205 const unsigned int channel_count = channels.size();
1206 const size_t sample_count = analog->num_samples() / channel_count;
1207 bool sweep_beginning = false;
1209 unique_ptr<float[]> data(new float[analog->num_samples()]);
1210 analog->get_data_as_float(data.get());
1212 if (signalbases_.empty())
1215 float *channel_data = data.get();
1216 for (auto channel : channels) {
1217 shared_ptr<data::AnalogSegment> segment;
1219 // Try to get the segment of the channel
1220 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1221 iterator iter = cur_analog_segments_.find(channel);
1222 if (iter != cur_analog_segments_.end())
1223 segment = (*iter).second;
1225 // If no segment was found, this means we haven't
1226 // created one yet. i.e. this is the first packet
1227 // in the sweep containing this segment.
1228 sweep_beginning = true;
1230 // Find the analog data associated with the channel
1231 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1234 shared_ptr<data::Analog> data(base->analog_data());
1237 // Create a segment, keep it in the maps of channels
1238 segment = make_shared<data::AnalogSegment>(
1239 *data, data->get_segment_count(), cur_samplerate_);
1240 cur_analog_segments_[channel] = segment;
1242 // Push the segment into the analog data.
1243 data->push_segment(segment);
1245 signal_new_segment();
1250 // Append the samples in the segment
1251 segment->append_interleaved_samples(channel_data++, sample_count,
1255 if (sweep_beginning) {
1256 // This could be the first packet after a trigger
1257 set_capture_state(Running);
1263 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1264 shared_ptr<Packet> packet)
1269 assert(device == device_->device());
1272 switch (packet->type()->id()) {
1278 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1287 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1288 } catch (bad_alloc&) {
1289 out_of_memory_ = true;
1296 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1297 } catch (bad_alloc&) {
1298 out_of_memory_ = true;
1303 case SR_DF_FRAME_BEGIN:
1304 feed_in_frame_begin();
1307 case SR_DF_FRAME_END:
1308 feed_in_frame_end();
1312 // Strictly speaking, this is performed when a frame end marker was
1313 // received, so there's no point doing this again. However, not all
1314 // devices use frames, and for those devices, we need to do it here.
1316 lock_guard<recursive_mutex> lock(data_mutex_);
1318 if (cur_logic_segment_)
1319 cur_logic_segment_->set_complete();
1321 for (auto entry : cur_analog_segments_) {
1322 shared_ptr<data::AnalogSegment> segment = entry.second;
1323 segment->set_complete();
1326 cur_logic_segment_.reset();
1327 cur_analog_segments_.clear();
1336 void Session::on_data_saved()