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