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