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