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