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