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