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