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