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