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