]> sigrok.org Git - pulseview.git/blob - pv/session.cpp
Session: Improve session robustness
[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 #ifdef ENABLE_DECODE
30 #include <libsigrokdecode/libsigrokdecode.h>
31 #endif
32
33 #include "session.hpp"
34
35 #include "devicemanager.hpp"
36
37 #include "data/analog.hpp"
38 #include "data/analogsegment.hpp"
39 #include "data/decoderstack.hpp"
40 #include "data/logic.hpp"
41 #include "data/logicsegment.hpp"
42 #include "data/decode/decoder.hpp"
43
44 #include "devices/hardwaredevice.hpp"
45 #include "devices/sessionfile.hpp"
46
47 #include "view/analogsignal.hpp"
48 #include "view/decodetrace.hpp"
49 #include "view/logicsignal.hpp"
50
51 #include <cassert>
52 #include <mutex>
53 #include <stdexcept>
54
55 #include <sys/stat.h>
56
57 #include <QDebug>
58
59 #include <libsigrokcxx/libsigrokcxx.hpp>
60
61 using boost::shared_lock;
62 using boost::shared_mutex;
63 using boost::unique_lock;
64
65 using std::dynamic_pointer_cast;
66 using std::function;
67 using std::lock_guard;
68 using std::list;
69 using std::map;
70 using std::mutex;
71 using std::recursive_mutex;
72 using std::set;
73 using std::shared_ptr;
74 using std::string;
75 using std::unordered_set;
76 using std::vector;
77
78 using sigrok::Analog;
79 using sigrok::Channel;
80 using sigrok::ChannelType;
81 using sigrok::ConfigKey;
82 using sigrok::DatafeedCallbackFunction;
83 using sigrok::Error;
84 using sigrok::Header;
85 using sigrok::Logic;
86 using sigrok::Meta;
87 using sigrok::Packet;
88 using sigrok::PacketPayload;
89 using sigrok::Session;
90 using sigrok::SessionDevice;
91
92 using Glib::VariantBase;
93 using Glib::Variant;
94
95 namespace pv {
96 Session::Session(DeviceManager &device_manager) :
97         device_manager_(device_manager),
98         capture_state_(Stopped),
99         cur_samplerate_(0)
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 void Session::set_device(shared_ptr<devices::Device> device)
132 {
133         assert(device);
134
135         // Ensure we are not capturing before setting the device
136         stop_capture();
137
138         if (device_)
139                 device_->close();
140
141         device_.reset();
142
143         // Remove all stored data
144         signals_.clear();
145         {
146                 shared_lock<shared_mutex> lock(signals_mutex_);
147                 for (const shared_ptr<data::SignalData> d : all_signal_data_)
148                         d->clear();
149         }
150         all_signal_data_.clear();
151         cur_logic_segment_.reset();
152
153         for (auto entry : cur_analog_segments_) {
154                 shared_ptr<sigrok::Channel>(entry.first).reset();
155                 shared_ptr<data::AnalogSegment>(entry.second).reset();
156         }
157
158         logic_data_.reset();
159         decode_traces_.clear();
160
161         signals_changed();
162
163         device_ = std::move(device);
164         device_->open();
165         device_->session()->add_datafeed_callback([=]
166                 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
167                         data_feed_in(device, packet);
168                 });
169
170         update_signals();
171         device_selected();
172 }
173
174 void Session::set_default_device()
175 {
176         const list< shared_ptr<devices::HardwareDevice> > &devices =
177                 device_manager_.devices();
178
179         if (devices.empty())
180                 return;
181
182         // Try and find the demo device and select that by default
183         const auto iter = std::find_if(devices.begin(), devices.end(),
184                 [] (const shared_ptr<devices::HardwareDevice> &d) {
185                         return d->hardware_device()->driver()->name() ==
186                         "demo"; });
187         set_device((iter == devices.end()) ? devices.front() : *iter);
188 }
189
190 Session::capture_state Session::get_capture_state() const
191 {
192         lock_guard<mutex> lock(sampling_mutex_);
193         return capture_state_;
194 }
195
196 void Session::start_capture(function<void (const QString)> error_handler)
197 {
198         if (!device_) {
199                 error_handler(tr("No active device set, can't start acquisition."));
200                 return;
201         }
202
203         stop_capture();
204
205         // Check that at least one channel is enabled
206         const shared_ptr<sigrok::Device> sr_dev = device_->device();
207         if (sr_dev) {
208                 const auto channels = sr_dev->channels();
209                 if (!std::any_of(channels.begin(), channels.end(),
210                         [](shared_ptr<Channel> channel) {
211                                 return channel->enabled(); })) {
212                         error_handler(tr("No channels enabled."));
213                         return;
214                 }
215         }
216
217         // Clear signal data
218         {
219                 shared_lock<shared_mutex> lock(signals_mutex_);
220                 for (const shared_ptr<data::SignalData> d : all_signal_data_)
221                         d->clear();
222         }
223
224         // Begin the session
225         sampling_thread_ = std::thread(
226                 &Session::sample_thread_proc, this, device_,
227                         error_handler);
228 }
229
230 void Session::stop_capture()
231 {
232         if (get_capture_state() != Stopped)
233                 device_->stop();
234
235         // Check that sampling stopped
236         if (sampling_thread_.joinable())
237                 sampling_thread_.join();
238 }
239
240 double Session::get_samplerate() const
241 {
242         double samplerate = 0.0;
243
244         {
245                 shared_lock<shared_mutex> lock(signals_mutex_);
246                 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
247                         assert(d);
248                         const vector< shared_ptr<pv::data::Segment> > segments =
249                                 d->segments();
250                         for (const shared_ptr<pv::data::Segment> &s : segments)
251                                 samplerate = std::max(samplerate, s->samplerate());
252                 }
253         }
254         // If there is no sample rate given we use samples as unit
255         if (samplerate == 0.0)
256                 samplerate = 1.0;
257
258         return samplerate;
259 }
260
261 const unordered_set< shared_ptr<view::Signal> > Session::signals() const
262 {
263         shared_lock<shared_mutex> lock(signals_mutex_);
264         return signals_;
265 }
266
267 #ifdef ENABLE_DECODE
268 bool Session::add_decoder(srd_decoder *const dec)
269 {
270         map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
271         shared_ptr<data::DecoderStack> decoder_stack;
272
273         try {
274                 lock_guard<boost::shared_mutex> lock(signals_mutex_);
275
276                 // Create the decoder
277                 decoder_stack = shared_ptr<data::DecoderStack>(
278                         new data::DecoderStack(*this, dec));
279
280                 // Make a list of all the channels
281                 std::vector<const srd_channel*> all_channels;
282                 for (const GSList *i = dec->channels; i; i = i->next)
283                         all_channels.push_back((const srd_channel*)i->data);
284                 for (const GSList *i = dec->opt_channels; i; i = i->next)
285                         all_channels.push_back((const srd_channel*)i->data);
286
287                 // Auto select the initial channels
288                 for (const srd_channel *pdch : all_channels)
289                         for (shared_ptr<view::Signal> s : signals_) {
290                                 shared_ptr<view::LogicSignal> l =
291                                         dynamic_pointer_cast<view::LogicSignal>(s);
292                                 if (l && QString::fromUtf8(pdch->name).
293                                         toLower().contains(
294                                         l->name().toLower()))
295                                         channels[pdch] = l;
296                         }
297
298                 assert(decoder_stack);
299                 assert(!decoder_stack->stack().empty());
300                 assert(decoder_stack->stack().front());
301                 decoder_stack->stack().front()->set_channels(channels);
302
303                 // Create the decode signal
304                 shared_ptr<view::DecodeTrace> d(
305                         new view::DecodeTrace(*this, decoder_stack,
306                                 decode_traces_.size()));
307                 decode_traces_.push_back(d);
308         } catch (std::runtime_error e) {
309                 return false;
310         }
311
312         signals_changed();
313
314         // Do an initial decode
315         decoder_stack->begin_decode();
316
317         return true;
318 }
319
320 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
321 {
322         shared_lock<shared_mutex> lock(signals_mutex_);
323         return decode_traces_;
324 }
325
326 void Session::remove_decode_signal(view::DecodeTrace *signal)
327 {
328         for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
329                 if ((*i).get() == signal) {
330                         decode_traces_.erase(i);
331                         signals_changed();
332                         return;
333                 }
334 }
335 #endif
336
337 void Session::set_capture_state(capture_state state)
338 {
339         bool changed;
340
341         {
342                 lock_guard<mutex> lock(sampling_mutex_);
343                 changed = capture_state_ != state;
344                 capture_state_ = state;
345         }
346
347         if (changed)
348                 capture_state_changed(state);
349 }
350
351 void Session::update_signals()
352 {
353         if (!device_) {
354                 signals_.clear();
355                 logic_data_.reset();
356                 return;
357         }
358
359         lock_guard<recursive_mutex> lock(data_mutex_);
360
361         const shared_ptr<sigrok::Device> sr_dev = device_->device();
362         if (!sr_dev) {
363                 signals_.clear();
364                 logic_data_.reset();
365                 return;
366         }
367
368         // Detect what data types we will receive
369         auto channels = sr_dev->channels();
370         unsigned int logic_channel_count = std::count_if(
371                 channels.begin(), channels.end(),
372                 [] (shared_ptr<Channel> channel) {
373                         return channel->type() == ChannelType::LOGIC; });
374
375         // Create data containers for the logic data segments
376         {
377                 lock_guard<recursive_mutex> data_lock(data_mutex_);
378
379                 if (logic_channel_count == 0) {
380                         logic_data_.reset();
381                 } else if (!logic_data_ ||
382                         logic_data_->num_channels() != logic_channel_count) {
383                         logic_data_.reset(new data::Logic(
384                                 logic_channel_count));
385                         assert(logic_data_);
386                 }
387         }
388
389         // Make the Signals list
390         {
391                 unique_lock<shared_mutex> lock(signals_mutex_);
392
393                 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
394                 signals_.clear();
395
396                 for (auto channel : sr_dev->channels()) {
397                         shared_ptr<view::Signal> signal;
398
399                         // Find the channel in the old signals
400                         const auto iter = std::find_if(
401                                 prev_sigs.cbegin(), prev_sigs.cend(),
402                                 [&](const shared_ptr<view::Signal> &s) {
403                                         return s->channel() == channel;
404                                 });
405                         if (iter != prev_sigs.end()) {
406                                 // Copy the signal from the old set to the new
407                                 signal = *iter;
408                                 auto logic_signal = dynamic_pointer_cast<
409                                         view::LogicSignal>(signal);
410                                 if (logic_signal)
411                                         logic_signal->set_logic_data(
412                                                 logic_data_);
413                         } else {
414                                 // Create a new signal
415                                 switch(channel->type()->id()) {
416                                 case SR_CHANNEL_LOGIC:
417                                         signal = shared_ptr<view::Signal>(
418                                                 new view::LogicSignal(*this,
419                                                         device_, channel,
420                                                         logic_data_));
421                                         all_signal_data_.insert(logic_data_);
422                                         break;
423
424                                 case SR_CHANNEL_ANALOG:
425                                 {
426                                         shared_ptr<data::Analog> data(
427                                                 new data::Analog());
428                                         signal = shared_ptr<view::Signal>(
429                                                 new view::AnalogSignal(
430                                                         *this, channel, data));
431                                         all_signal_data_.insert(data);
432                                         break;
433                                 }
434
435                                 default:
436                                         assert(0);
437                                         break;
438                                 }
439                         }
440
441                         assert(signal);
442                         signals_.insert(signal);
443                 }
444         }
445
446         signals_changed();
447 }
448
449 shared_ptr<view::Signal> Session::signal_from_channel(
450         shared_ptr<Channel> channel) const
451 {
452         lock_guard<boost::shared_mutex> lock(signals_mutex_);
453         for (shared_ptr<view::Signal> sig : signals_) {
454                 assert(sig);
455                 if (sig->channel() == channel)
456                         return sig;
457         }
458         return shared_ptr<view::Signal>();
459 }
460
461 void Session::sample_thread_proc(shared_ptr<devices::Device> device,
462         function<void (const QString)> error_handler)
463 {
464         assert(device);
465         assert(error_handler);
466
467         if (!device_)
468                 return;
469
470         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
471
472         out_of_memory_ = false;
473
474         try {
475                 device_->start();
476         } catch (Error e) {
477                 error_handler(e.what());
478                 return;
479         }
480
481         set_capture_state(device_->session()->trigger() ?
482                 AwaitingTrigger : Running);
483
484         device_->run();
485         set_capture_state(Stopped);
486
487         // Confirm that SR_DF_END was received
488         if (cur_logic_segment_) {
489                 qDebug("SR_DF_END was not received.");
490                 assert(0);
491         }
492
493         if (out_of_memory_)
494                 error_handler(tr("Out of memory, acquisition stopped."));
495 }
496
497 void Session::feed_in_header()
498 {
499         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
500 }
501
502 void Session::feed_in_meta(shared_ptr<Meta> meta)
503 {
504         for (auto entry : meta->config()) {
505                 switch (entry.first->id()) {
506                 case SR_CONF_SAMPLERATE:
507                         // We can't rely on the header to always contain the sample rate,
508                         // so in case it's supplied via a meta packet, we use it.
509                         if (!cur_samplerate_)
510                                 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
511
512                         /// @todo handle samplerate changes
513                         break;
514                 default:
515                         // Unknown metadata is not an error.
516                         break;
517                 }
518         }
519
520         signals_changed();
521 }
522
523 void Session::feed_in_trigger()
524 {
525         // The channel containing most samples should be most accurate
526         uint64_t sample_count = 0;
527
528         {
529                 shared_lock<shared_mutex> lock(signals_mutex_);
530                 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
531                         assert(d);
532                         uint64_t temp_count = 0;
533
534                         const vector< shared_ptr<pv::data::Segment> > segments =
535                                 d->segments();
536                         for (const shared_ptr<pv::data::Segment> &s : segments)
537                                 temp_count += s->get_sample_count();
538
539                         if (temp_count > sample_count)
540                                 sample_count = temp_count;
541                 }
542         }
543
544         trigger_event(sample_count / get_samplerate());
545 }
546
547 void Session::feed_in_frame_begin()
548 {
549         if (cur_logic_segment_ || !cur_analog_segments_.empty())
550                 frame_began();
551 }
552
553 void Session::feed_in_logic(shared_ptr<Logic> logic)
554 {
555         lock_guard<recursive_mutex> lock(data_mutex_);
556
557         const size_t sample_count = logic->data_length() / logic->unit_size();
558
559         if (!logic_data_) {
560                 // The only reason logic_data_ would not have been created is
561                 // if it was not possible to determine the signals when the
562                 // device was created.
563                 update_signals();
564         }
565
566         if (!cur_logic_segment_) {
567                 // This could be the first packet after a trigger
568                 set_capture_state(Running);
569
570                 // Create a new data segment
571                 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
572                         new data::LogicSegment(
573                                 logic, cur_samplerate_, sample_count));
574                 logic_data_->push_segment(cur_logic_segment_);
575
576                 // @todo Putting this here means that only listeners querying
577                 // for logic will be notified. Currently the only user of
578                 // frame_began is DecoderStack, but in future we need to signal
579                 // this after both analog and logic sweeps have begun.
580                 frame_began();
581         } else {
582                 // Append to the existing data segment
583                 cur_logic_segment_->append_payload(logic);
584         }
585
586         data_received();
587 }
588
589 void Session::feed_in_analog(shared_ptr<Analog> analog)
590 {
591         lock_guard<recursive_mutex> lock(data_mutex_);
592
593         const vector<shared_ptr<Channel>> channels = analog->channels();
594         const unsigned int channel_count = channels.size();
595         const size_t sample_count = analog->num_samples() / channel_count;
596         const float *data = static_cast<const float *>(analog->data_pointer());
597         bool sweep_beginning = false;
598
599         if (signals_.empty())
600                 update_signals();
601
602         for (auto channel : channels) {
603                 shared_ptr<data::AnalogSegment> segment;
604
605                 // Try to get the segment of the channel
606                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
607                         iterator iter = cur_analog_segments_.find(channel);
608                 if (iter != cur_analog_segments_.end())
609                         segment = (*iter).second;
610                 else {
611                         // If no segment was found, this means we haven't
612                         // created one yet. i.e. this is the first packet
613                         // in the sweep containing this segment.
614                         sweep_beginning = true;
615
616                         // Create a segment, keep it in the maps of channels
617                         segment = shared_ptr<data::AnalogSegment>(
618                                 new data::AnalogSegment(
619                                         cur_samplerate_, sample_count));
620                         cur_analog_segments_[channel] = segment;
621
622                         // Find the analog data associated with the channel
623                         shared_ptr<view::AnalogSignal> sig =
624                                 dynamic_pointer_cast<view::AnalogSignal>(
625                                         signal_from_channel(channel));
626                         assert(sig);
627
628                         shared_ptr<data::Analog> data(sig->analog_data());
629                         assert(data);
630
631                         // Push the segment into the analog data.
632                         data->push_segment(segment);
633                 }
634
635                 assert(segment);
636
637                 // Append the samples in the segment
638                 segment->append_interleaved_samples(data++, sample_count,
639                         channel_count);
640         }
641
642         if (sweep_beginning) {
643                 // This could be the first packet after a trigger
644                 set_capture_state(Running);
645         }
646
647         data_received();
648 }
649
650 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
651         shared_ptr<Packet> packet)
652 {
653         (void)device;
654
655         assert(device);
656         assert(device == device_->device());
657         assert(packet);
658
659         switch (packet->type()->id()) {
660         case SR_DF_HEADER:
661                 feed_in_header();
662                 break;
663
664         case SR_DF_META:
665                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
666                 break;
667
668         case SR_DF_TRIGGER:
669                 feed_in_trigger();
670                 break;
671
672         case SR_DF_FRAME_BEGIN:
673                 feed_in_frame_begin();
674                 break;
675
676         case SR_DF_LOGIC:
677                 try {
678                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
679                 } catch (std::bad_alloc) {
680                         out_of_memory_ = true;
681                         device_->stop();
682                 }
683                 break;
684
685         case SR_DF_ANALOG:
686                 try {
687                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
688                 } catch (std::bad_alloc) {
689                         out_of_memory_ = true;
690                         device_->stop();
691                 }
692                 break;
693
694         case SR_DF_END:
695         {
696                 {
697                         lock_guard<recursive_mutex> lock(data_mutex_);
698                         cur_logic_segment_.reset();
699                         cur_analog_segments_.clear();
700                 }
701                 frame_ended();
702                 break;
703         }
704         default:
705                 break;
706         }
707 }
708
709 } // namespace pv