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