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