Remove unused "using" declarations.
[pulseview.git] / pv / session.cpp
blob0fef9c91764bc75366bc8db57cfd6880783465b3
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 #ifdef _WIN32
21 // Windows: Avoid boost/thread namespace pollution (which includes windows.h).
22 #define NOGDI
23 #define NORESOURCE
24 #endif
26 #include <QFileInfo>
28 #include <cassert>
29 #include <mutex>
30 #include <stdexcept>
32 #include <sys/stat.h>
34 #include "session.hpp"
35 #include "devicemanager.hpp"
37 #include "data/analog.hpp"
38 #include "data/analogsegment.hpp"
39 #include "data/decoderstack.hpp"
40 #include "data/logic.hpp"
41 #include "data/logicsegment.hpp"
42 #include "data/signalbase.hpp"
43 #include "data/decode/decoder.hpp"
45 #include "devices/hardwaredevice.hpp"
46 #include "devices/inputfile.hpp"
47 #include "devices/sessionfile.hpp"
49 #include "toolbars/mainbar.hpp"
51 #include "view/analogsignal.hpp"
52 #include "view/decodetrace.hpp"
53 #include "view/logicsignal.hpp"
54 #include "view/signal.hpp"
55 #include "view/view.hpp"
57 #include <libsigrokcxx/libsigrokcxx.hpp>
59 #ifdef ENABLE_DECODE
60 #include <libsigrokdecode/libsigrokdecode.h>
61 #endif
63 using std::bad_alloc;
64 using std::dynamic_pointer_cast;
65 using std::find_if;
66 using std::function;
67 using std::lock_guard;
68 using std::list;
69 using std::make_pair;
70 using std::make_shared;
71 using std::map;
72 using std::max;
73 using std::move;
74 using std::mutex;
75 using std::pair;
76 using std::recursive_mutex;
77 using std::runtime_error;
78 using std::shared_ptr;
79 using std::string;
80 using std::unordered_set;
81 using std::vector;
83 using sigrok::Analog;
84 using sigrok::Channel;
85 using sigrok::ConfigKey;
86 using sigrok::DatafeedCallbackFunction;
87 using sigrok::Error;
88 using sigrok::InputFormat;
89 using sigrok::Logic;
90 using sigrok::Meta;
91 using sigrok::Packet;
92 using sigrok::Session;
94 using Glib::VariantBase;
96 namespace pv {
97 Session::Session(DeviceManager &device_manager, QString name) :
98 device_manager_(device_manager),
99 default_name_(name),
100 name_(name),
101 capture_state_(Stopped),
102 cur_samplerate_(0),
103 data_saved_(true)
107 Session::~Session()
109 // Stop and join to the thread
110 stop_capture();
113 DeviceManager& Session::device_manager()
115 return device_manager_;
118 const DeviceManager& Session::device_manager() const
120 return device_manager_;
123 shared_ptr<sigrok::Session> Session::session() const
125 if (!device_)
126 return shared_ptr<sigrok::Session>();
127 return device_->session();
130 shared_ptr<devices::Device> Session::device() const
132 return device_;
135 QString Session::name() const
137 return name_;
140 void Session::set_name(QString name)
142 if (default_name_.isEmpty())
143 default_name_ = name;
145 name_ = name;
147 name_changed();
150 const list< shared_ptr<views::ViewBase> > Session::views() const
152 return views_;
155 shared_ptr<views::ViewBase> Session::main_view() const
157 return main_view_;
160 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
162 main_bar_ = main_bar;
165 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
167 return main_bar_;
170 bool Session::data_saved() const
172 return data_saved_;
175 void Session::save_settings(QSettings &settings) const
177 map<string, string> dev_info;
178 list<string> key_list;
179 int stacks = 0, views = 0;
181 if (device_) {
182 shared_ptr<devices::HardwareDevice> hw_device =
183 dynamic_pointer_cast< devices::HardwareDevice >(device_);
185 if (hw_device) {
186 settings.setValue("device_type", "hardware");
187 settings.beginGroup("device");
189 key_list.emplace_back("vendor");
190 key_list.emplace_back("model");
191 key_list.emplace_back("version");
192 key_list.emplace_back("serial_num");
193 key_list.emplace_back("connection_id");
195 dev_info = device_manager_.get_device_info(device_);
197 for (string key : key_list) {
198 if (dev_info.count(key))
199 settings.setValue(QString::fromUtf8(key.c_str()),
200 QString::fromUtf8(dev_info.at(key).c_str()));
201 else
202 settings.remove(QString::fromUtf8(key.c_str()));
205 settings.endGroup();
208 shared_ptr<devices::SessionFile> sessionfile_device =
209 dynamic_pointer_cast< devices::SessionFile >(device_);
211 if (sessionfile_device) {
212 settings.setValue("device_type", "sessionfile");
213 settings.beginGroup("device");
214 settings.setValue("filename", QString::fromStdString(
215 sessionfile_device->full_name()));
216 settings.endGroup();
219 // Save channels and decoders
220 for (shared_ptr<data::SignalBase> base : signalbases_) {
221 #ifdef ENABLE_DECODE
222 if (base->is_decode_signal()) {
223 shared_ptr<pv::data::DecoderStack> decoder_stack =
224 base->decoder_stack();
225 shared_ptr<data::decode::Decoder> top_decoder =
226 decoder_stack->stack().front();
228 settings.beginGroup("decoder_stack" + QString::number(stacks++));
229 settings.setValue("id", top_decoder->decoder()->id);
230 settings.setValue("name", top_decoder->decoder()->name);
231 settings.endGroup();
232 } else
233 #endif
235 settings.beginGroup(base->internal_name());
236 base->save_settings(settings);
237 settings.endGroup();
241 settings.setValue("decoder_stacks", stacks);
243 // Save view states and their signal settings
244 // Note: main_view must be saved as view0
245 settings.beginGroup("view" + QString::number(views++));
246 main_view_->save_settings(settings);
247 settings.endGroup();
249 for (shared_ptr<views::ViewBase> view : views_) {
250 if (view != main_view_) {
251 settings.beginGroup("view" + QString::number(views++));
252 view->save_settings(settings);
253 settings.endGroup();
257 settings.setValue("views", views);
261 void Session::restore_settings(QSettings &settings)
263 shared_ptr<devices::Device> device;
265 QString device_type = settings.value("device_type").toString();
267 if (device_type == "hardware") {
268 map<string, string> dev_info;
269 list<string> key_list;
271 // Re-select last used device if possible but only if it's not demo
272 settings.beginGroup("device");
273 key_list.emplace_back("vendor");
274 key_list.emplace_back("model");
275 key_list.emplace_back("version");
276 key_list.emplace_back("serial_num");
277 key_list.emplace_back("connection_id");
279 for (string key : key_list) {
280 const QString k = QString::fromStdString(key);
281 if (!settings.contains(k))
282 continue;
284 const string value = settings.value(k).toString().toStdString();
285 if (!value.empty())
286 dev_info.insert(make_pair(key, value));
289 if (dev_info.count("model") > 0)
290 device = device_manager_.find_device_from_info(dev_info);
292 if (device)
293 set_device(device);
295 settings.endGroup();
298 if (device_type == "sessionfile") {
299 settings.beginGroup("device");
300 QString filename = settings.value("filename").toString();
301 settings.endGroup();
303 if (QFileInfo(filename).isReadable()) {
304 device = make_shared<devices::SessionFile>(device_manager_.context(),
305 filename.toStdString());
306 set_device(device);
308 // TODO Perform error handling
309 start_capture([](QString infoMessage) { (void)infoMessage; });
311 set_name(QFileInfo(filename).fileName());
315 if (device) {
316 // Restore channels
317 for (shared_ptr<data::SignalBase> base : signalbases_) {
318 settings.beginGroup(base->internal_name());
319 base->restore_settings(settings);
320 settings.endGroup();
323 // Restore decoders
324 #ifdef ENABLE_DECODE
325 int stacks = settings.value("decoder_stacks").toInt();
327 for (int i = 0; i < stacks; i++) {
328 settings.beginGroup("decoder_stack" + QString::number(i++));
330 QString id = settings.value("id").toString();
331 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
333 settings.endGroup();
335 #endif
337 // Restore views
338 int views = settings.value("views").toInt();
340 for (int i = 0; i < views; i++) {
341 settings.beginGroup("view" + QString::number(i));
343 if (i > 0) {
344 views::ViewType type = (views::ViewType)settings.value("type").toInt();
345 add_view(name_, type, this);
346 views_.back()->restore_settings(settings);
347 } else
348 main_view_->restore_settings(settings);
350 settings.endGroup();
355 void Session::select_device(shared_ptr<devices::Device> device)
357 try {
358 if (device)
359 set_device(device);
360 else
361 set_default_device();
362 } catch (const QString &e) {
363 main_bar_->session_error(tr("Failed to Select Device"),
364 tr("Failed to Select Device"));
368 void Session::set_device(shared_ptr<devices::Device> device)
370 assert(device);
372 // Ensure we are not capturing before setting the device
373 stop_capture();
375 if (device_)
376 device_->close();
378 device_.reset();
380 // Revert name back to default name (e.g. "Session 1") as the data is gone
381 name_ = default_name_;
382 name_changed();
384 // Remove all stored data
385 for (shared_ptr<views::ViewBase> view : views_) {
386 view->clear_signals();
387 #ifdef ENABLE_DECODE
388 view->clear_decode_signals();
389 #endif
391 for (const shared_ptr<data::SignalData> d : all_signal_data_)
392 d->clear();
393 all_signal_data_.clear();
394 signalbases_.clear();
395 cur_logic_segment_.reset();
397 for (auto entry : cur_analog_segments_) {
398 shared_ptr<sigrok::Channel>(entry.first).reset();
399 shared_ptr<data::AnalogSegment>(entry.second).reset();
402 logic_data_.reset();
404 signals_changed();
406 device_ = move(device);
408 try {
409 device_->open();
410 } catch (const QString &e) {
411 device_.reset();
414 if (device_) {
415 device_->session()->add_datafeed_callback([=]
416 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
417 data_feed_in(device, packet);
420 update_signals();
423 device_changed();
426 void Session::set_default_device()
428 const list< shared_ptr<devices::HardwareDevice> > &devices =
429 device_manager_.devices();
431 if (devices.empty())
432 return;
434 // Try and find the demo device and select that by default
435 const auto iter = find_if(devices.begin(), devices.end(),
436 [] (const shared_ptr<devices::HardwareDevice> &d) {
437 return d->hardware_device()->driver()->name() == "demo"; });
438 set_device((iter == devices.end()) ? devices.front() : *iter);
441 void Session::load_init_file(const string &file_name, const string &format)
443 shared_ptr<InputFormat> input_format;
445 if (!format.empty()) {
446 const map<string, shared_ptr<InputFormat> > formats =
447 device_manager_.context()->input_formats();
448 const auto iter = find_if(formats.begin(), formats.end(),
449 [&](const pair<string, shared_ptr<InputFormat> > f) {
450 return f.first == format; });
451 if (iter == formats.end()) {
452 main_bar_->session_error(tr("Error"),
453 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
454 return;
457 input_format = (*iter).second;
460 load_file(QString::fromStdString(file_name), input_format);
463 void Session::load_file(QString file_name,
464 shared_ptr<sigrok::InputFormat> format,
465 const map<string, Glib::VariantBase> &options)
467 const QString errorMessage(
468 QString("Failed to load file %1").arg(file_name));
470 try {
471 if (format)
472 set_device(shared_ptr<devices::Device>(
473 new devices::InputFile(
474 device_manager_.context(),
475 file_name.toStdString(),
476 format, options)));
477 else
478 set_device(shared_ptr<devices::Device>(
479 new devices::SessionFile(
480 device_manager_.context(),
481 file_name.toStdString())));
482 } catch (Error e) {
483 main_bar_->session_error(tr("Failed to load ") + file_name, e.what());
484 set_default_device();
485 main_bar_->update_device_list();
486 return;
489 main_bar_->update_device_list();
491 start_capture([&, errorMessage](QString infoMessage) {
492 main_bar_->session_error(errorMessage, infoMessage); });
494 set_name(QFileInfo(file_name).fileName());
497 Session::capture_state Session::get_capture_state() const
499 lock_guard<mutex> lock(sampling_mutex_);
500 return capture_state_;
503 void Session::start_capture(function<void (const QString)> error_handler)
505 if (!device_) {
506 error_handler(tr("No active device set, can't start acquisition."));
507 return;
510 stop_capture();
512 // Check that at least one channel is enabled
513 const shared_ptr<sigrok::Device> sr_dev = device_->device();
514 if (sr_dev) {
515 const auto channels = sr_dev->channels();
516 if (!any_of(channels.begin(), channels.end(),
517 [](shared_ptr<Channel> channel) {
518 return channel->enabled(); })) {
519 error_handler(tr("No channels enabled."));
520 return;
524 // Clear signal data
525 for (const shared_ptr<data::SignalData> d : all_signal_data_)
526 d->clear();
528 // Revert name back to default name (e.g. "Session 1") for real devices
529 // as the (possibly saved) data is gone. File devices keep their name.
530 shared_ptr<devices::HardwareDevice> hw_device =
531 dynamic_pointer_cast< devices::HardwareDevice >(device_);
533 if (hw_device) {
534 name_ = default_name_;
535 name_changed();
538 // Begin the session
539 sampling_thread_ = std::thread(
540 &Session::sample_thread_proc, this, error_handler);
543 void Session::stop_capture()
545 if (get_capture_state() != Stopped)
546 device_->stop();
548 // Check that sampling stopped
549 if (sampling_thread_.joinable())
550 sampling_thread_.join();
553 void Session::register_view(shared_ptr<views::ViewBase> view)
555 if (views_.empty()) {
556 main_view_ = view;
559 views_.push_back(view);
561 update_signals();
564 void Session::deregister_view(shared_ptr<views::ViewBase> view)
566 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
568 if (views_.empty()) {
569 main_view_.reset();
571 // Without a view there can be no main bar
572 main_bar_.reset();
576 bool Session::has_view(shared_ptr<views::ViewBase> view)
578 for (shared_ptr<views::ViewBase> v : views_)
579 if (v == view)
580 return true;
582 return false;
585 double Session::get_samplerate() const
587 double samplerate = 0.0;
589 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
590 assert(d);
591 const vector< shared_ptr<pv::data::Segment> > segments =
592 d->segments();
593 for (const shared_ptr<pv::data::Segment> &s : segments)
594 samplerate = max(samplerate, s->samplerate());
596 // If there is no sample rate given we use samples as unit
597 if (samplerate == 0.0)
598 samplerate = 1.0;
600 return samplerate;
603 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
605 return signalbases_;
608 #ifdef ENABLE_DECODE
609 bool Session::add_decoder(srd_decoder *const dec)
611 if (!dec)
612 return false;
614 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
615 shared_ptr<data::DecoderStack> decoder_stack;
617 try {
618 // Create the decoder
619 decoder_stack = make_shared<data::DecoderStack>(*this, dec);
621 // Make a list of all the channels
622 vector<const srd_channel*> all_channels;
623 for (const GSList *i = dec->channels; i; i = i->next)
624 all_channels.push_back((const srd_channel*)i->data);
625 for (const GSList *i = dec->opt_channels; i; i = i->next)
626 all_channels.push_back((const srd_channel*)i->data);
628 // Auto select the initial channels
629 for (const srd_channel *pdch : all_channels)
630 for (shared_ptr<data::SignalBase> b : signalbases_) {
631 if (b->logic_data()) {
632 if (QString::fromUtf8(pdch->name).toLower().
633 contains(b->name().toLower()))
634 channels[pdch] = b;
638 assert(decoder_stack);
639 assert(!decoder_stack->stack().empty());
640 assert(decoder_stack->stack().front());
641 decoder_stack->stack().front()->set_channels(channels);
643 // Create the decode signal
644 shared_ptr<data::SignalBase> signalbase =
645 make_shared<data::SignalBase>(nullptr, data::SignalBase::DecodeChannel);
647 signalbase->set_decoder_stack(decoder_stack);
648 signalbases_.insert(signalbase);
650 for (shared_ptr<views::ViewBase> view : views_)
651 view->add_decode_signal(signalbase);
652 } catch (runtime_error e) {
653 return false;
656 signals_changed();
658 // Do an initial decode
659 decoder_stack->begin_decode();
661 return true;
664 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
666 signalbases_.erase(signalbase);
668 for (shared_ptr<views::ViewBase> view : views_)
669 view->remove_decode_signal(signalbase);
671 signals_changed();
673 #endif
675 void Session::set_capture_state(capture_state state)
677 bool changed;
680 lock_guard<mutex> lock(sampling_mutex_);
681 changed = capture_state_ != state;
682 capture_state_ = state;
685 if (changed)
686 capture_state_changed(state);
689 void Session::update_signals()
691 if (!device_) {
692 signalbases_.clear();
693 logic_data_.reset();
694 for (shared_ptr<views::ViewBase> view : views_) {
695 view->clear_signals();
696 #ifdef ENABLE_DECODE
697 view->clear_decode_signals();
698 #endif
700 return;
703 lock_guard<recursive_mutex> lock(data_mutex_);
705 const shared_ptr<sigrok::Device> sr_dev = device_->device();
706 if (!sr_dev) {
707 signalbases_.clear();
708 logic_data_.reset();
709 for (shared_ptr<views::ViewBase> view : views_) {
710 view->clear_signals();
711 #ifdef ENABLE_DECODE
712 view->clear_decode_signals();
713 #endif
715 return;
718 // Detect what data types we will receive
719 auto channels = sr_dev->channels();
720 unsigned int logic_channel_count = count_if(
721 channels.begin(), channels.end(),
722 [] (shared_ptr<Channel> channel) {
723 return channel->type() == sigrok::ChannelType::LOGIC; });
725 // Create data containers for the logic data segments
727 lock_guard<recursive_mutex> data_lock(data_mutex_);
729 if (logic_channel_count == 0) {
730 logic_data_.reset();
731 } else if (!logic_data_ ||
732 logic_data_->num_channels() != logic_channel_count) {
733 logic_data_.reset(new data::Logic(
734 logic_channel_count));
735 assert(logic_data_);
739 // Make the signals list
740 for (shared_ptr<views::ViewBase> viewbase : views_) {
741 views::TraceView::View *trace_view =
742 qobject_cast<views::TraceView::View*>(viewbase.get());
744 if (trace_view) {
745 unordered_set< shared_ptr<views::TraceView::Signal> >
746 prev_sigs(trace_view->signals());
747 trace_view->clear_signals();
749 for (auto channel : sr_dev->channels()) {
750 shared_ptr<data::SignalBase> signalbase;
751 shared_ptr<views::TraceView::Signal> signal;
753 // Find the channel in the old signals
754 const auto iter = find_if(
755 prev_sigs.cbegin(), prev_sigs.cend(),
756 [&](const shared_ptr<views::TraceView::Signal> &s) {
757 return s->base()->channel() == channel;
759 if (iter != prev_sigs.end()) {
760 // Copy the signal from the old set to the new
761 signal = *iter;
762 trace_view->add_signal(signal);
763 } else {
764 // Find the signalbase for this channel if possible
765 signalbase.reset();
766 for (const shared_ptr<data::SignalBase> b : signalbases_)
767 if (b->channel() == channel)
768 signalbase = b;
770 switch(channel->type()->id()) {
771 case SR_CHANNEL_LOGIC:
772 if (!signalbase) {
773 signalbase = make_shared<data::SignalBase>(channel,
774 data::SignalBase::LogicChannel);
775 signalbases_.insert(signalbase);
777 all_signal_data_.insert(logic_data_);
778 signalbase->set_data(logic_data_);
780 connect(this, SIGNAL(capture_state_changed(int)),
781 signalbase.get(), SLOT(on_capture_state_changed(int)));
784 signal = shared_ptr<views::TraceView::Signal>(
785 new views::TraceView::LogicSignal(*this,
786 device_, signalbase));
787 trace_view->add_signal(signal);
788 break;
790 case SR_CHANNEL_ANALOG:
792 if (!signalbase) {
793 signalbase = make_shared<data::SignalBase>(channel,
794 data::SignalBase::AnalogChannel);
795 signalbases_.insert(signalbase);
797 shared_ptr<data::Analog> data(new data::Analog());
798 all_signal_data_.insert(data);
799 signalbase->set_data(data);
801 connect(this, SIGNAL(capture_state_changed(int)),
802 signalbase.get(), SLOT(on_capture_state_changed(int)));
805 signal = shared_ptr<views::TraceView::Signal>(
806 new views::TraceView::AnalogSignal(
807 *this, signalbase));
808 trace_view->add_signal(signal);
809 break;
812 default:
813 assert(0);
814 break;
821 signals_changed();
824 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
825 shared_ptr<sigrok::Channel> channel) const
827 for (shared_ptr<data::SignalBase> sig : signalbases_) {
828 assert(sig);
829 if (sig->channel() == channel)
830 return sig;
832 return shared_ptr<data::SignalBase>();
835 void Session::sample_thread_proc(function<void (const QString)> error_handler)
837 assert(error_handler);
839 if (!device_)
840 return;
842 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
844 out_of_memory_ = false;
846 try {
847 device_->start();
848 } catch (Error e) {
849 error_handler(e.what());
850 return;
853 set_capture_state(device_->session()->trigger() ?
854 AwaitingTrigger : Running);
856 device_->run();
857 set_capture_state(Stopped);
859 // Confirm that SR_DF_END was received
860 if (cur_logic_segment_) {
861 qDebug("SR_DF_END was not received.");
862 assert(0);
865 // Optimize memory usage
866 free_unused_memory();
868 // We now have unsaved data unless we just "captured" from a file
869 shared_ptr<devices::File> file_device =
870 dynamic_pointer_cast<devices::File>(device_);
872 if (!file_device)
873 data_saved_ = false;
875 if (out_of_memory_)
876 error_handler(tr("Out of memory, acquisition stopped."));
879 void Session::free_unused_memory()
881 for (shared_ptr<data::SignalData> data : all_signal_data_) {
882 const vector< shared_ptr<data::Segment> > segments = data->segments();
884 for (shared_ptr<data::Segment> segment : segments) {
885 segment->free_unused_memory();
890 void Session::feed_in_header()
892 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
895 void Session::feed_in_meta(shared_ptr<Meta> meta)
897 for (auto entry : meta->config()) {
898 switch (entry.first->id()) {
899 case SR_CONF_SAMPLERATE:
900 // We can't rely on the header to always contain the sample rate,
901 // so in case it's supplied via a meta packet, we use it.
902 if (!cur_samplerate_)
903 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
905 /// @todo handle samplerate changes
906 break;
907 default:
908 // Unknown metadata is not an error.
909 break;
913 signals_changed();
916 void Session::feed_in_trigger()
918 // The channel containing most samples should be most accurate
919 uint64_t sample_count = 0;
922 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
923 assert(d);
924 uint64_t temp_count = 0;
926 const vector< shared_ptr<pv::data::Segment> > segments =
927 d->segments();
928 for (const shared_ptr<pv::data::Segment> &s : segments)
929 temp_count += s->get_sample_count();
931 if (temp_count > sample_count)
932 sample_count = temp_count;
936 trigger_event(sample_count / get_samplerate());
939 void Session::feed_in_frame_begin()
941 if (cur_logic_segment_ || !cur_analog_segments_.empty())
942 frame_began();
945 void Session::feed_in_logic(shared_ptr<Logic> logic)
947 lock_guard<recursive_mutex> lock(data_mutex_);
949 if (!logic_data_) {
950 // The only reason logic_data_ would not have been created is
951 // if it was not possible to determine the signals when the
952 // device was created.
953 update_signals();
956 if (!cur_logic_segment_) {
957 // This could be the first packet after a trigger
958 set_capture_state(Running);
960 // Create a new data segment
961 cur_logic_segment_ = make_shared<data::LogicSegment>(
962 *logic_data_, logic->unit_size(), cur_samplerate_);
963 logic_data_->push_segment(cur_logic_segment_);
965 // @todo Putting this here means that only listeners querying
966 // for logic will be notified. Currently the only user of
967 // frame_began is DecoderStack, but in future we need to signal
968 // this after both analog and logic sweeps have begun.
969 frame_began();
972 cur_logic_segment_->append_payload(logic);
974 data_received();
977 void Session::feed_in_analog(shared_ptr<Analog> analog)
979 lock_guard<recursive_mutex> lock(data_mutex_);
981 const vector<shared_ptr<Channel>> channels = analog->channels();
982 const unsigned int channel_count = channels.size();
983 const size_t sample_count = analog->num_samples() / channel_count;
984 const float *data = static_cast<const float *>(analog->data_pointer());
985 bool sweep_beginning = false;
987 if (signalbases_.empty())
988 update_signals();
990 for (auto channel : channels) {
991 shared_ptr<data::AnalogSegment> segment;
993 // Try to get the segment of the channel
994 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
995 iterator iter = cur_analog_segments_.find(channel);
996 if (iter != cur_analog_segments_.end())
997 segment = (*iter).second;
998 else {
999 // If no segment was found, this means we haven't
1000 // created one yet. i.e. this is the first packet
1001 // in the sweep containing this segment.
1002 sweep_beginning = true;
1004 // Find the analog data associated with the channel
1005 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1006 assert(base);
1008 shared_ptr<data::Analog> data(base->analog_data());
1009 assert(data);
1011 // Create a segment, keep it in the maps of channels
1012 segment = make_shared<data::AnalogSegment>(
1013 *data, cur_samplerate_);
1014 cur_analog_segments_[channel] = segment;
1016 // Push the segment into the analog data.
1017 data->push_segment(segment);
1020 assert(segment);
1022 // Append the samples in the segment
1023 segment->append_interleaved_samples(data++, sample_count,
1024 channel_count);
1027 if (sweep_beginning) {
1028 // This could be the first packet after a trigger
1029 set_capture_state(Running);
1032 data_received();
1035 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1036 shared_ptr<Packet> packet)
1038 static bool frame_began=false;
1040 (void)device;
1042 assert(device);
1043 assert(device == device_->device());
1044 assert(packet);
1046 switch (packet->type()->id()) {
1047 case SR_DF_HEADER:
1048 feed_in_header();
1049 break;
1051 case SR_DF_META:
1052 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1053 break;
1055 case SR_DF_TRIGGER:
1056 feed_in_trigger();
1057 break;
1059 case SR_DF_FRAME_BEGIN:
1060 feed_in_frame_begin();
1061 frame_began = true;
1062 break;
1064 case SR_DF_LOGIC:
1065 try {
1066 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1067 } catch (bad_alloc) {
1068 out_of_memory_ = true;
1069 device_->stop();
1071 break;
1073 case SR_DF_ANALOG:
1074 try {
1075 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1076 } catch (bad_alloc) {
1077 out_of_memory_ = true;
1078 device_->stop();
1080 break;
1082 case SR_DF_FRAME_END:
1083 case SR_DF_END:
1086 lock_guard<recursive_mutex> lock(data_mutex_);
1087 cur_logic_segment_.reset();
1088 cur_analog_segments_.clear();
1090 if (frame_began) {
1091 frame_began = false;
1092 frame_ended();
1094 break;
1096 default:
1097 break;
1101 void Session::on_data_saved()
1103 data_saved_ = true;
1106 } // namespace pv