]> sigrok.org Git - pulseview.git/blame_incremental - pv/session.cpp
build: Bump libsigrokcxx requirement to >= 0.5.2.
[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 <cassert>
21#include <memory>
22#include <mutex>
23#include <stdexcept>
24
25#include <sys/stat.h>
26
27#include <QDebug>
28#include <QFileInfo>
29
30#include "devicemanager.hpp"
31#include "mainwindow.hpp"
32#include "session.hpp"
33#include "util.hpp"
34
35#include "data/analog.hpp"
36#include "data/analogsegment.hpp"
37#include "data/decode/decoder.hpp"
38#include "data/logic.hpp"
39#include "data/logicsegment.hpp"
40#include "data/signalbase.hpp"
41
42#include "devices/hardwaredevice.hpp"
43#include "devices/inputfile.hpp"
44#include "devices/sessionfile.hpp"
45
46#include "toolbars/mainbar.hpp"
47
48#include "views/trace/analogsignal.hpp"
49#include "views/trace/decodetrace.hpp"
50#include "views/trace/logicsignal.hpp"
51#include "views/trace/signal.hpp"
52#include "views/trace/view.hpp"
53
54#include <libsigrokcxx/libsigrokcxx.hpp>
55
56#ifdef ENABLE_FLOW
57#include <gstreamermm.h>
58#include <libsigrokflow/libsigrokflow.hpp>
59#endif
60
61#ifdef ENABLE_DECODE
62#include <libsigrokdecode/libsigrokdecode.h>
63#include "data/decodesignal.hpp"
64#endif
65
66using std::bad_alloc;
67using std::dynamic_pointer_cast;
68using std::find_if;
69using std::function;
70using std::list;
71using std::lock_guard;
72using std::make_pair;
73using std::make_shared;
74using std::map;
75using std::max;
76using std::move;
77using std::mutex;
78using std::pair;
79using std::recursive_mutex;
80using std::runtime_error;
81using std::shared_ptr;
82using std::string;
83#ifdef ENABLE_FLOW
84using std::unique_lock;
85#endif
86using std::unique_ptr;
87using std::vector;
88
89using sigrok::Analog;
90using sigrok::Channel;
91using sigrok::ConfigKey;
92using sigrok::DatafeedCallbackFunction;
93using sigrok::Error;
94using sigrok::InputFormat;
95using sigrok::Logic;
96using sigrok::Meta;
97using sigrok::Packet;
98using sigrok::Session;
99
100using Glib::VariantBase;
101
102#ifdef ENABLE_FLOW
103using Gst::Bus;
104using Gst::ElementFactory;
105using Gst::Pipeline;
106#endif
107
108using pv::util::Timestamp;
109using pv::views::trace::Signal;
110using pv::views::trace::AnalogSignal;
111using pv::views::trace::LogicSignal;
112
113namespace pv {
114
115shared_ptr<sigrok::Context> Session::sr_context;
116
117Session::Session(DeviceManager &device_manager, QString name) :
118 device_manager_(device_manager),
119 default_name_(name),
120 name_(name),
121 capture_state_(Stopped),
122 cur_samplerate_(0),
123 data_saved_(true)
124{
125}
126
127Session::~Session()
128{
129 // Stop and join to the thread
130 stop_capture();
131}
132
133DeviceManager& Session::device_manager()
134{
135 return device_manager_;
136}
137
138const DeviceManager& Session::device_manager() const
139{
140 return device_manager_;
141}
142
143shared_ptr<sigrok::Session> Session::session() const
144{
145 if (!device_)
146 return shared_ptr<sigrok::Session>();
147 return device_->session();
148}
149
150shared_ptr<devices::Device> Session::device() const
151{
152 return device_;
153}
154
155QString Session::name() const
156{
157 return name_;
158}
159
160void Session::set_name(QString name)
161{
162 if (default_name_.isEmpty())
163 default_name_ = name;
164
165 name_ = name;
166
167 name_changed();
168}
169
170const vector< shared_ptr<views::ViewBase> > Session::views() const
171{
172 return views_;
173}
174
175shared_ptr<views::ViewBase> Session::main_view() const
176{
177 return main_view_;
178}
179
180void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
181{
182 main_bar_ = main_bar;
183}
184
185shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
186{
187 return main_bar_;
188}
189
190bool Session::data_saved() const
191{
192 return data_saved_;
193}
194
195void Session::save_setup(QSettings &settings) const
196{
197 int i = 0;
198
199 // Save channels and decoders
200 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
201#ifdef ENABLE_DECODE
202 if (base->is_decode_signal()) {
203 settings.beginGroup("decode_signal" + QString::number(i++));
204 base->save_settings(settings);
205 settings.endGroup();
206 } else
207#endif
208 {
209 settings.beginGroup(base->internal_name());
210 base->save_settings(settings);
211 settings.endGroup();
212 }
213 }
214
215 settings.setValue("decode_signals", i);
216
217 // Save view states and their signal settings
218 // Note: main_view must be saved as view0
219 i = 0;
220 settings.beginGroup("view" + QString::number(i++));
221 main_view_->save_settings(settings);
222 settings.endGroup();
223
224 for (const shared_ptr<views::ViewBase>& view : views_) {
225 if (view != main_view_) {
226 settings.beginGroup("view" + QString::number(i++));
227 settings.setValue("type", view->get_type());
228 view->save_settings(settings);
229 settings.endGroup();
230 }
231 }
232
233 settings.setValue("views", i);
234
235 int view_id = 0;
236 i = 0;
237 for (const shared_ptr<views::ViewBase>& vb : views_) {
238 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(vb);
239 if (tv) {
240 for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
241
242 const shared_ptr<views::trace::Flag> flag =
243 dynamic_pointer_cast<views::trace::Flag>(time_item);
244 if (flag) {
245 if (!flag->enabled())
246 continue;
247
248 settings.beginGroup("meta_obj" + QString::number(i++));
249 settings.setValue("type", "time_marker");
250 settings.setValue("assoc_view", view_id);
251 GlobalSettings::store_timestamp(settings, "time", flag->time());
252 settings.setValue("text", flag->get_text());
253 settings.endGroup();
254 }
255 }
256
257 if (tv->cursors_shown()) {
258 settings.beginGroup("meta_obj" + QString::number(i++));
259 settings.setValue("type", "selection");
260 settings.setValue("assoc_view", view_id);
261 const shared_ptr<views::trace::CursorPair> cp = tv->cursors();
262 GlobalSettings::store_timestamp(settings, "start_time", cp->first()->time());
263 GlobalSettings::store_timestamp(settings, "end_time", cp->second()->time());
264 settings.endGroup();
265 }
266 }
267
268 view_id++;
269 }
270
271 settings.setValue("meta_objs", i);
272}
273
274void Session::save_settings(QSettings &settings) const
275{
276 map<string, string> dev_info;
277 list<string> key_list;
278
279 if (device_) {
280 shared_ptr<devices::HardwareDevice> hw_device =
281 dynamic_pointer_cast< devices::HardwareDevice >(device_);
282
283 if (hw_device) {
284 settings.setValue("device_type", "hardware");
285 settings.beginGroup("device");
286
287 key_list.emplace_back("vendor");
288 key_list.emplace_back("model");
289 key_list.emplace_back("version");
290 key_list.emplace_back("serial_num");
291 key_list.emplace_back("connection_id");
292
293 dev_info = device_manager_.get_device_info(device_);
294
295 for (string& key : key_list) {
296 if (dev_info.count(key))
297 settings.setValue(QString::fromUtf8(key.c_str()),
298 QString::fromUtf8(dev_info.at(key).c_str()));
299 else
300 settings.remove(QString::fromUtf8(key.c_str()));
301 }
302
303 settings.endGroup();
304 }
305
306 shared_ptr<devices::SessionFile> sessionfile_device =
307 dynamic_pointer_cast<devices::SessionFile>(device_);
308
309 if (sessionfile_device) {
310 settings.setValue("device_type", "sessionfile");
311 settings.beginGroup("device");
312 settings.setValue("filename", QString::fromStdString(
313 sessionfile_device->full_name()));
314 settings.endGroup();
315 }
316
317 shared_ptr<devices::InputFile> inputfile_device =
318 dynamic_pointer_cast<devices::InputFile>(device_);
319
320 if (inputfile_device) {
321 settings.setValue("device_type", "inputfile");
322 settings.beginGroup("device");
323 inputfile_device->save_meta_to_settings(settings);
324 settings.endGroup();
325 }
326
327 save_setup(settings);
328 }
329}
330
331void Session::restore_setup(QSettings &settings)
332{
333 // Restore channels
334 for (shared_ptr<data::SignalBase> base : signalbases_) {
335 settings.beginGroup(base->internal_name());
336 base->restore_settings(settings);
337 settings.endGroup();
338 }
339
340 // Restore decoders
341#ifdef ENABLE_DECODE
342 int decode_signals = settings.value("decode_signals").toInt();
343
344 for (int i = 0; i < decode_signals; i++) {
345 settings.beginGroup("decode_signal" + QString::number(i));
346 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
347 signal->restore_settings(settings);
348 settings.endGroup();
349 }
350#endif
351
352 // Restore views
353 int views = settings.value("views").toInt();
354
355 for (int i = 0; i < views; i++) {
356 settings.beginGroup("view" + QString::number(i));
357
358 if (i > 0) {
359 views::ViewType type = (views::ViewType)settings.value("type").toInt();
360 add_view(type, this);
361 views_.back()->restore_settings(settings);
362 } else
363 main_view_->restore_settings(settings);
364
365 settings.endGroup();
366 }
367
368 // Restore meta objects like markers and cursors
369 int meta_objs = settings.value("meta_objs").toInt();
370
371 for (int i = 0; i < meta_objs; i++) {
372 settings.beginGroup("meta_obj" + QString::number(i));
373
374 shared_ptr<views::ViewBase> vb;
375 shared_ptr<views::trace::View> tv;
376 if (settings.contains("assoc_view"))
377 vb = views_.at(settings.value("assoc_view").toInt());
378
379 if (vb)
380 tv = dynamic_pointer_cast<views::trace::View>(vb);
381
382 const QString type = settings.value("type").toString();
383
384 if ((type == "time_marker") && tv) {
385 Timestamp ts = GlobalSettings::restore_timestamp(settings, "time");
386 shared_ptr<views::trace::Flag> flag = tv->add_flag(ts);
387 flag->set_text(settings.value("text").toString());
388 }
389
390 if ((type == "selection") && tv) {
391 Timestamp start = GlobalSettings::restore_timestamp(settings, "start_time");
392 Timestamp end = GlobalSettings::restore_timestamp(settings, "end_time");
393 tv->set_cursors(start, end);
394 tv->show_cursors();
395 }
396
397 settings.endGroup();
398 }
399}
400
401void Session::restore_settings(QSettings &settings)
402{
403 shared_ptr<devices::Device> device;
404
405 const QString device_type = settings.value("device_type").toString();
406
407 if (device_type == "hardware") {
408 map<string, string> dev_info;
409 list<string> key_list;
410
411 // Re-select last used device if possible but only if it's not demo
412 settings.beginGroup("device");
413 key_list.emplace_back("vendor");
414 key_list.emplace_back("model");
415 key_list.emplace_back("version");
416 key_list.emplace_back("serial_num");
417 key_list.emplace_back("connection_id");
418
419 for (string key : key_list) {
420 const QString k = QString::fromStdString(key);
421 if (!settings.contains(k))
422 continue;
423
424 const string value = settings.value(k).toString().toStdString();
425 if (!value.empty())
426 dev_info.insert(make_pair(key, value));
427 }
428
429 if (dev_info.count("model") > 0)
430 device = device_manager_.find_device_from_info(dev_info);
431
432 if (device)
433 set_device(device);
434
435 settings.endGroup();
436 }
437
438 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
439 if (device_type == "sessionfile") {
440 settings.beginGroup("device");
441 const QString filename = settings.value("filename").toString();
442 settings.endGroup();
443
444 if (QFileInfo(filename).isReadable()) {
445 device = make_shared<devices::SessionFile>(device_manager_.context(),
446 filename.toStdString());
447 }
448 }
449
450 if (device_type == "inputfile") {
451 settings.beginGroup("device");
452 device = make_shared<devices::InputFile>(device_manager_.context(),
453 settings);
454 settings.endGroup();
455 }
456
457 if (device) {
458 set_device(device);
459
460 start_capture([](QString infoMessage) {
461 // TODO Emulate noquote()
462 qDebug() << "Session error:" << infoMessage; });
463
464 set_name(QString::fromStdString(
465 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
466 }
467 }
468
469 if (device)
470 restore_setup(settings);
471}
472
473void Session::select_device(shared_ptr<devices::Device> device)
474{
475 try {
476 if (device)
477 set_device(device);
478 else
479 set_default_device();
480 } catch (const QString &e) {
481 MainWindow::show_session_error(tr("Failed to select device"), e);
482 }
483}
484
485void Session::set_device(shared_ptr<devices::Device> device)
486{
487 assert(device);
488
489 // Ensure we are not capturing before setting the device
490 stop_capture();
491
492 if (device_)
493 device_->close();
494
495 device_.reset();
496
497 // Revert name back to default name (e.g. "Session 1") as the data is gone
498 name_ = default_name_;
499 name_changed();
500
501 // Remove all stored data and reset all views
502 for (shared_ptr<views::ViewBase> view : views_) {
503 view->clear_signals();
504#ifdef ENABLE_DECODE
505 view->clear_decode_signals();
506#endif
507 view->reset_view_state();
508 }
509 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
510 d->clear();
511 all_signal_data_.clear();
512 signalbases_.clear();
513 cur_logic_segment_.reset();
514
515 for (auto& entry : cur_analog_segments_) {
516 shared_ptr<sigrok::Channel>(entry.first).reset();
517 shared_ptr<data::AnalogSegment>(entry.second).reset();
518 }
519
520 logic_data_.reset();
521
522 signals_changed();
523
524 device_ = move(device);
525
526 try {
527 device_->open();
528 } catch (const QString &e) {
529 device_.reset();
530 MainWindow::show_session_error(tr("Failed to open device"), e);
531 }
532
533 if (device_) {
534 device_->session()->add_datafeed_callback([=]
535 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
536 data_feed_in(device, packet);
537 });
538
539 update_signals();
540 }
541
542 device_changed();
543}
544
545void Session::set_default_device()
546{
547 const list< shared_ptr<devices::HardwareDevice> > &devices =
548 device_manager_.devices();
549
550 if (devices.empty())
551 return;
552
553 // Try and find the demo device and select that by default
554 const auto iter = find_if(devices.begin(), devices.end(),
555 [] (const shared_ptr<devices::HardwareDevice> &d) {
556 return d->hardware_device()->driver()->name() == "demo"; });
557 set_device((iter == devices.end()) ? devices.front() : *iter);
558}
559
560bool Session::using_file_device() const
561{
562 shared_ptr<devices::SessionFile> sessionfile_device =
563 dynamic_pointer_cast<devices::SessionFile>(device_);
564
565 shared_ptr<devices::InputFile> inputfile_device =
566 dynamic_pointer_cast<devices::InputFile>(device_);
567
568 return (sessionfile_device || inputfile_device);
569}
570
571/**
572 * Convert generic options to data types that are specific to InputFormat.
573 *
574 * @param[in] user_spec Vector of tokenized words, string format.
575 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
576 *
577 * @return Map of options suitable for InputFormat::create_input().
578 */
579map<string, Glib::VariantBase>
580Session::input_format_options(vector<string> user_spec,
581 map<string, shared_ptr<Option>> fmt_opts)
582{
583 map<string, Glib::VariantBase> result;
584
585 for (auto& entry : user_spec) {
586 /*
587 * Split key=value specs. Accept entries without separator
588 * (for simplified boolean specifications).
589 */
590 string key, val;
591 size_t pos = entry.find("=");
592 if (pos == std::string::npos) {
593 key = entry;
594 val = "";
595 } else {
596 key = entry.substr(0, pos);
597 val = entry.substr(pos + 1);
598 }
599
600 /*
601 * Skip user specifications that are not a member of the
602 * format's set of supported options. Have the text input
603 * spec converted to the required input format specific
604 * data type.
605 */
606 auto found = fmt_opts.find(key);
607 if (found == fmt_opts.end())
608 continue;
609 shared_ptr<Option> opt = found->second;
610 result[key] = opt->parse_string(val);
611 }
612
613 return result;
614}
615
616void Session::load_init_file(const string &file_name,
617 const string &format, const string &setup_file_name)
618{
619 shared_ptr<InputFormat> input_format;
620 map<string, Glib::VariantBase> input_opts;
621
622 if (!format.empty()) {
623 const map<string, shared_ptr<InputFormat> > formats =
624 device_manager_.context()->input_formats();
625 auto user_opts = pv::util::split_string(format, ":");
626 string user_name = user_opts.front();
627 user_opts.erase(user_opts.begin());
628 const auto iter = find_if(formats.begin(), formats.end(),
629 [&](const pair<string, shared_ptr<InputFormat> > f) {
630 return f.first == user_name; });
631 if (iter == formats.end()) {
632 MainWindow::show_session_error(tr("Error"),
633 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
634 return;
635 }
636 input_format = (*iter).second;
637 input_opts = input_format_options(user_opts,
638 input_format->options());
639 }
640
641 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
642 input_format, input_opts);
643}
644
645void Session::load_file(QString file_name, QString setup_file_name,
646 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
647{
648 const QString errorMessage(
649 QString("Failed to load file %1").arg(file_name));
650
651 // In the absence of a caller's format spec, try to auto detect.
652 // Assume "sigrok session file" upon lookup miss.
653 if (!format)
654 format = device_manager_.context()->input_format_match(file_name.toStdString());
655 try {
656 if (format)
657 set_device(shared_ptr<devices::Device>(
658 new devices::InputFile(
659 device_manager_.context(),
660 file_name.toStdString(),
661 format, options)));
662 else
663 set_device(shared_ptr<devices::Device>(
664 new devices::SessionFile(
665 device_manager_.context(),
666 file_name.toStdString())));
667 } catch (Error& e) {
668 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
669 set_default_device();
670 main_bar_->update_device_list();
671 return;
672 }
673
674 // Use the input file with .pvs extension if no setup file was given
675 if (setup_file_name.isEmpty()) {
676 setup_file_name = file_name;
677 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
678 setup_file_name.append(".pvs");
679 }
680
681 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
682 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
683 restore_setup(settings_storage);
684 }
685
686 main_bar_->update_device_list();
687
688 start_capture([&, errorMessage](QString infoMessage) {
689 MainWindow::show_session_error(errorMessage, infoMessage); });
690
691 set_name(QFileInfo(file_name).fileName());
692}
693
694Session::capture_state Session::get_capture_state() const
695{
696 lock_guard<mutex> lock(sampling_mutex_);
697 return capture_state_;
698}
699
700void Session::start_capture(function<void (const QString)> error_handler)
701{
702 if (!device_) {
703 error_handler(tr("No active device set, can't start acquisition."));
704 return;
705 }
706
707 stop_capture();
708
709 // Check that at least one channel is enabled
710 const shared_ptr<sigrok::Device> sr_dev = device_->device();
711 if (sr_dev) {
712 const auto channels = sr_dev->channels();
713 if (!any_of(channels.begin(), channels.end(),
714 [](shared_ptr<Channel> channel) {
715 return channel->enabled(); })) {
716 error_handler(tr("No channels enabled."));
717 return;
718 }
719 }
720
721 // Clear signal data
722 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
723 d->clear();
724
725 trigger_list_.clear();
726
727 // Revert name back to default name (e.g. "Session 1") for real devices
728 // as the (possibly saved) data is gone. File devices keep their name.
729 shared_ptr<devices::HardwareDevice> hw_device =
730 dynamic_pointer_cast< devices::HardwareDevice >(device_);
731
732 if (hw_device) {
733 name_ = default_name_;
734 name_changed();
735 }
736
737 // Begin the session
738 sampling_thread_ = std::thread(
739 &Session::sample_thread_proc, this, error_handler);
740}
741
742void Session::stop_capture()
743{
744 if (get_capture_state() != Stopped)
745 device_->stop();
746
747 // Check that sampling stopped
748 if (sampling_thread_.joinable())
749 sampling_thread_.join();
750}
751
752void Session::register_view(shared_ptr<views::ViewBase> view)
753{
754 if (views_.empty())
755 main_view_ = view;
756
757 views_.push_back(view);
758
759 // Add all device signals
760 update_signals();
761
762 // Add all other signals
763 vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
764
765 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
766 const int sb_exists = count_if(
767 view_signalbases.cbegin(), view_signalbases.cend(),
768 [&](const shared_ptr<data::SignalBase> &sb) {
769 return sb == signalbase;
770 });
771
772 // Add the signal to the view if it doesn't have it yet
773 if (!sb_exists)
774 switch (signalbase->type()) {
775 case data::SignalBase::AnalogChannel:
776 case data::SignalBase::LogicChannel:
777 case data::SignalBase::MathChannel:
778 view->add_signalbase(signalbase);
779 break;
780 case data::SignalBase::DecodeChannel:
781#ifdef ENABLE_DECODE
782 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
783#endif
784 break;
785 }
786 }
787
788 signals_changed();
789}
790
791void Session::deregister_view(shared_ptr<views::ViewBase> view)
792{
793 views_.erase(std::remove_if(views_.begin(), views_.end(),
794 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
795 views_.end());
796
797 if (views_.empty()) {
798 main_view_.reset();
799
800 // Without a view there can be no main bar
801 main_bar_.reset();
802 }
803}
804
805bool Session::has_view(shared_ptr<views::ViewBase> view)
806{
807 for (shared_ptr<views::ViewBase>& v : views_)
808 if (v == view)
809 return true;
810
811 return false;
812}
813
814double Session::get_samplerate() const
815{
816 double samplerate = 0.0;
817
818 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
819 assert(d);
820 const vector< shared_ptr<pv::data::Segment> > segments =
821 d->segments();
822 for (const shared_ptr<pv::data::Segment>& s : segments)
823 samplerate = max(samplerate, s->samplerate());
824 }
825 // If there is no sample rate given we use samples as unit
826 if (samplerate == 0.0)
827 samplerate = 1.0;
828
829 return samplerate;
830}
831
832uint32_t Session::get_segment_count() const
833{
834 uint32_t value = 0;
835
836 // Find the highest number of segments
837 for (const shared_ptr<data::SignalData>& data : all_signal_data_)
838 if (data->get_segment_count() > value)
839 value = data->get_segment_count();
840
841 return value;
842}
843
844vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
845{
846 vector<util::Timestamp> result;
847
848 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
849 if (entry.first == segment_id)
850 result.push_back(entry.second);
851
852 return result;
853}
854
855const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
856{
857 return signalbases_;
858}
859
860bool Session::all_segments_complete(uint32_t segment_id) const
861{
862 bool all_complete = true;
863
864 for (const shared_ptr<data::SignalBase>& base : signalbases_)
865 if (!base->segment_is_complete(segment_id))
866 all_complete = false;
867
868 return all_complete;
869}
870
871#ifdef ENABLE_DECODE
872shared_ptr<data::DecodeSignal> Session::add_decode_signal()
873{
874 shared_ptr<data::DecodeSignal> signal;
875
876 try {
877 // Create the decode signal
878 signal = make_shared<data::DecodeSignal>(*this);
879
880 signalbases_.push_back(signal);
881
882 // Add the decode signal to all views
883 for (shared_ptr<views::ViewBase>& view : views_)
884 view->add_decode_signal(signal);
885 } catch (runtime_error& e) {
886 remove_decode_signal(signal);
887 return nullptr;
888 }
889
890 signals_changed();
891
892 return signal;
893}
894
895void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
896{
897 signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
898 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
899 signalbases_.end());
900
901 for (shared_ptr<views::ViewBase>& view : views_)
902 view->remove_decode_signal(signal);
903
904 signals_changed();
905}
906#endif
907
908void Session::set_capture_state(capture_state state)
909{
910 bool changed;
911
912 if (state == Running)
913 acq_time_.restart();
914 if (state == Stopped)
915 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
916
917 {
918 lock_guard<mutex> lock(sampling_mutex_);
919 changed = capture_state_ != state;
920 capture_state_ = state;
921 }
922
923 if (changed)
924 capture_state_changed(state);
925}
926
927void Session::update_signals()
928{
929 if (!device_) {
930 signalbases_.clear();
931 logic_data_.reset();
932 for (shared_ptr<views::ViewBase>& view : views_) {
933 view->clear_signals();
934#ifdef ENABLE_DECODE
935 view->clear_decode_signals();
936#endif
937 }
938 return;
939 }
940
941 lock_guard<recursive_mutex> lock(data_mutex_);
942
943 const shared_ptr<sigrok::Device> sr_dev = device_->device();
944 if (!sr_dev) {
945 signalbases_.clear();
946 logic_data_.reset();
947 for (shared_ptr<views::ViewBase>& view : views_) {
948 view->clear_signals();
949#ifdef ENABLE_DECODE
950 view->clear_decode_signals();
951#endif
952 }
953 return;
954 }
955
956 // Detect what data types we will receive
957 auto channels = sr_dev->channels();
958 unsigned int logic_channel_count = count_if(
959 channels.begin(), channels.end(),
960 [] (shared_ptr<Channel> channel) {
961 return channel->type() == sigrok::ChannelType::LOGIC; });
962
963 // Create data containers for the logic data segments
964 {
965 lock_guard<recursive_mutex> data_lock(data_mutex_);
966
967 if (logic_channel_count == 0) {
968 logic_data_.reset();
969 } else if (!logic_data_ ||
970 logic_data_->num_channels() != logic_channel_count) {
971 logic_data_.reset(new data::Logic(
972 logic_channel_count));
973 assert(logic_data_);
974 }
975 }
976
977 // Make the signals list
978 for (shared_ptr<views::ViewBase>& viewbase : views_) {
979 views::trace::View *trace_view =
980 qobject_cast<views::trace::View*>(viewbase.get());
981
982 if (trace_view) {
983 vector< shared_ptr<Signal> > prev_sigs(trace_view->signals());
984 trace_view->clear_signals();
985
986 for (auto channel : sr_dev->channels()) {
987 shared_ptr<data::SignalBase> signalbase;
988 shared_ptr<Signal> signal;
989
990 // Find the channel in the old signals
991 const auto iter = find_if(
992 prev_sigs.cbegin(), prev_sigs.cend(),
993 [&](const shared_ptr<Signal> &s) {
994 return s->base()->channel() == channel;
995 });
996 if (iter != prev_sigs.end()) {
997 // Copy the signal from the old set to the new
998 signal = *iter;
999 trace_view->add_signal(signal);
1000 } else {
1001 // Find the signalbase for this channel if possible
1002 signalbase.reset();
1003 for (const shared_ptr<data::SignalBase>& b : signalbases_)
1004 if (b->channel() == channel)
1005 signalbase = b;
1006
1007 shared_ptr<Signal> signal;
1008
1009 switch(channel->type()->id()) {
1010 case SR_CHANNEL_LOGIC:
1011 if (!signalbase) {
1012 signalbase = make_shared<data::SignalBase>(channel,
1013 data::SignalBase::LogicChannel);
1014 signalbases_.push_back(signalbase);
1015
1016 all_signal_data_.insert(logic_data_);
1017 signalbase->set_data(logic_data_);
1018
1019 connect(this, SIGNAL(capture_state_changed(int)),
1020 signalbase.get(), SLOT(on_capture_state_changed(int)));
1021 }
1022
1023 signal = shared_ptr<Signal>(new LogicSignal(*this, device_, signalbase));
1024 break;
1025
1026 case SR_CHANNEL_ANALOG:
1027 {
1028 if (!signalbase) {
1029 signalbase = make_shared<data::SignalBase>(channel,
1030 data::SignalBase::AnalogChannel);
1031 signalbases_.push_back(signalbase);
1032
1033 shared_ptr<data::Analog> data(new data::Analog());
1034 all_signal_data_.insert(data);
1035 signalbase->set_data(data);
1036
1037 connect(this, SIGNAL(capture_state_changed(int)),
1038 signalbase.get(), SLOT(on_capture_state_changed(int)));
1039 }
1040
1041 signal = shared_ptr<Signal>(new AnalogSignal(*this, signalbase));
1042 break;
1043 }
1044
1045 default:
1046 assert(false);
1047 break;
1048 }
1049
1050 // New views take their signal settings from the main view
1051 if (!viewbase->is_main_view()) {
1052 shared_ptr<pv::views::trace::View> main_tv =
1053 dynamic_pointer_cast<pv::views::trace::View>(main_view_);
1054 shared_ptr<Signal> main_signal =
1055 main_tv->get_signal_by_signalbase(signalbase);
1056 signal->restore_settings(main_signal->save_settings());
1057 }
1058
1059 trace_view->add_signal(signal);
1060 }
1061 }
1062 }
1063 }
1064
1065 signals_changed();
1066}
1067
1068shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1069 shared_ptr<sigrok::Channel> channel) const
1070{
1071 for (shared_ptr<data::SignalBase> sig : signalbases_) {
1072 assert(sig);
1073 if (sig->channel() == channel)
1074 return sig;
1075 }
1076 return shared_ptr<data::SignalBase>();
1077}
1078
1079void Session::sample_thread_proc(function<void (const QString)> error_handler)
1080{
1081 assert(error_handler);
1082
1083#ifdef ENABLE_FLOW
1084 pipeline_ = Pipeline::create();
1085
1086 source_ = ElementFactory::create_element("filesrc", "source");
1087 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1088
1089 pipeline_->add(source_)->add(sink_);
1090 source_->link(sink_);
1091
1092 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1093
1094 sink_->set_property("emit-signals", TRUE);
1095 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1096
1097 // Get the bus from the pipeline and add a bus watch to the default main context
1098 RefPtr<Bus> bus = pipeline_->get_bus();
1099 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1100
1101 // Start pipeline and Wait until it finished processing
1102 pipeline_done_interrupt_ = false;
1103 pipeline_->set_state(Gst::STATE_PLAYING);
1104
1105 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1106 pipeline_done_cond_.wait(pipeline_done_lock_);
1107
1108 // Let the pipeline free all resources
1109 pipeline_->set_state(Gst::STATE_NULL);
1110
1111#else
1112 if (!device_)
1113 return;
1114
1115 try {
1116 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1117 } catch (Error& e) {
1118 cur_samplerate_ = 0;
1119 }
1120
1121 out_of_memory_ = false;
1122
1123 {
1124 lock_guard<recursive_mutex> lock(data_mutex_);
1125 cur_logic_segment_.reset();
1126 cur_analog_segments_.clear();
1127 }
1128 highest_segment_id_ = -1;
1129 frame_began_ = false;
1130
1131 try {
1132 device_->start();
1133 } catch (Error& e) {
1134 error_handler(e.what());
1135 return;
1136 }
1137
1138 set_capture_state(device_->session()->trigger() ?
1139 AwaitingTrigger : Running);
1140
1141 try {
1142 device_->run();
1143 } catch (Error& e) {
1144 error_handler(e.what());
1145 set_capture_state(Stopped);
1146 return;
1147 } catch (QString& e) {
1148 error_handler(e);
1149 set_capture_state(Stopped);
1150 return;
1151 }
1152
1153 set_capture_state(Stopped);
1154
1155 // Confirm that SR_DF_END was received
1156 if (cur_logic_segment_)
1157 qDebug() << "WARNING: SR_DF_END was not received.";
1158#endif
1159
1160 // Optimize memory usage
1161 free_unused_memory();
1162
1163 // We now have unsaved data unless we just "captured" from a file
1164 shared_ptr<devices::File> file_device =
1165 dynamic_pointer_cast<devices::File>(device_);
1166
1167 if (!file_device)
1168 data_saved_ = false;
1169
1170 if (out_of_memory_)
1171 error_handler(tr("Out of memory, acquisition stopped."));
1172}
1173
1174void Session::free_unused_memory()
1175{
1176 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1177 const vector< shared_ptr<data::Segment> > segments = data->segments();
1178
1179 for (const shared_ptr<data::Segment>& segment : segments)
1180 segment->free_unused_memory();
1181 }
1182}
1183
1184void Session::signal_new_segment()
1185{
1186 int new_segment_id = 0;
1187
1188 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1189
1190 // Determine new frame/segment number, assuming that all
1191 // signals have the same number of frames/segments
1192 if (cur_logic_segment_) {
1193 new_segment_id = logic_data_->get_segment_count() - 1;
1194 } else {
1195 shared_ptr<sigrok::Channel> any_channel =
1196 (*cur_analog_segments_.begin()).first;
1197
1198 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1199 assert(base);
1200
1201 shared_ptr<data::Analog> data(base->analog_data());
1202 assert(data);
1203
1204 new_segment_id = data->get_segment_count() - 1;
1205 }
1206 }
1207
1208 if (new_segment_id > highest_segment_id_) {
1209 highest_segment_id_ = new_segment_id;
1210 new_segment(highest_segment_id_);
1211 }
1212}
1213
1214void Session::signal_segment_completed()
1215{
1216 int segment_id = 0;
1217
1218 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1219 // We only care about analog and logic channels, not derived ones
1220 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1221 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1222 break;
1223 }
1224
1225 if (signalbase->type() == data::SignalBase::LogicChannel) {
1226 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1227 break;
1228 }
1229 }
1230
1231 if (segment_id >= 0)
1232 segment_completed(segment_id);
1233}
1234
1235#ifdef ENABLE_FLOW
1236bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1237{
1238 (void)bus;
1239
1240 if ((message->get_source() == pipeline_) && \
1241 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1242 pipeline_done_cond_.notify_one();
1243
1244 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1245
1246 return true;
1247}
1248
1249Gst::FlowReturn Session::on_gst_new_sample()
1250{
1251 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1252 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1253
1254 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1255 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1256 Gst::MapInfo mapinfo;
1257 buf_mem->map(mapinfo, Gst::MAP_READ);
1258
1259 shared_ptr<sigrok::Packet> logic_packet =
1260 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1261
1262 try {
1263 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1264 } catch (bad_alloc&) {
1265 out_of_memory_ = true;
1266 device_->stop();
1267 buf_mem->unmap(mapinfo);
1268 return Gst::FLOW_ERROR;
1269 }
1270
1271 buf_mem->unmap(mapinfo);
1272 }
1273
1274 return Gst::FLOW_OK;
1275}
1276#endif
1277
1278void Session::feed_in_header()
1279{
1280 // Nothing to do here for now
1281}
1282
1283void Session::feed_in_meta(shared_ptr<Meta> meta)
1284{
1285 for (auto& entry : meta->config()) {
1286 switch (entry.first->id()) {
1287 case SR_CONF_SAMPLERATE:
1288 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1289 break;
1290 default:
1291 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1292 break;
1293 }
1294 }
1295
1296 signals_changed();
1297}
1298
1299void Session::feed_in_trigger()
1300{
1301 // The channel containing most samples should be most accurate
1302 uint64_t sample_count = 0;
1303
1304 {
1305 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1306 assert(d);
1307 uint64_t temp_count = 0;
1308
1309 const vector< shared_ptr<pv::data::Segment> > segments =
1310 d->segments();
1311 for (const shared_ptr<pv::data::Segment> &s : segments)
1312 temp_count += s->get_sample_count();
1313
1314 if (temp_count > sample_count)
1315 sample_count = temp_count;
1316 }
1317 }
1318
1319 uint32_t segment_id = 0; // Default segment when no frames are used
1320
1321 // If a frame began, we'd ideally be able to use the highest segment ID for
1322 // the trigger. However, as new segments are only created when logic or
1323 // analog data comes in, this doesn't work if the trigger appears right
1324 // after the beginning of the frame, before any sample data.
1325 // For this reason, we use highest segment ID + 1 if no sample data came in
1326 // yet and the highest segment ID otherwise.
1327 if (frame_began_) {
1328 segment_id = highest_segment_id_;
1329 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1330 segment_id++;
1331 }
1332
1333 // TODO Create timestamp from segment start time + segment's current sample count
1334 util::Timestamp timestamp = sample_count / get_samplerate();
1335 trigger_list_.emplace_back(segment_id, timestamp);
1336 trigger_event(segment_id, timestamp);
1337}
1338
1339void Session::feed_in_frame_begin()
1340{
1341 frame_began_ = true;
1342}
1343
1344void Session::feed_in_frame_end()
1345{
1346 if (!frame_began_)
1347 return;
1348
1349 {
1350 lock_guard<recursive_mutex> lock(data_mutex_);
1351
1352 if (cur_logic_segment_)
1353 cur_logic_segment_->set_complete();
1354
1355 for (auto& entry : cur_analog_segments_) {
1356 shared_ptr<data::AnalogSegment> segment = entry.second;
1357 segment->set_complete();
1358 }
1359
1360 cur_logic_segment_.reset();
1361 cur_analog_segments_.clear();
1362 }
1363
1364 frame_began_ = false;
1365
1366 signal_segment_completed();
1367}
1368
1369void Session::feed_in_logic(shared_ptr<Logic> logic)
1370{
1371 if (logic->data_length() == 0) {
1372 qDebug() << "WARNING: Received logic packet with 0 samples.";
1373 return;
1374 }
1375
1376 if (logic->unit_size() > 8)
1377 throw QString(tr("Can't handle more than 64 logic channels."));
1378
1379 if (!cur_samplerate_)
1380 try {
1381 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1382 } catch (Error& e) {
1383 // Do nothing
1384 }
1385
1386 lock_guard<recursive_mutex> lock(data_mutex_);
1387
1388 if (!logic_data_) {
1389 // The only reason logic_data_ would not have been created is
1390 // if it was not possible to determine the signals when the
1391 // device was created.
1392 update_signals();
1393 }
1394
1395 if (!cur_logic_segment_) {
1396 // This could be the first packet after a trigger
1397 set_capture_state(Running);
1398
1399 // Create a new data segment
1400 cur_logic_segment_ = make_shared<data::LogicSegment>(
1401 *logic_data_, logic_data_->get_segment_count(),
1402 logic->unit_size(), cur_samplerate_);
1403 logic_data_->push_segment(cur_logic_segment_);
1404
1405 signal_new_segment();
1406 }
1407
1408 cur_logic_segment_->append_payload(logic);
1409
1410 data_received();
1411}
1412
1413void Session::feed_in_analog(shared_ptr<Analog> analog)
1414{
1415 if (analog->num_samples() == 0) {
1416 qDebug() << "WARNING: Received analog packet with 0 samples.";
1417 return;
1418 }
1419
1420 if (!cur_samplerate_)
1421 try {
1422 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1423 } catch (Error& e) {
1424 // Do nothing
1425 }
1426
1427 lock_guard<recursive_mutex> lock(data_mutex_);
1428
1429 const vector<shared_ptr<Channel>> channels = analog->channels();
1430 bool sweep_beginning = false;
1431
1432 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1433 analog->get_data_as_float(data.get());
1434
1435 if (signalbases_.empty())
1436 update_signals();
1437
1438 float *channel_data = data.get();
1439 for (auto& channel : channels) {
1440 shared_ptr<data::AnalogSegment> segment;
1441
1442 // Try to get the segment of the channel
1443 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1444 iterator iter = cur_analog_segments_.find(channel);
1445 if (iter != cur_analog_segments_.end())
1446 segment = (*iter).second;
1447 else {
1448 // If no segment was found, this means we haven't
1449 // created one yet. i.e. this is the first packet
1450 // in the sweep containing this segment.
1451 sweep_beginning = true;
1452
1453 // Find the analog data associated with the channel
1454 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1455 assert(base);
1456
1457 shared_ptr<data::Analog> data(base->analog_data());
1458 assert(data);
1459
1460 // Create a segment, keep it in the maps of channels
1461 segment = make_shared<data::AnalogSegment>(
1462 *data, data->get_segment_count(), cur_samplerate_);
1463 cur_analog_segments_[channel] = segment;
1464
1465 // Push the segment into the analog data.
1466 data->push_segment(segment);
1467
1468 signal_new_segment();
1469 }
1470
1471 assert(segment);
1472
1473 // Append the samples in the segment
1474 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1475 channels.size());
1476 }
1477
1478 if (sweep_beginning) {
1479 // This could be the first packet after a trigger
1480 set_capture_state(Running);
1481 }
1482
1483 data_received();
1484}
1485
1486void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1487 shared_ptr<Packet> packet)
1488{
1489 (void)device;
1490
1491 assert(device);
1492 assert(device == device_->device());
1493 assert(packet);
1494
1495 switch (packet->type()->id()) {
1496 case SR_DF_HEADER:
1497 feed_in_header();
1498 break;
1499
1500 case SR_DF_META:
1501 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1502 break;
1503
1504 case SR_DF_TRIGGER:
1505 feed_in_trigger();
1506 break;
1507
1508 case SR_DF_LOGIC:
1509 try {
1510 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1511 } catch (bad_alloc&) {
1512 out_of_memory_ = true;
1513 device_->stop();
1514 }
1515 break;
1516
1517 case SR_DF_ANALOG:
1518 try {
1519 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1520 } catch (bad_alloc&) {
1521 out_of_memory_ = true;
1522 device_->stop();
1523 }
1524 break;
1525
1526 case SR_DF_FRAME_BEGIN:
1527 feed_in_frame_begin();
1528 break;
1529
1530 case SR_DF_FRAME_END:
1531 feed_in_frame_end();
1532 break;
1533
1534 case SR_DF_END:
1535 // Strictly speaking, this is performed when a frame end marker was
1536 // received, so there's no point doing this again. However, not all
1537 // devices use frames, and for those devices, we need to do it here.
1538 {
1539 lock_guard<recursive_mutex> lock(data_mutex_);
1540
1541 if (cur_logic_segment_)
1542 cur_logic_segment_->set_complete();
1543
1544 for (auto& entry : cur_analog_segments_) {
1545 shared_ptr<data::AnalogSegment> segment = entry.second;
1546 segment->set_complete();
1547 }
1548
1549 cur_logic_segment_.reset();
1550 cur_analog_segments_.clear();
1551 }
1552 break;
1553
1554 default:
1555 break;
1556 }
1557}
1558
1559void Session::on_data_saved()
1560{
1561 data_saved_ = true;
1562}
1563
1564#ifdef ENABLE_DECODE
1565void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1566{
1567 assert(decoders.size() > 0);
1568
1569 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1570
1571 if (signal)
1572 for (unsigned int i = 0; i < decoders.size(); i++) {
1573 const srd_decoder* d = decoders[i];
1574 signal->stack_decoder(d, !(i < decoders.size() - 1));
1575 }
1576}
1577#endif
1578
1579} // namespace pv