]> sigrok.org Git - pulseview.git/blame_incremental - pv/session.cpp
Session: Break up add_decoder()
[pulseview.git] / pv / session.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
20#include <QDebug>
21#include <QFileInfo>
22
23#include <cassert>
24#include <memory>
25#include <mutex>
26#include <stdexcept>
27
28#include <sys/stat.h>
29
30#include "devicemanager.hpp"
31#include "session.hpp"
32
33#include "data/analog.hpp"
34#include "data/analogsegment.hpp"
35#include "data/decode/decoder.hpp"
36#include "data/logic.hpp"
37#include "data/logicsegment.hpp"
38#include "data/signalbase.hpp"
39
40#include "devices/hardwaredevice.hpp"
41#include "devices/inputfile.hpp"
42#include "devices/sessionfile.hpp"
43
44#include "toolbars/mainbar.hpp"
45
46#include "views/trace/analogsignal.hpp"
47#include "views/trace/decodetrace.hpp"
48#include "views/trace/logicsignal.hpp"
49#include "views/trace/signal.hpp"
50#include "views/trace/view.hpp"
51
52#include <libsigrokcxx/libsigrokcxx.hpp>
53
54#ifdef ENABLE_DECODE
55#include <libsigrokdecode/libsigrokdecode.h>
56#include "data/decodesignal.hpp"
57#endif
58
59using std::bad_alloc;
60using std::dynamic_pointer_cast;
61using std::find_if;
62using std::function;
63using std::lock_guard;
64using std::list;
65using std::make_pair;
66using std::make_shared;
67using std::map;
68using std::max;
69using std::move;
70using std::mutex;
71using std::pair;
72using std::recursive_mutex;
73using std::runtime_error;
74using std::shared_ptr;
75using std::string;
76using std::unique_ptr;
77using std::unordered_set;
78using std::vector;
79
80using sigrok::Analog;
81using sigrok::Channel;
82using sigrok::ConfigKey;
83using sigrok::DatafeedCallbackFunction;
84using sigrok::Error;
85using sigrok::InputFormat;
86using sigrok::Logic;
87using sigrok::Meta;
88using sigrok::Packet;
89using sigrok::Session;
90
91using Glib::VariantBase;
92
93namespace pv {
94Session::Session(DeviceManager &device_manager, QString name) :
95 device_manager_(device_manager),
96 default_name_(name),
97 name_(name),
98 capture_state_(Stopped),
99 cur_samplerate_(0),
100 data_saved_(true)
101{
102}
103
104Session::~Session()
105{
106 // Stop and join to the thread
107 stop_capture();
108}
109
110DeviceManager& Session::device_manager()
111{
112 return device_manager_;
113}
114
115const DeviceManager& Session::device_manager() const
116{
117 return device_manager_;
118}
119
120shared_ptr<sigrok::Session> Session::session() const
121{
122 if (!device_)
123 return shared_ptr<sigrok::Session>();
124 return device_->session();
125}
126
127shared_ptr<devices::Device> Session::device() const
128{
129 return device_;
130}
131
132QString Session::name() const
133{
134 return name_;
135}
136
137void Session::set_name(QString name)
138{
139 if (default_name_.isEmpty())
140 default_name_ = name;
141
142 name_ = name;
143
144 name_changed();
145}
146
147const list< shared_ptr<views::ViewBase> > Session::views() const
148{
149 return views_;
150}
151
152shared_ptr<views::ViewBase> Session::main_view() const
153{
154 return main_view_;
155}
156
157void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
158{
159 main_bar_ = main_bar;
160}
161
162shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
163{
164 return main_bar_;
165}
166
167bool Session::data_saved() const
168{
169 return data_saved_;
170}
171
172void Session::save_settings(QSettings &settings) const
173{
174 map<string, string> dev_info;
175 list<string> key_list;
176 int decode_signals = 0, views = 0;
177
178 if (device_) {
179 shared_ptr<devices::HardwareDevice> hw_device =
180 dynamic_pointer_cast< devices::HardwareDevice >(device_);
181
182 if (hw_device) {
183 settings.setValue("device_type", "hardware");
184 settings.beginGroup("device");
185
186 key_list.emplace_back("vendor");
187 key_list.emplace_back("model");
188 key_list.emplace_back("version");
189 key_list.emplace_back("serial_num");
190 key_list.emplace_back("connection_id");
191
192 dev_info = device_manager_.get_device_info(device_);
193
194 for (string key : key_list) {
195 if (dev_info.count(key))
196 settings.setValue(QString::fromUtf8(key.c_str()),
197 QString::fromUtf8(dev_info.at(key).c_str()));
198 else
199 settings.remove(QString::fromUtf8(key.c_str()));
200 }
201
202 settings.endGroup();
203 }
204
205 shared_ptr<devices::SessionFile> sessionfile_device =
206 dynamic_pointer_cast< devices::SessionFile >(device_);
207
208 if (sessionfile_device) {
209 settings.setValue("device_type", "sessionfile");
210 settings.beginGroup("device");
211 settings.setValue("filename", QString::fromStdString(
212 sessionfile_device->full_name()));
213 settings.endGroup();
214 }
215
216 // Save channels and decoders
217 for (shared_ptr<data::SignalBase> base : signalbases_) {
218#ifdef ENABLE_DECODE
219 if (base->is_decode_signal()) {
220 settings.beginGroup("decode_signal" + QString::number(decode_signals++));
221 base->save_settings(settings);
222 settings.endGroup();
223 } else
224#endif
225 {
226 settings.beginGroup(base->internal_name());
227 base->save_settings(settings);
228 settings.endGroup();
229 }
230 }
231
232 settings.setValue("decode_signals", decode_signals);
233
234 // Save view states and their signal settings
235 // Note: main_view must be saved as view0
236 settings.beginGroup("view" + QString::number(views++));
237 main_view_->save_settings(settings);
238 settings.endGroup();
239
240 for (shared_ptr<views::ViewBase> view : views_) {
241 if (view != main_view_) {
242 settings.beginGroup("view" + QString::number(views++));
243 view->save_settings(settings);
244 settings.endGroup();
245 }
246 }
247
248 settings.setValue("views", views);
249 }
250}
251
252void Session::restore_settings(QSettings &settings)
253{
254 shared_ptr<devices::Device> device;
255
256 QString device_type = settings.value("device_type").toString();
257
258 if (device_type == "hardware") {
259 map<string, string> dev_info;
260 list<string> key_list;
261
262 // Re-select last used device if possible but only if it's not demo
263 settings.beginGroup("device");
264 key_list.emplace_back("vendor");
265 key_list.emplace_back("model");
266 key_list.emplace_back("version");
267 key_list.emplace_back("serial_num");
268 key_list.emplace_back("connection_id");
269
270 for (string key : key_list) {
271 const QString k = QString::fromStdString(key);
272 if (!settings.contains(k))
273 continue;
274
275 const string value = settings.value(k).toString().toStdString();
276 if (!value.empty())
277 dev_info.insert(make_pair(key, value));
278 }
279
280 if (dev_info.count("model") > 0)
281 device = device_manager_.find_device_from_info(dev_info);
282
283 if (device)
284 set_device(device);
285
286 settings.endGroup();
287 }
288
289 if (device_type == "sessionfile") {
290 settings.beginGroup("device");
291 QString filename = settings.value("filename").toString();
292 settings.endGroup();
293
294 if (QFileInfo(filename).isReadable()) {
295 device = make_shared<devices::SessionFile>(device_manager_.context(),
296 filename.toStdString());
297 set_device(device);
298
299 // TODO Perform error handling
300 start_capture([](QString infoMessage) { (void)infoMessage; });
301
302 set_name(QFileInfo(filename).fileName());
303 }
304 }
305
306 if (device) {
307 // Restore channels
308 for (shared_ptr<data::SignalBase> base : signalbases_) {
309 settings.beginGroup(base->internal_name());
310 base->restore_settings(settings);
311 settings.endGroup();
312 }
313
314 // Restore decoders
315#ifdef ENABLE_DECODE
316 int decode_signals = settings.value("decode_signals").toInt();
317
318 for (int i = 0; i < decode_signals; i++) {
319 settings.beginGroup("decode_signal" + QString::number(i++));
320 // TODO Split up add_decoder() into add_decode_signal() and add_decoder(),
321 // then call add_decode_signal() and signal->restore_settings() here
322 settings.endGroup();
323 }
324#endif
325
326 // Restore views
327 int views = settings.value("views").toInt();
328
329 for (int i = 0; i < views; i++) {
330 settings.beginGroup("view" + QString::number(i));
331
332 if (i > 0) {
333 views::ViewType type = (views::ViewType)settings.value("type").toInt();
334 add_view(name_, type, this);
335 views_.back()->restore_settings(settings);
336 } else
337 main_view_->restore_settings(settings);
338
339 settings.endGroup();
340 }
341 }
342}
343
344void Session::select_device(shared_ptr<devices::Device> device)
345{
346 try {
347 if (device)
348 set_device(device);
349 else
350 set_default_device();
351 } catch (const QString &e) {
352 main_bar_->session_error(tr("Failed to Select Device"),
353 tr("Failed to Select Device"));
354 }
355}
356
357void Session::set_device(shared_ptr<devices::Device> device)
358{
359 assert(device);
360
361 // Ensure we are not capturing before setting the device
362 stop_capture();
363
364 if (device_)
365 device_->close();
366
367 device_.reset();
368
369 // Revert name back to default name (e.g. "Session 1") as the data is gone
370 name_ = default_name_;
371 name_changed();
372
373 // Remove all stored data
374 for (shared_ptr<views::ViewBase> view : views_) {
375 view->clear_signals();
376#ifdef ENABLE_DECODE
377 view->clear_decode_signals();
378#endif
379 }
380 for (const shared_ptr<data::SignalData> d : all_signal_data_)
381 d->clear();
382 all_signal_data_.clear();
383 signalbases_.clear();
384 cur_logic_segment_.reset();
385
386 for (auto entry : cur_analog_segments_) {
387 shared_ptr<sigrok::Channel>(entry.first).reset();
388 shared_ptr<data::AnalogSegment>(entry.second).reset();
389 }
390
391 logic_data_.reset();
392
393 signals_changed();
394
395 device_ = move(device);
396
397 try {
398 device_->open();
399 } catch (const QString &e) {
400 device_.reset();
401 }
402
403 if (device_) {
404 device_->session()->add_datafeed_callback([=]
405 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
406 data_feed_in(device, packet);
407 });
408
409 update_signals();
410 }
411
412 device_changed();
413}
414
415void Session::set_default_device()
416{
417 const list< shared_ptr<devices::HardwareDevice> > &devices =
418 device_manager_.devices();
419
420 if (devices.empty())
421 return;
422
423 // Try and find the demo device and select that by default
424 const auto iter = find_if(devices.begin(), devices.end(),
425 [] (const shared_ptr<devices::HardwareDevice> &d) {
426 return d->hardware_device()->driver()->name() == "demo"; });
427 set_device((iter == devices.end()) ? devices.front() : *iter);
428}
429
430/**
431 * Convert generic options to data types that are specific to InputFormat.
432 *
433 * @param[in] user_spec Vector of tokenized words, string format.
434 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
435 *
436 * @return Map of options suitable for InputFormat::create_input().
437 */
438map<string, Glib::VariantBase>
439Session::input_format_options(vector<string> user_spec,
440 map<string, shared_ptr<Option>> fmt_opts)
441{
442 map<string, Glib::VariantBase> result;
443
444 for (auto entry : user_spec) {
445 /*
446 * Split key=value specs. Accept entries without separator
447 * (for simplified boolean specifications).
448 */
449 string key, val;
450 size_t pos = entry.find("=");
451 if (pos == std::string::npos) {
452 key = entry;
453 val = "";
454 } else {
455 key = entry.substr(0, pos);
456 val = entry.substr(pos + 1);
457 }
458
459 /*
460 * Skip user specifications that are not a member of the
461 * format's set of supported options. Have the text input
462 * spec converted to the required input format specific
463 * data type.
464 */
465 auto found = fmt_opts.find(key);
466 if (found == fmt_opts.end())
467 continue;
468 shared_ptr<Option> opt = found->second;
469 result[key] = opt->parse_string(val);
470 }
471
472 return result;
473}
474
475void Session::load_init_file(const string &file_name, const string &format)
476{
477 shared_ptr<InputFormat> input_format;
478 map<string, Glib::VariantBase> input_opts;
479
480 if (!format.empty()) {
481 const map<string, shared_ptr<InputFormat> > formats =
482 device_manager_.context()->input_formats();
483 auto user_opts = pv::util::split_string(format, ":");
484 string user_name = user_opts.front();
485 user_opts.erase(user_opts.begin());
486 const auto iter = find_if(formats.begin(), formats.end(),
487 [&](const pair<string, shared_ptr<InputFormat> > f) {
488 return f.first == user_name; });
489 if (iter == formats.end()) {
490 main_bar_->session_error(tr("Error"),
491 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
492 return;
493 }
494 input_format = (*iter).second;
495 input_opts = input_format_options(user_opts,
496 input_format->options());
497 }
498
499 load_file(QString::fromStdString(file_name), input_format, input_opts);
500}
501
502void Session::load_file(QString file_name,
503 shared_ptr<sigrok::InputFormat> format,
504 const map<string, Glib::VariantBase> &options)
505{
506 const QString errorMessage(
507 QString("Failed to load file %1").arg(file_name));
508
509 try {
510 if (format)
511 set_device(shared_ptr<devices::Device>(
512 new devices::InputFile(
513 device_manager_.context(),
514 file_name.toStdString(),
515 format, options)));
516 else
517 set_device(shared_ptr<devices::Device>(
518 new devices::SessionFile(
519 device_manager_.context(),
520 file_name.toStdString())));
521 } catch (Error e) {
522 main_bar_->session_error(tr("Failed to load ") + file_name, e.what());
523 set_default_device();
524 main_bar_->update_device_list();
525 return;
526 }
527
528 main_bar_->update_device_list();
529
530 start_capture([&, errorMessage](QString infoMessage) {
531 main_bar_->session_error(errorMessage, infoMessage); });
532
533 set_name(QFileInfo(file_name).fileName());
534}
535
536Session::capture_state Session::get_capture_state() const
537{
538 lock_guard<mutex> lock(sampling_mutex_);
539 return capture_state_;
540}
541
542void Session::start_capture(function<void (const QString)> error_handler)
543{
544 if (!device_) {
545 error_handler(tr("No active device set, can't start acquisition."));
546 return;
547 }
548
549 stop_capture();
550
551 // Check that at least one channel is enabled
552 const shared_ptr<sigrok::Device> sr_dev = device_->device();
553 if (sr_dev) {
554 const auto channels = sr_dev->channels();
555 if (!any_of(channels.begin(), channels.end(),
556 [](shared_ptr<Channel> channel) {
557 return channel->enabled(); })) {
558 error_handler(tr("No channels enabled."));
559 return;
560 }
561 }
562
563 // Clear signal data
564 for (const shared_ptr<data::SignalData> d : all_signal_data_)
565 d->clear();
566
567 // Revert name back to default name (e.g. "Session 1") for real devices
568 // as the (possibly saved) data is gone. File devices keep their name.
569 shared_ptr<devices::HardwareDevice> hw_device =
570 dynamic_pointer_cast< devices::HardwareDevice >(device_);
571
572 if (hw_device) {
573 name_ = default_name_;
574 name_changed();
575 }
576
577 // Begin the session
578 sampling_thread_ = std::thread(
579 &Session::sample_thread_proc, this, error_handler);
580}
581
582void Session::stop_capture()
583{
584 if (get_capture_state() != Stopped)
585 device_->stop();
586
587 // Check that sampling stopped
588 if (sampling_thread_.joinable())
589 sampling_thread_.join();
590}
591
592void Session::register_view(shared_ptr<views::ViewBase> view)
593{
594 if (views_.empty()) {
595 main_view_ = view;
596 }
597
598 views_.push_back(view);
599
600 // Add all device signals
601 update_signals();
602
603 // Add all other signals
604 unordered_set< shared_ptr<data::SignalBase> > view_signalbases =
605 view->signalbases();
606
607 views::trace::View *trace_view =
608 qobject_cast<views::trace::View*>(view.get());
609
610 if (trace_view) {
611 for (shared_ptr<data::SignalBase> signalbase : signalbases_) {
612 const int sb_exists = count_if(
613 view_signalbases.cbegin(), view_signalbases.cend(),
614 [&](const shared_ptr<data::SignalBase> &sb) {
615 return sb == signalbase;
616 });
617 // Add the signal to the view as it doesn't have it yet
618 if (!sb_exists)
619 switch (signalbase->type()) {
620 case data::SignalBase::AnalogChannel:
621 case data::SignalBase::LogicChannel:
622 case data::SignalBase::A2LChannel:
623 break;
624 case data::SignalBase::DecodeChannel:
625#ifdef ENABLE_DECODE
626 trace_view->add_decode_signal(
627 dynamic_pointer_cast<data::DecodeSignal>(signalbase));
628#endif
629 break;
630 case data::SignalBase::MathChannel:
631 // TBD
632 break;
633 }
634 }
635 }
636
637 signals_changed();
638}
639
640void Session::deregister_view(shared_ptr<views::ViewBase> view)
641{
642 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
643
644 if (views_.empty()) {
645 main_view_.reset();
646
647 // Without a view there can be no main bar
648 main_bar_.reset();
649 }
650}
651
652bool Session::has_view(shared_ptr<views::ViewBase> view)
653{
654 for (shared_ptr<views::ViewBase> v : views_)
655 if (v == view)
656 return true;
657
658 return false;
659}
660
661double Session::get_samplerate() const
662{
663 double samplerate = 0.0;
664
665 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
666 assert(d);
667 const vector< shared_ptr<pv::data::Segment> > segments =
668 d->segments();
669 for (const shared_ptr<pv::data::Segment> &s : segments)
670 samplerate = max(samplerate, s->samplerate());
671 }
672 // If there is no sample rate given we use samples as unit
673 if (samplerate == 0.0)
674 samplerate = 1.0;
675
676 return samplerate;
677}
678
679const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
680{
681 return signalbases_;
682}
683
684#ifdef ENABLE_DECODE
685shared_ptr<data::DecodeSignal> Session::add_decode_signal()
686{
687 shared_ptr<data::DecodeSignal> signal;
688
689 try {
690 // Create the decode signal
691 signal = make_shared<data::DecodeSignal>(*this);
692
693 signalbases_.insert(signal);
694
695 // Add the decode signal to all views
696 for (shared_ptr<views::ViewBase> view : views_)
697 view->add_decode_signal(signal);
698 } catch (runtime_error e) {
699 remove_decode_signal(signal);
700 return nullptr;
701 }
702
703 signals_changed();
704
705 return signal;
706}
707
708void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
709{
710 signalbases_.erase(signal);
711
712 for (shared_ptr<views::ViewBase> view : views_)
713 view->remove_decode_signal(signal);
714
715 signals_changed();
716}
717#endif
718
719void Session::set_capture_state(capture_state state)
720{
721 bool changed;
722
723 {
724 lock_guard<mutex> lock(sampling_mutex_);
725 changed = capture_state_ != state;
726 capture_state_ = state;
727 }
728
729 if (changed)
730 capture_state_changed(state);
731}
732
733void Session::update_signals()
734{
735 if (!device_) {
736 signalbases_.clear();
737 logic_data_.reset();
738 for (shared_ptr<views::ViewBase> view : views_) {
739 view->clear_signals();
740#ifdef ENABLE_DECODE
741 view->clear_decode_signals();
742#endif
743 }
744 return;
745 }
746
747 lock_guard<recursive_mutex> lock(data_mutex_);
748
749 const shared_ptr<sigrok::Device> sr_dev = device_->device();
750 if (!sr_dev) {
751 signalbases_.clear();
752 logic_data_.reset();
753 for (shared_ptr<views::ViewBase> view : views_) {
754 view->clear_signals();
755#ifdef ENABLE_DECODE
756 view->clear_decode_signals();
757#endif
758 }
759 return;
760 }
761
762 // Detect what data types we will receive
763 auto channels = sr_dev->channels();
764 unsigned int logic_channel_count = count_if(
765 channels.begin(), channels.end(),
766 [] (shared_ptr<Channel> channel) {
767 return channel->type() == sigrok::ChannelType::LOGIC; });
768
769 // Create data containers for the logic data segments
770 {
771 lock_guard<recursive_mutex> data_lock(data_mutex_);
772
773 if (logic_channel_count == 0) {
774 logic_data_.reset();
775 } else if (!logic_data_ ||
776 logic_data_->num_channels() != logic_channel_count) {
777 logic_data_.reset(new data::Logic(
778 logic_channel_count));
779 assert(logic_data_);
780 }
781 }
782
783 // Make the signals list
784 for (shared_ptr<views::ViewBase> viewbase : views_) {
785 views::trace::View *trace_view =
786 qobject_cast<views::trace::View*>(viewbase.get());
787
788 if (trace_view) {
789 unordered_set< shared_ptr<views::trace::Signal> >
790 prev_sigs(trace_view->signals());
791 trace_view->clear_signals();
792
793 for (auto channel : sr_dev->channels()) {
794 shared_ptr<data::SignalBase> signalbase;
795 shared_ptr<views::trace::Signal> signal;
796
797 // Find the channel in the old signals
798 const auto iter = find_if(
799 prev_sigs.cbegin(), prev_sigs.cend(),
800 [&](const shared_ptr<views::trace::Signal> &s) {
801 return s->base()->channel() == channel;
802 });
803 if (iter != prev_sigs.end()) {
804 // Copy the signal from the old set to the new
805 signal = *iter;
806 trace_view->add_signal(signal);
807 } else {
808 // Find the signalbase for this channel if possible
809 signalbase.reset();
810 for (const shared_ptr<data::SignalBase> b : signalbases_)
811 if (b->channel() == channel)
812 signalbase = b;
813
814 switch(channel->type()->id()) {
815 case SR_CHANNEL_LOGIC:
816 if (!signalbase) {
817 signalbase = make_shared<data::SignalBase>(channel,
818 data::SignalBase::LogicChannel);
819 signalbases_.insert(signalbase);
820
821 all_signal_data_.insert(logic_data_);
822 signalbase->set_data(logic_data_);
823
824 connect(this, SIGNAL(capture_state_changed(int)),
825 signalbase.get(), SLOT(on_capture_state_changed(int)));
826 }
827
828 signal = shared_ptr<views::trace::Signal>(
829 new views::trace::LogicSignal(*this,
830 device_, signalbase));
831 trace_view->add_signal(signal);
832 break;
833
834 case SR_CHANNEL_ANALOG:
835 {
836 if (!signalbase) {
837 signalbase = make_shared<data::SignalBase>(channel,
838 data::SignalBase::AnalogChannel);
839 signalbases_.insert(signalbase);
840
841 shared_ptr<data::Analog> data(new data::Analog());
842 all_signal_data_.insert(data);
843 signalbase->set_data(data);
844
845 connect(this, SIGNAL(capture_state_changed(int)),
846 signalbase.get(), SLOT(on_capture_state_changed(int)));
847 }
848
849 signal = shared_ptr<views::trace::Signal>(
850 new views::trace::AnalogSignal(
851 *this, signalbase));
852 trace_view->add_signal(signal);
853 break;
854 }
855
856 default:
857 assert(false);
858 break;
859 }
860 }
861 }
862 }
863 }
864
865 signals_changed();
866}
867
868shared_ptr<data::SignalBase> Session::signalbase_from_channel(
869 shared_ptr<sigrok::Channel> channel) const
870{
871 for (shared_ptr<data::SignalBase> sig : signalbases_) {
872 assert(sig);
873 if (sig->channel() == channel)
874 return sig;
875 }
876 return shared_ptr<data::SignalBase>();
877}
878
879void Session::sample_thread_proc(function<void (const QString)> error_handler)
880{
881 assert(error_handler);
882
883 if (!device_)
884 return;
885
886 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
887
888 out_of_memory_ = false;
889
890 try {
891 device_->start();
892 } catch (Error e) {
893 error_handler(e.what());
894 return;
895 }
896
897 set_capture_state(device_->session()->trigger() ?
898 AwaitingTrigger : Running);
899
900 try {
901 device_->run();
902 } catch (Error e) {
903 error_handler(e.what());
904 set_capture_state(Stopped);
905 return;
906 }
907
908 set_capture_state(Stopped);
909
910 // Confirm that SR_DF_END was received
911 if (cur_logic_segment_) {
912 qDebug("SR_DF_END was not received.");
913 assert(false);
914 }
915
916 // Optimize memory usage
917 free_unused_memory();
918
919 // We now have unsaved data unless we just "captured" from a file
920 shared_ptr<devices::File> file_device =
921 dynamic_pointer_cast<devices::File>(device_);
922
923 if (!file_device)
924 data_saved_ = false;
925
926 if (out_of_memory_)
927 error_handler(tr("Out of memory, acquisition stopped."));
928}
929
930void Session::free_unused_memory()
931{
932 for (shared_ptr<data::SignalData> data : all_signal_data_) {
933 const vector< shared_ptr<data::Segment> > segments = data->segments();
934
935 for (shared_ptr<data::Segment> segment : segments) {
936 segment->free_unused_memory();
937 }
938 }
939}
940
941void Session::feed_in_header()
942{
943 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
944}
945
946void Session::feed_in_meta(shared_ptr<Meta> meta)
947{
948 for (auto entry : meta->config()) {
949 switch (entry.first->id()) {
950 case SR_CONF_SAMPLERATE:
951 // We can't rely on the header to always contain the sample rate,
952 // so in case it's supplied via a meta packet, we use it.
953 if (!cur_samplerate_)
954 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
955
956 /// @todo handle samplerate changes
957 break;
958 default:
959 // Unknown metadata is not an error.
960 break;
961 }
962 }
963
964 signals_changed();
965}
966
967void Session::feed_in_trigger()
968{
969 // The channel containing most samples should be most accurate
970 uint64_t sample_count = 0;
971
972 {
973 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
974 assert(d);
975 uint64_t temp_count = 0;
976
977 const vector< shared_ptr<pv::data::Segment> > segments =
978 d->segments();
979 for (const shared_ptr<pv::data::Segment> &s : segments)
980 temp_count += s->get_sample_count();
981
982 if (temp_count > sample_count)
983 sample_count = temp_count;
984 }
985 }
986
987 trigger_event(sample_count / get_samplerate());
988}
989
990void Session::feed_in_frame_begin()
991{
992 if (cur_logic_segment_ || !cur_analog_segments_.empty())
993 frame_began();
994}
995
996void Session::feed_in_logic(shared_ptr<Logic> logic)
997{
998 lock_guard<recursive_mutex> lock(data_mutex_);
999
1000 if (!logic_data_) {
1001 // The only reason logic_data_ would not have been created is
1002 // if it was not possible to determine the signals when the
1003 // device was created.
1004 update_signals();
1005 }
1006
1007 if (!cur_logic_segment_) {
1008 // This could be the first packet after a trigger
1009 set_capture_state(Running);
1010
1011 // Create a new data segment
1012 cur_logic_segment_ = make_shared<data::LogicSegment>(
1013 *logic_data_, logic->unit_size(), cur_samplerate_);
1014 logic_data_->push_segment(cur_logic_segment_);
1015
1016 // @todo Putting this here means that only listeners querying
1017 // for logic will be notified. Currently the only user of
1018 // frame_began is DecoderStack, but in future we need to signal
1019 // this after both analog and logic sweeps have begun.
1020 frame_began();
1021 }
1022
1023 cur_logic_segment_->append_payload(logic);
1024
1025 data_received();
1026}
1027
1028void Session::feed_in_analog(shared_ptr<Analog> analog)
1029{
1030 lock_guard<recursive_mutex> lock(data_mutex_);
1031
1032 const vector<shared_ptr<Channel>> channels = analog->channels();
1033 const unsigned int channel_count = channels.size();
1034 const size_t sample_count = analog->num_samples() / channel_count;
1035 bool sweep_beginning = false;
1036
1037 unique_ptr<float> data(new float[analog->num_samples()]);
1038 analog->get_data_as_float(data.get());
1039
1040 if (signalbases_.empty())
1041 update_signals();
1042
1043 float *channel_data = data.get();
1044 for (auto channel : channels) {
1045 shared_ptr<data::AnalogSegment> segment;
1046
1047 // Try to get the segment of the channel
1048 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1049 iterator iter = cur_analog_segments_.find(channel);
1050 if (iter != cur_analog_segments_.end())
1051 segment = (*iter).second;
1052 else {
1053 // If no segment was found, this means we haven't
1054 // created one yet. i.e. this is the first packet
1055 // in the sweep containing this segment.
1056 sweep_beginning = true;
1057
1058 // Find the analog data associated with the channel
1059 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1060 assert(base);
1061
1062 shared_ptr<data::Analog> data(base->analog_data());
1063 assert(data);
1064
1065 // Create a segment, keep it in the maps of channels
1066 segment = make_shared<data::AnalogSegment>(
1067 *data, cur_samplerate_);
1068 cur_analog_segments_[channel] = segment;
1069
1070 // Push the segment into the analog data.
1071 data->push_segment(segment);
1072 }
1073
1074 assert(segment);
1075
1076 // Append the samples in the segment
1077 segment->append_interleaved_samples(channel_data++, sample_count,
1078 channel_count);
1079 }
1080
1081 if (sweep_beginning) {
1082 // This could be the first packet after a trigger
1083 set_capture_state(Running);
1084 }
1085
1086 data_received();
1087}
1088
1089void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1090 shared_ptr<Packet> packet)
1091{
1092 static bool frame_began = false;
1093
1094 (void)device;
1095
1096 assert(device);
1097 assert(device == device_->device());
1098 assert(packet);
1099
1100 switch (packet->type()->id()) {
1101 case SR_DF_HEADER:
1102 feed_in_header();
1103 break;
1104
1105 case SR_DF_META:
1106 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1107 break;
1108
1109 case SR_DF_TRIGGER:
1110 feed_in_trigger();
1111 break;
1112
1113 case SR_DF_FRAME_BEGIN:
1114 feed_in_frame_begin();
1115 frame_began = true;
1116 break;
1117
1118 case SR_DF_LOGIC:
1119 try {
1120 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1121 } catch (bad_alloc) {
1122 out_of_memory_ = true;
1123 device_->stop();
1124 }
1125 break;
1126
1127 case SR_DF_ANALOG:
1128 try {
1129 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1130 } catch (bad_alloc) {
1131 out_of_memory_ = true;
1132 device_->stop();
1133 }
1134 break;
1135
1136 case SR_DF_FRAME_END:
1137 case SR_DF_END:
1138 {
1139 {
1140 lock_guard<recursive_mutex> lock(data_mutex_);
1141 cur_logic_segment_.reset();
1142 cur_analog_segments_.clear();
1143 }
1144 if (frame_began) {
1145 frame_began = false;
1146 frame_ended();
1147 }
1148 break;
1149 }
1150 default:
1151 break;
1152 }
1153}
1154
1155void Session::on_data_saved()
1156{
1157 data_saved_ = true;
1158}
1159
1160} // namespace pv