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