desktop file: Add additional Development category.
[pulseview.git] / pv / session.cpp
blobeec1a051b5a8838ba3f81b58c0759adbadb024a9
1 /*
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/>.
20 #include <QFileInfo>
22 #include <cassert>
23 #include <memory>
24 #include <mutex>
25 #include <stdexcept>
27 #include <sys/stat.h>
29 #include "devicemanager.hpp"
30 #include "session.hpp"
32 #include "data/analog.hpp"
33 #include "data/analogsegment.hpp"
34 #include "data/decode/decoder.hpp"
35 #include "data/decoderstack.hpp"
36 #include "data/logic.hpp"
37 #include "data/logicsegment.hpp"
38 #include "data/signalbase.hpp"
40 #include "devices/hardwaredevice.hpp"
41 #include "devices/inputfile.hpp"
42 #include "devices/sessionfile.hpp"
44 #include "toolbars/mainbar.hpp"
46 #include "view/analogsignal.hpp"
47 #include "view/decodetrace.hpp"
48 #include "view/logicsignal.hpp"
49 #include "view/signal.hpp"
50 #include "view/view.hpp"
52 #include <libsigrokcxx/libsigrokcxx.hpp>
54 #ifdef ENABLE_DECODE
55 #include <libsigrokdecode/libsigrokdecode.h>
56 #endif
58 using std::bad_alloc;
59 using std::dynamic_pointer_cast;
60 using std::find_if;
61 using std::function;
62 using std::lock_guard;
63 using std::list;
64 using std::make_pair;
65 using std::make_shared;
66 using std::map;
67 using std::max;
68 using std::move;
69 using std::mutex;
70 using std::pair;
71 using std::recursive_mutex;
72 using std::runtime_error;
73 using std::shared_ptr;
74 using std::string;
75 using std::unique_ptr;
76 using std::unordered_set;
77 using std::vector;
79 using sigrok::Analog;
80 using sigrok::Channel;
81 using sigrok::ConfigKey;
82 using sigrok::DatafeedCallbackFunction;
83 using sigrok::Error;
84 using sigrok::InputFormat;
85 using sigrok::Logic;
86 using sigrok::Meta;
87 using sigrok::Packet;
88 using sigrok::Session;
90 using Glib::VariantBase;
92 namespace pv {
93 Session::Session(DeviceManager &device_manager, QString name) :
94 device_manager_(device_manager),
95 default_name_(name),
96 name_(name),
97 capture_state_(Stopped),
98 cur_samplerate_(0),
99 data_saved_(true)
103 Session::~Session()
105 // Stop and join to the thread
106 stop_capture();
109 DeviceManager& Session::device_manager()
111 return device_manager_;
114 const DeviceManager& Session::device_manager() const
116 return device_manager_;
119 shared_ptr<sigrok::Session> Session::session() const
121 if (!device_)
122 return shared_ptr<sigrok::Session>();
123 return device_->session();
126 shared_ptr<devices::Device> Session::device() const
128 return device_;
131 QString Session::name() const
133 return name_;
136 void Session::set_name(QString name)
138 if (default_name_.isEmpty())
139 default_name_ = name;
141 name_ = name;
143 name_changed();
146 const list< shared_ptr<views::ViewBase> > Session::views() const
148 return views_;
151 shared_ptr<views::ViewBase> Session::main_view() const
153 return main_view_;
156 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
158 main_bar_ = main_bar;
161 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
163 return main_bar_;
166 bool Session::data_saved() const
168 return data_saved_;
171 void Session::save_settings(QSettings &settings) const
173 map<string, string> dev_info;
174 list<string> key_list;
175 int stacks = 0, views = 0;
177 if (device_) {
178 shared_ptr<devices::HardwareDevice> hw_device =
179 dynamic_pointer_cast< devices::HardwareDevice >(device_);
181 if (hw_device) {
182 settings.setValue("device_type", "hardware");
183 settings.beginGroup("device");
185 key_list.emplace_back("vendor");
186 key_list.emplace_back("model");
187 key_list.emplace_back("version");
188 key_list.emplace_back("serial_num");
189 key_list.emplace_back("connection_id");
191 dev_info = device_manager_.get_device_info(device_);
193 for (string key : key_list) {
194 if (dev_info.count(key))
195 settings.setValue(QString::fromUtf8(key.c_str()),
196 QString::fromUtf8(dev_info.at(key).c_str()));
197 else
198 settings.remove(QString::fromUtf8(key.c_str()));
201 settings.endGroup();
204 shared_ptr<devices::SessionFile> sessionfile_device =
205 dynamic_pointer_cast< devices::SessionFile >(device_);
207 if (sessionfile_device) {
208 settings.setValue("device_type", "sessionfile");
209 settings.beginGroup("device");
210 settings.setValue("filename", QString::fromStdString(
211 sessionfile_device->full_name()));
212 settings.endGroup();
215 // Save channels and decoders
216 for (shared_ptr<data::SignalBase> base : signalbases_) {
217 #ifdef ENABLE_DECODE
218 if (base->is_decode_signal()) {
219 shared_ptr<pv::data::DecoderStack> decoder_stack =
220 base->decoder_stack();
221 shared_ptr<data::decode::Decoder> top_decoder =
222 decoder_stack->stack().front();
224 settings.beginGroup("decoder_stack" + QString::number(stacks++));
225 settings.setValue("id", top_decoder->decoder()->id);
226 settings.setValue("name", top_decoder->decoder()->name);
227 settings.endGroup();
228 } else
229 #endif
231 settings.beginGroup(base->internal_name());
232 base->save_settings(settings);
233 settings.endGroup();
237 settings.setValue("decoder_stacks", stacks);
239 // Save view states and their signal settings
240 // Note: main_view must be saved as view0
241 settings.beginGroup("view" + QString::number(views++));
242 main_view_->save_settings(settings);
243 settings.endGroup();
245 for (shared_ptr<views::ViewBase> view : views_) {
246 if (view != main_view_) {
247 settings.beginGroup("view" + QString::number(views++));
248 view->save_settings(settings);
249 settings.endGroup();
253 settings.setValue("views", views);
257 void Session::restore_settings(QSettings &settings)
259 shared_ptr<devices::Device> device;
261 QString device_type = settings.value("device_type").toString();
263 if (device_type == "hardware") {
264 map<string, string> dev_info;
265 list<string> key_list;
267 // Re-select last used device if possible but only if it's not demo
268 settings.beginGroup("device");
269 key_list.emplace_back("vendor");
270 key_list.emplace_back("model");
271 key_list.emplace_back("version");
272 key_list.emplace_back("serial_num");
273 key_list.emplace_back("connection_id");
275 for (string key : key_list) {
276 const QString k = QString::fromStdString(key);
277 if (!settings.contains(k))
278 continue;
280 const string value = settings.value(k).toString().toStdString();
281 if (!value.empty())
282 dev_info.insert(make_pair(key, value));
285 if (dev_info.count("model") > 0)
286 device = device_manager_.find_device_from_info(dev_info);
288 if (device)
289 set_device(device);
291 settings.endGroup();
294 if (device_type == "sessionfile") {
295 settings.beginGroup("device");
296 QString filename = settings.value("filename").toString();
297 settings.endGroup();
299 if (QFileInfo(filename).isReadable()) {
300 device = make_shared<devices::SessionFile>(device_manager_.context(),
301 filename.toStdString());
302 set_device(device);
304 // TODO Perform error handling
305 start_capture([](QString infoMessage) { (void)infoMessage; });
307 set_name(QFileInfo(filename).fileName());
311 if (device) {
312 // Restore channels
313 for (shared_ptr<data::SignalBase> base : signalbases_) {
314 settings.beginGroup(base->internal_name());
315 base->restore_settings(settings);
316 settings.endGroup();
319 // Restore decoders
320 #ifdef ENABLE_DECODE
321 int stacks = settings.value("decoder_stacks").toInt();
323 for (int i = 0; i < stacks; i++) {
324 settings.beginGroup("decoder_stack" + QString::number(i++));
326 QString id = settings.value("id").toString();
327 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
329 settings.endGroup();
331 #endif
333 // Restore views
334 int views = settings.value("views").toInt();
336 for (int i = 0; i < views; i++) {
337 settings.beginGroup("view" + QString::number(i));
339 if (i > 0) {
340 views::ViewType type = (views::ViewType)settings.value("type").toInt();
341 add_view(name_, type, this);
342 views_.back()->restore_settings(settings);
343 } else
344 main_view_->restore_settings(settings);
346 settings.endGroup();
351 void Session::select_device(shared_ptr<devices::Device> device)
353 try {
354 if (device)
355 set_device(device);
356 else
357 set_default_device();
358 } catch (const QString &e) {
359 main_bar_->session_error(tr("Failed to Select Device"),
360 tr("Failed to Select Device"));
364 void Session::set_device(shared_ptr<devices::Device> device)
366 assert(device);
368 // Ensure we are not capturing before setting the device
369 stop_capture();
371 if (device_)
372 device_->close();
374 device_.reset();
376 // Revert name back to default name (e.g. "Session 1") as the data is gone
377 name_ = default_name_;
378 name_changed();
380 // Remove all stored data
381 for (shared_ptr<views::ViewBase> view : views_) {
382 view->clear_signals();
383 #ifdef ENABLE_DECODE
384 view->clear_decode_signals();
385 #endif
387 for (const shared_ptr<data::SignalData> d : all_signal_data_)
388 d->clear();
389 all_signal_data_.clear();
390 signalbases_.clear();
391 cur_logic_segment_.reset();
393 for (auto entry : cur_analog_segments_) {
394 shared_ptr<sigrok::Channel>(entry.first).reset();
395 shared_ptr<data::AnalogSegment>(entry.second).reset();
398 logic_data_.reset();
400 signals_changed();
402 device_ = move(device);
404 try {
405 device_->open();
406 } catch (const QString &e) {
407 device_.reset();
410 if (device_) {
411 device_->session()->add_datafeed_callback([=]
412 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
413 data_feed_in(device, packet);
416 update_signals();
419 device_changed();
422 void Session::set_default_device()
424 const list< shared_ptr<devices::HardwareDevice> > &devices =
425 device_manager_.devices();
427 if (devices.empty())
428 return;
430 // Try and find the demo device and select that by default
431 const auto iter = find_if(devices.begin(), devices.end(),
432 [] (const shared_ptr<devices::HardwareDevice> &d) {
433 return d->hardware_device()->driver()->name() == "demo"; });
434 set_device((iter == devices.end()) ? devices.front() : *iter);
437 void Session::load_init_file(const string &file_name, const string &format)
439 shared_ptr<InputFormat> input_format;
441 if (!format.empty()) {
442 const map<string, shared_ptr<InputFormat> > formats =
443 device_manager_.context()->input_formats();
444 const auto iter = find_if(formats.begin(), formats.end(),
445 [&](const pair<string, shared_ptr<InputFormat> > f) {
446 return f.first == format; });
447 if (iter == formats.end()) {
448 main_bar_->session_error(tr("Error"),
449 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
450 return;
453 input_format = (*iter).second;
456 load_file(QString::fromStdString(file_name), input_format);
459 void Session::load_file(QString file_name,
460 shared_ptr<sigrok::InputFormat> format,
461 const map<string, Glib::VariantBase> &options)
463 const QString errorMessage(
464 QString("Failed to load file %1").arg(file_name));
466 try {
467 if (format)
468 set_device(shared_ptr<devices::Device>(
469 new devices::InputFile(
470 device_manager_.context(),
471 file_name.toStdString(),
472 format, options)));
473 else
474 set_device(shared_ptr<devices::Device>(
475 new devices::SessionFile(
476 device_manager_.context(),
477 file_name.toStdString())));
478 } catch (Error e) {
479 main_bar_->session_error(tr("Failed to load ") + file_name, e.what());
480 set_default_device();
481 main_bar_->update_device_list();
482 return;
485 main_bar_->update_device_list();
487 start_capture([&, errorMessage](QString infoMessage) {
488 main_bar_->session_error(errorMessage, infoMessage); });
490 set_name(QFileInfo(file_name).fileName());
493 Session::capture_state Session::get_capture_state() const
495 lock_guard<mutex> lock(sampling_mutex_);
496 return capture_state_;
499 void Session::start_capture(function<void (const QString)> error_handler)
501 if (!device_) {
502 error_handler(tr("No active device set, can't start acquisition."));
503 return;
506 stop_capture();
508 // Check that at least one channel is enabled
509 const shared_ptr<sigrok::Device> sr_dev = device_->device();
510 if (sr_dev) {
511 const auto channels = sr_dev->channels();
512 if (!any_of(channels.begin(), channels.end(),
513 [](shared_ptr<Channel> channel) {
514 return channel->enabled(); })) {
515 error_handler(tr("No channels enabled."));
516 return;
520 // Clear signal data
521 for (const shared_ptr<data::SignalData> d : all_signal_data_)
522 d->clear();
524 // Revert name back to default name (e.g. "Session 1") for real devices
525 // as the (possibly saved) data is gone. File devices keep their name.
526 shared_ptr<devices::HardwareDevice> hw_device =
527 dynamic_pointer_cast< devices::HardwareDevice >(device_);
529 if (hw_device) {
530 name_ = default_name_;
531 name_changed();
534 // Begin the session
535 sampling_thread_ = std::thread(
536 &Session::sample_thread_proc, this, error_handler);
539 void Session::stop_capture()
541 if (get_capture_state() != Stopped)
542 device_->stop();
544 // Check that sampling stopped
545 if (sampling_thread_.joinable())
546 sampling_thread_.join();
549 void Session::register_view(shared_ptr<views::ViewBase> view)
551 if (views_.empty()) {
552 main_view_ = view;
555 views_.push_back(view);
557 update_signals();
560 void Session::deregister_view(shared_ptr<views::ViewBase> view)
562 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
564 if (views_.empty()) {
565 main_view_.reset();
567 // Without a view there can be no main bar
568 main_bar_.reset();
572 bool Session::has_view(shared_ptr<views::ViewBase> view)
574 for (shared_ptr<views::ViewBase> v : views_)
575 if (v == view)
576 return true;
578 return false;
581 double Session::get_samplerate() const
583 double samplerate = 0.0;
585 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
586 assert(d);
587 const vector< shared_ptr<pv::data::Segment> > segments =
588 d->segments();
589 for (const shared_ptr<pv::data::Segment> &s : segments)
590 samplerate = max(samplerate, s->samplerate());
592 // If there is no sample rate given we use samples as unit
593 if (samplerate == 0.0)
594 samplerate = 1.0;
596 return samplerate;
599 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
601 return signalbases_;
604 #ifdef ENABLE_DECODE
605 bool Session::add_decoder(srd_decoder *const dec)
607 if (!dec)
608 return false;
610 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
611 shared_ptr<data::DecoderStack> decoder_stack;
613 try {
614 // Create the decoder
615 decoder_stack = make_shared<data::DecoderStack>(*this, dec);
617 // Make a list of all the channels
618 vector<const srd_channel*> all_channels;
619 for (const GSList *i = dec->channels; i; i = i->next)
620 all_channels.push_back((const srd_channel*)i->data);
621 for (const GSList *i = dec->opt_channels; i; i = i->next)
622 all_channels.push_back((const srd_channel*)i->data);
624 // Auto select the initial channels
625 for (const srd_channel *pdch : all_channels)
626 for (shared_ptr<data::SignalBase> b : signalbases_) {
627 if (b->logic_data()) {
628 if (QString::fromUtf8(pdch->name).toLower().
629 contains(b->name().toLower()))
630 channels[pdch] = b;
634 assert(decoder_stack);
635 assert(!decoder_stack->stack().empty());
636 assert(decoder_stack->stack().front());
637 decoder_stack->stack().front()->set_channels(channels);
639 // Create the decode signal
640 shared_ptr<data::SignalBase> signalbase =
641 make_shared<data::SignalBase>(nullptr, data::SignalBase::DecodeChannel);
643 signalbase->set_decoder_stack(decoder_stack);
644 signalbases_.insert(signalbase);
646 for (shared_ptr<views::ViewBase> view : views_)
647 view->add_decode_signal(signalbase);
648 } catch (runtime_error e) {
649 return false;
652 signals_changed();
654 // Do an initial decode
655 decoder_stack->begin_decode();
657 return true;
660 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
662 signalbases_.erase(signalbase);
664 for (shared_ptr<views::ViewBase> view : views_)
665 view->remove_decode_signal(signalbase);
667 signals_changed();
669 #endif
671 void Session::set_capture_state(capture_state state)
673 bool changed;
676 lock_guard<mutex> lock(sampling_mutex_);
677 changed = capture_state_ != state;
678 capture_state_ = state;
681 if (changed)
682 capture_state_changed(state);
685 void Session::update_signals()
687 if (!device_) {
688 signalbases_.clear();
689 logic_data_.reset();
690 for (shared_ptr<views::ViewBase> view : views_) {
691 view->clear_signals();
692 #ifdef ENABLE_DECODE
693 view->clear_decode_signals();
694 #endif
696 return;
699 lock_guard<recursive_mutex> lock(data_mutex_);
701 const shared_ptr<sigrok::Device> sr_dev = device_->device();
702 if (!sr_dev) {
703 signalbases_.clear();
704 logic_data_.reset();
705 for (shared_ptr<views::ViewBase> view : views_) {
706 view->clear_signals();
707 #ifdef ENABLE_DECODE
708 view->clear_decode_signals();
709 #endif
711 return;
714 // Detect what data types we will receive
715 auto channels = sr_dev->channels();
716 unsigned int logic_channel_count = count_if(
717 channels.begin(), channels.end(),
718 [] (shared_ptr<Channel> channel) {
719 return channel->type() == sigrok::ChannelType::LOGIC; });
721 // Create data containers for the logic data segments
723 lock_guard<recursive_mutex> data_lock(data_mutex_);
725 if (logic_channel_count == 0) {
726 logic_data_.reset();
727 } else if (!logic_data_ ||
728 logic_data_->num_channels() != logic_channel_count) {
729 logic_data_.reset(new data::Logic(
730 logic_channel_count));
731 assert(logic_data_);
735 // Make the signals list
736 for (shared_ptr<views::ViewBase> viewbase : views_) {
737 views::TraceView::View *trace_view =
738 qobject_cast<views::TraceView::View*>(viewbase.get());
740 if (trace_view) {
741 unordered_set< shared_ptr<views::TraceView::Signal> >
742 prev_sigs(trace_view->signals());
743 trace_view->clear_signals();
745 for (auto channel : sr_dev->channels()) {
746 shared_ptr<data::SignalBase> signalbase;
747 shared_ptr<views::TraceView::Signal> signal;
749 // Find the channel in the old signals
750 const auto iter = find_if(
751 prev_sigs.cbegin(), prev_sigs.cend(),
752 [&](const shared_ptr<views::TraceView::Signal> &s) {
753 return s->base()->channel() == channel;
755 if (iter != prev_sigs.end()) {
756 // Copy the signal from the old set to the new
757 signal = *iter;
758 trace_view->add_signal(signal);
759 } else {
760 // Find the signalbase for this channel if possible
761 signalbase.reset();
762 for (const shared_ptr<data::SignalBase> b : signalbases_)
763 if (b->channel() == channel)
764 signalbase = b;
766 switch(channel->type()->id()) {
767 case SR_CHANNEL_LOGIC:
768 if (!signalbase) {
769 signalbase = make_shared<data::SignalBase>(channel,
770 data::SignalBase::LogicChannel);
771 signalbases_.insert(signalbase);
773 all_signal_data_.insert(logic_data_);
774 signalbase->set_data(logic_data_);
776 connect(this, SIGNAL(capture_state_changed(int)),
777 signalbase.get(), SLOT(on_capture_state_changed(int)));
780 signal = shared_ptr<views::TraceView::Signal>(
781 new views::TraceView::LogicSignal(*this,
782 device_, signalbase));
783 trace_view->add_signal(signal);
784 break;
786 case SR_CHANNEL_ANALOG:
788 if (!signalbase) {
789 signalbase = make_shared<data::SignalBase>(channel,
790 data::SignalBase::AnalogChannel);
791 signalbases_.insert(signalbase);
793 shared_ptr<data::Analog> data(new data::Analog());
794 all_signal_data_.insert(data);
795 signalbase->set_data(data);
797 connect(this, SIGNAL(capture_state_changed(int)),
798 signalbase.get(), SLOT(on_capture_state_changed(int)));
801 signal = shared_ptr<views::TraceView::Signal>(
802 new views::TraceView::AnalogSignal(
803 *this, signalbase));
804 trace_view->add_signal(signal);
805 break;
808 default:
809 assert(false);
810 break;
817 signals_changed();
820 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
821 shared_ptr<sigrok::Channel> channel) const
823 for (shared_ptr<data::SignalBase> sig : signalbases_) {
824 assert(sig);
825 if (sig->channel() == channel)
826 return sig;
828 return shared_ptr<data::SignalBase>();
831 void Session::sample_thread_proc(function<void (const QString)> error_handler)
833 assert(error_handler);
835 if (!device_)
836 return;
838 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
840 out_of_memory_ = false;
842 try {
843 device_->start();
844 } catch (Error e) {
845 error_handler(e.what());
846 return;
849 set_capture_state(device_->session()->trigger() ?
850 AwaitingTrigger : Running);
852 device_->run();
853 set_capture_state(Stopped);
855 // Confirm that SR_DF_END was received
856 if (cur_logic_segment_) {
857 qDebug("SR_DF_END was not received.");
858 assert(false);
861 // Optimize memory usage
862 free_unused_memory();
864 // We now have unsaved data unless we just "captured" from a file
865 shared_ptr<devices::File> file_device =
866 dynamic_pointer_cast<devices::File>(device_);
868 if (!file_device)
869 data_saved_ = false;
871 if (out_of_memory_)
872 error_handler(tr("Out of memory, acquisition stopped."));
875 void Session::free_unused_memory()
877 for (shared_ptr<data::SignalData> data : all_signal_data_) {
878 const vector< shared_ptr<data::Segment> > segments = data->segments();
880 for (shared_ptr<data::Segment> segment : segments) {
881 segment->free_unused_memory();
886 void Session::feed_in_header()
888 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
891 void Session::feed_in_meta(shared_ptr<Meta> meta)
893 for (auto entry : meta->config()) {
894 switch (entry.first->id()) {
895 case SR_CONF_SAMPLERATE:
896 // We can't rely on the header to always contain the sample rate,
897 // so in case it's supplied via a meta packet, we use it.
898 if (!cur_samplerate_)
899 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
901 /// @todo handle samplerate changes
902 break;
903 default:
904 // Unknown metadata is not an error.
905 break;
909 signals_changed();
912 void Session::feed_in_trigger()
914 // The channel containing most samples should be most accurate
915 uint64_t sample_count = 0;
918 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
919 assert(d);
920 uint64_t temp_count = 0;
922 const vector< shared_ptr<pv::data::Segment> > segments =
923 d->segments();
924 for (const shared_ptr<pv::data::Segment> &s : segments)
925 temp_count += s->get_sample_count();
927 if (temp_count > sample_count)
928 sample_count = temp_count;
932 trigger_event(sample_count / get_samplerate());
935 void Session::feed_in_frame_begin()
937 if (cur_logic_segment_ || !cur_analog_segments_.empty())
938 frame_began();
941 void Session::feed_in_logic(shared_ptr<Logic> logic)
943 lock_guard<recursive_mutex> lock(data_mutex_);
945 if (!logic_data_) {
946 // The only reason logic_data_ would not have been created is
947 // if it was not possible to determine the signals when the
948 // device was created.
949 update_signals();
952 if (!cur_logic_segment_) {
953 // This could be the first packet after a trigger
954 set_capture_state(Running);
956 // Create a new data segment
957 cur_logic_segment_ = make_shared<data::LogicSegment>(
958 *logic_data_, logic->unit_size(), cur_samplerate_);
959 logic_data_->push_segment(cur_logic_segment_);
961 // @todo Putting this here means that only listeners querying
962 // for logic will be notified. Currently the only user of
963 // frame_began is DecoderStack, but in future we need to signal
964 // this after both analog and logic sweeps have begun.
965 frame_began();
968 cur_logic_segment_->append_payload(logic);
970 data_received();
973 void Session::feed_in_analog(shared_ptr<Analog> analog)
975 lock_guard<recursive_mutex> lock(data_mutex_);
977 const vector<shared_ptr<Channel>> channels = analog->channels();
978 const unsigned int channel_count = channels.size();
979 const size_t sample_count = analog->num_samples() / channel_count;
980 bool sweep_beginning = false;
982 unique_ptr<float> data(new float[analog->num_samples()]);
983 analog->get_data_as_float(data.get());
985 if (signalbases_.empty())
986 update_signals();
988 float *channel_data = data.get();
989 for (auto channel : channels) {
990 shared_ptr<data::AnalogSegment> segment;
992 // Try to get the segment of the channel
993 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
994 iterator iter = cur_analog_segments_.find(channel);
995 if (iter != cur_analog_segments_.end())
996 segment = (*iter).second;
997 else {
998 // If no segment was found, this means we haven't
999 // created one yet. i.e. this is the first packet
1000 // in the sweep containing this segment.
1001 sweep_beginning = true;
1003 // Find the analog data associated with the channel
1004 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1005 assert(base);
1007 shared_ptr<data::Analog> data(base->analog_data());
1008 assert(data);
1010 // Create a segment, keep it in the maps of channels
1011 segment = make_shared<data::AnalogSegment>(
1012 *data, cur_samplerate_);
1013 cur_analog_segments_[channel] = segment;
1015 // Push the segment into the analog data.
1016 data->push_segment(segment);
1019 assert(segment);
1021 // Append the samples in the segment
1022 segment->append_interleaved_samples(channel_data++, sample_count,
1023 channel_count);
1026 if (sweep_beginning) {
1027 // This could be the first packet after a trigger
1028 set_capture_state(Running);
1031 data_received();
1034 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1035 shared_ptr<Packet> packet)
1037 static bool frame_began = false;
1039 (void)device;
1041 assert(device);
1042 assert(device == device_->device());
1043 assert(packet);
1045 switch (packet->type()->id()) {
1046 case SR_DF_HEADER:
1047 feed_in_header();
1048 break;
1050 case SR_DF_META:
1051 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1052 break;
1054 case SR_DF_TRIGGER:
1055 feed_in_trigger();
1056 break;
1058 case SR_DF_FRAME_BEGIN:
1059 feed_in_frame_begin();
1060 frame_began = true;
1061 break;
1063 case SR_DF_LOGIC:
1064 try {
1065 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1066 } catch (bad_alloc) {
1067 out_of_memory_ = true;
1068 device_->stop();
1070 break;
1072 case SR_DF_ANALOG:
1073 try {
1074 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1075 } catch (bad_alloc) {
1076 out_of_memory_ = true;
1077 device_->stop();
1079 break;
1081 case SR_DF_FRAME_END:
1082 case SR_DF_END:
1085 lock_guard<recursive_mutex> lock(data_mutex_);
1086 cur_logic_segment_.reset();
1087 cur_analog_segments_.clear();
1089 if (frame_began) {
1090 frame_began = false;
1091 frame_ended();
1093 break;
1095 default:
1096 break;
1100 void Session::on_data_saved()
1102 data_saved_ = true;
1105 } // namespace pv