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