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