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