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