2 * This file is part of the PulseView project.
4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
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.
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.
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
22 // Windows: Avoid boost/thread namespace pollution (which includes windows.h).
26 #include <boost/thread/locks.hpp>
27 #include <boost/thread/shared_mutex.hpp>
30 #include <libsigrokdecode/libsigrokdecode.h>
33 #include "session.hpp"
35 #include "devicemanager.hpp"
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"
45 #include "devices/hardwaredevice.hpp"
46 #include "devices/sessionfile.hpp"
48 #include "view/analogsignal.hpp"
49 #include "view/decodetrace.hpp"
50 #include "view/logicsignal.hpp"
60 #include <libsigrokcxx/libsigrokcxx.hpp>
62 using boost::shared_lock;
63 using boost::shared_mutex;
64 using boost::unique_lock;
66 using std::dynamic_pointer_cast;
68 using std::lock_guard;
72 using std::recursive_mutex;
74 using std::shared_ptr;
76 using std::unordered_set;
80 using sigrok::Channel;
81 using sigrok::ChannelType;
82 using sigrok::ConfigKey;
83 using sigrok::DatafeedCallbackFunction;
89 using sigrok::PacketPayload;
90 using sigrok::Session;
91 using sigrok::SessionDevice;
93 using Glib::VariantBase;
97 Session::Session(DeviceManager &device_manager) :
98 device_manager_(device_manager),
99 capture_state_(Stopped),
106 // Stop and join to the thread
110 DeviceManager& Session::device_manager()
112 return device_manager_;
115 const DeviceManager& Session::device_manager() const
117 return device_manager_;
120 shared_ptr<sigrok::Session> Session::session() const
123 return shared_ptr<sigrok::Session>();
124 return device_->session();
127 shared_ptr<devices::Device> Session::device() const
132 void Session::set_device(shared_ptr<devices::Device> device)
136 // Ensure we are not capturing before setting the device
144 // Remove all stored data
147 shared_lock<shared_mutex> lock(signals_mutex_);
148 for (const shared_ptr<data::SignalData> d : all_signal_data_)
151 all_signal_data_.clear();
152 cur_logic_segment_.reset();
154 for (auto entry : cur_analog_segments_) {
155 shared_ptr<sigrok::Channel>(entry.first).reset();
156 shared_ptr<data::AnalogSegment>(entry.second).reset();
160 decode_traces_.clear();
164 device_ = std::move(device);
168 } catch (const QString &e) {
174 device_->session()->add_datafeed_callback([=]
175 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
176 data_feed_in(device, packet);
183 void Session::set_default_device()
185 const list< shared_ptr<devices::HardwareDevice> > &devices =
186 device_manager_.devices();
191 // Try and find the demo device and select that by default
192 const auto iter = std::find_if(devices.begin(), devices.end(),
193 [] (const shared_ptr<devices::HardwareDevice> &d) {
194 return d->hardware_device()->driver()->name() ==
196 set_device((iter == devices.end()) ? devices.front() : *iter);
199 Session::capture_state Session::get_capture_state() const
201 lock_guard<mutex> lock(sampling_mutex_);
202 return capture_state_;
205 void Session::start_capture(function<void (const QString)> error_handler)
208 error_handler(tr("No active device set, can't start acquisition."));
214 // Check that at least one channel is enabled
215 const shared_ptr<sigrok::Device> sr_dev = device_->device();
217 const auto channels = sr_dev->channels();
218 if (!std::any_of(channels.begin(), channels.end(),
219 [](shared_ptr<Channel> channel) {
220 return channel->enabled(); })) {
221 error_handler(tr("No channels enabled."));
228 shared_lock<shared_mutex> lock(signals_mutex_);
229 for (const shared_ptr<data::SignalData> d : all_signal_data_)
234 sampling_thread_ = std::thread(
235 &Session::sample_thread_proc, this, error_handler);
238 void Session::stop_capture()
240 if (get_capture_state() != Stopped)
243 // Check that sampling stopped
244 if (sampling_thread_.joinable())
245 sampling_thread_.join();
248 double Session::get_samplerate() const
250 double samplerate = 0.0;
253 shared_lock<shared_mutex> lock(signals_mutex_);
254 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
256 const vector< shared_ptr<pv::data::Segment> > segments =
258 for (const shared_ptr<pv::data::Segment> &s : segments)
259 samplerate = std::max(samplerate, s->samplerate());
262 // If there is no sample rate given we use samples as unit
263 if (samplerate == 0.0)
269 const unordered_set< shared_ptr<view::Signal> > Session::signals() const
271 shared_lock<shared_mutex> lock(signals_mutex_);
276 bool Session::add_decoder(srd_decoder *const dec)
278 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
279 shared_ptr<data::DecoderStack> decoder_stack;
282 lock_guard<boost::shared_mutex> lock(signals_mutex_);
284 // Create the decoder
285 decoder_stack = shared_ptr<data::DecoderStack>(
286 new data::DecoderStack(*this, dec));
288 // Make a list of all the channels
289 std::vector<const srd_channel*> all_channels;
290 for (const GSList *i = dec->channels; i; i = i->next)
291 all_channels.push_back((const srd_channel*)i->data);
292 for (const GSList *i = dec->opt_channels; i; i = i->next)
293 all_channels.push_back((const srd_channel*)i->data);
295 // Auto select the initial channels
296 for (const srd_channel *pdch : all_channels)
297 for (shared_ptr<view::Signal> s : signals_) {
298 shared_ptr<view::LogicSignal> l =
299 dynamic_pointer_cast<view::LogicSignal>(s);
300 if (l && QString::fromUtf8(pdch->name).
302 s->base()->name().toLower()))
306 assert(decoder_stack);
307 assert(!decoder_stack->stack().empty());
308 assert(decoder_stack->stack().front());
309 decoder_stack->stack().front()->set_channels(channels);
311 // Create the decode signal
312 shared_ptr<data::SignalBase> signalbase =
313 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
315 shared_ptr<view::DecodeTrace> d(
316 new view::DecodeTrace(*this, signalbase, decoder_stack,
317 decode_traces_.size()));
318 decode_traces_.push_back(d);
319 } catch (std::runtime_error e) {
325 // Do an initial decode
326 decoder_stack->begin_decode();
331 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
333 shared_lock<shared_mutex> lock(signals_mutex_);
334 return decode_traces_;
337 void Session::remove_decode_signal(view::DecodeTrace *signal)
339 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
340 if ((*i).get() == signal) {
341 decode_traces_.erase(i);
348 void Session::set_capture_state(capture_state state)
353 lock_guard<mutex> lock(sampling_mutex_);
354 changed = capture_state_ != state;
355 capture_state_ = state;
359 capture_state_changed(state);
362 void Session::update_signals()
370 lock_guard<recursive_mutex> lock(data_mutex_);
372 const shared_ptr<sigrok::Device> sr_dev = device_->device();
379 // Detect what data types we will receive
380 auto channels = sr_dev->channels();
381 unsigned int logic_channel_count = std::count_if(
382 channels.begin(), channels.end(),
383 [] (shared_ptr<Channel> channel) {
384 return channel->type() == ChannelType::LOGIC; });
386 // Create data containers for the logic data segments
388 lock_guard<recursive_mutex> data_lock(data_mutex_);
390 if (logic_channel_count == 0) {
392 } else if (!logic_data_ ||
393 logic_data_->num_channels() != logic_channel_count) {
394 logic_data_.reset(new data::Logic(
395 logic_channel_count));
400 // Make the Signals list
402 unique_lock<shared_mutex> lock(signals_mutex_);
404 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
407 for (auto channel : sr_dev->channels()) {
408 shared_ptr<data::SignalBase> signalbase;
409 shared_ptr<view::Signal> signal;
411 // Find the channel in the old signals
412 const auto iter = std::find_if(
413 prev_sigs.cbegin(), prev_sigs.cend(),
414 [&](const shared_ptr<view::Signal> &s) {
415 return s->base()->channel() == channel;
417 if (iter != prev_sigs.end()) {
418 // Copy the signal from the old set to the new
421 // Create a new signal
422 signalbase = shared_ptr<data::SignalBase>(
423 new data::SignalBase(channel));
425 switch(channel->type()->id()) {
426 case SR_CHANNEL_LOGIC:
427 signalbase->set_data(logic_data_);
428 signal = shared_ptr<view::Signal>(
429 new view::LogicSignal(*this,
430 device_, signalbase));
431 all_signal_data_.insert(logic_data_);
432 signalbases_.insert(signalbase);
435 case SR_CHANNEL_ANALOG:
437 shared_ptr<data::Analog> data(new data::Analog());
438 signalbase->set_data(data);
439 signal = shared_ptr<view::Signal>(
440 new view::AnalogSignal(
442 all_signal_data_.insert(data);
443 signalbases_.insert(signalbase);
454 signals_.insert(signal);
461 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
462 shared_ptr<sigrok::Channel> channel) const
464 for (shared_ptr<data::SignalBase> sig : signalbases_) {
466 if (sig->channel() == channel)
469 return shared_ptr<data::SignalBase>();
472 void Session::sample_thread_proc(function<void (const QString)> error_handler)
474 assert(error_handler);
479 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
481 out_of_memory_ = false;
486 error_handler(e.what());
490 set_capture_state(device_->session()->trigger() ?
491 AwaitingTrigger : Running);
494 set_capture_state(Stopped);
496 // Confirm that SR_DF_END was received
497 if (cur_logic_segment_) {
498 qDebug("SR_DF_END was not received.");
503 error_handler(tr("Out of memory, acquisition stopped."));
506 void Session::feed_in_header()
508 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
511 void Session::feed_in_meta(shared_ptr<Meta> meta)
513 for (auto entry : meta->config()) {
514 switch (entry.first->id()) {
515 case SR_CONF_SAMPLERATE:
516 // We can't rely on the header to always contain the sample rate,
517 // so in case it's supplied via a meta packet, we use it.
518 if (!cur_samplerate_)
519 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
521 /// @todo handle samplerate changes
524 // Unknown metadata is not an error.
532 void Session::feed_in_trigger()
534 // The channel containing most samples should be most accurate
535 uint64_t sample_count = 0;
538 shared_lock<shared_mutex> lock(signals_mutex_);
539 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
541 uint64_t temp_count = 0;
543 const vector< shared_ptr<pv::data::Segment> > segments =
545 for (const shared_ptr<pv::data::Segment> &s : segments)
546 temp_count += s->get_sample_count();
548 if (temp_count > sample_count)
549 sample_count = temp_count;
553 trigger_event(sample_count / get_samplerate());
556 void Session::feed_in_frame_begin()
558 if (cur_logic_segment_ || !cur_analog_segments_.empty())
562 void Session::feed_in_logic(shared_ptr<Logic> logic)
564 lock_guard<recursive_mutex> lock(data_mutex_);
566 const size_t sample_count = logic->data_length() / logic->unit_size();
569 // The only reason logic_data_ would not have been created is
570 // if it was not possible to determine the signals when the
571 // device was created.
575 if (!cur_logic_segment_) {
576 // This could be the first packet after a trigger
577 set_capture_state(Running);
579 // Create a new data segment
580 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
581 new data::LogicSegment(
582 logic, cur_samplerate_, sample_count));
583 logic_data_->push_segment(cur_logic_segment_);
585 // @todo Putting this here means that only listeners querying
586 // for logic will be notified. Currently the only user of
587 // frame_began is DecoderStack, but in future we need to signal
588 // this after both analog and logic sweeps have begun.
591 // Append to the existing data segment
592 cur_logic_segment_->append_payload(logic);
598 void Session::feed_in_analog(shared_ptr<Analog> analog)
600 lock_guard<recursive_mutex> lock(data_mutex_);
602 const vector<shared_ptr<Channel>> channels = analog->channels();
603 const unsigned int channel_count = channels.size();
604 const size_t sample_count = analog->num_samples() / channel_count;
605 const float *data = static_cast<const float *>(analog->data_pointer());
606 bool sweep_beginning = false;
608 if (signals_.empty())
611 for (auto channel : channels) {
612 shared_ptr<data::AnalogSegment> segment;
614 // Try to get the segment of the channel
615 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
616 iterator iter = cur_analog_segments_.find(channel);
617 if (iter != cur_analog_segments_.end())
618 segment = (*iter).second;
620 // If no segment was found, this means we haven't
621 // created one yet. i.e. this is the first packet
622 // in the sweep containing this segment.
623 sweep_beginning = true;
625 // Create a segment, keep it in the maps of channels
626 segment = shared_ptr<data::AnalogSegment>(
627 new data::AnalogSegment(
628 cur_samplerate_, sample_count));
629 cur_analog_segments_[channel] = segment;
631 // Find the analog data associated with the channel
632 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
635 shared_ptr<data::Analog> data(base->analog_data());
638 // Push the segment into the analog data.
639 data->push_segment(segment);
644 // Append the samples in the segment
645 segment->append_interleaved_samples(data++, sample_count,
649 if (sweep_beginning) {
650 // This could be the first packet after a trigger
651 set_capture_state(Running);
657 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
658 shared_ptr<Packet> packet)
663 assert(device == device_->device());
666 switch (packet->type()->id()) {
672 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
679 case SR_DF_FRAME_BEGIN:
680 feed_in_frame_begin();
685 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
686 } catch (std::bad_alloc) {
687 out_of_memory_ = true;
694 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
695 } catch (std::bad_alloc) {
696 out_of_memory_ = true;
704 lock_guard<recursive_mutex> lock(data_mutex_);
705 cur_logic_segment_.reset();
706 cur_analog_segments_.clear();