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/decode/decoder.hpp"
44 #include "devices/hardwaredevice.hpp"
45 #include "devices/sessionfile.hpp"
47 #include "view/analogsignal.hpp"
48 #include "view/decodetrace.hpp"
49 #include "view/logicsignal.hpp"
59 #include <libsigrokcxx/libsigrokcxx.hpp>
61 using boost::shared_lock;
62 using boost::shared_mutex;
63 using boost::unique_lock;
65 using std::dynamic_pointer_cast;
67 using std::lock_guard;
71 using std::recursive_mutex;
73 using std::shared_ptr;
75 using std::unordered_set;
79 using sigrok::Channel;
80 using sigrok::ChannelType;
81 using sigrok::ConfigKey;
82 using sigrok::DatafeedCallbackFunction;
88 using sigrok::PacketPayload;
89 using sigrok::Session;
90 using sigrok::SessionDevice;
92 using Glib::VariantBase;
96 Session::Session(DeviceManager &device_manager) :
97 device_manager_(device_manager),
98 capture_state_(Stopped),
105 // Stop and join to the thread
109 DeviceManager& Session::device_manager()
111 return device_manager_;
114 const DeviceManager& Session::device_manager() const
116 return device_manager_;
119 shared_ptr<sigrok::Session> Session::session() const
122 return shared_ptr<sigrok::Session>();
123 return device_->session();
126 shared_ptr<devices::Device> Session::device() const
131 void Session::set_device(shared_ptr<devices::Device> device)
135 // Ensure we are not capturing before setting the device
145 decode_traces_.clear();
148 device_ = std::move(device);
150 device_->session()->add_datafeed_callback([=]
151 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
152 data_feed_in(device, packet);
159 void Session::set_default_device()
161 const list< shared_ptr<devices::HardwareDevice> > &devices =
162 device_manager_.devices();
167 // Try and find the demo device and select that by default
168 const auto iter = std::find_if(devices.begin(), devices.end(),
169 [] (const shared_ptr<devices::HardwareDevice> &d) {
170 return d->hardware_device()->driver()->name() ==
172 set_device((iter == devices.end()) ? devices.front() : *iter);
175 Session::capture_state Session::get_capture_state() const
177 lock_guard<mutex> lock(sampling_mutex_);
178 return capture_state_;
181 void Session::start_capture(function<void (const QString)> error_handler)
185 // Check that at least one channel is enabled
187 const shared_ptr<sigrok::Device> sr_dev = device_->device();
189 const auto channels = sr_dev->channels();
190 if (!std::any_of(channels.begin(), channels.end(),
191 [](shared_ptr<Channel> channel) {
192 return channel->enabled(); })) {
193 error_handler(tr("No channels enabled."));
199 for (const shared_ptr<data::SignalData> d : get_data())
203 sampling_thread_ = std::thread(
204 &Session::sample_thread_proc, this, device_,
208 void Session::stop_capture()
210 if (get_capture_state() != Stopped)
213 // Check that sampling stopped
214 if (sampling_thread_.joinable())
215 sampling_thread_.join();
218 set< shared_ptr<data::SignalData> > Session::get_data() const
220 shared_lock<shared_mutex> lock(signals_mutex_);
221 set< shared_ptr<data::SignalData> > data;
222 for (const shared_ptr<view::Signal> sig : signals_) {
224 data.insert(sig->data());
230 double Session::get_samplerate() const
232 double samplerate = 0.0;
234 for (const shared_ptr<pv::data::SignalData> d : get_data()) {
236 const vector< shared_ptr<pv::data::Segment> > segments =
238 for (const shared_ptr<pv::data::Segment> &s : segments)
239 samplerate = std::max(samplerate, s->samplerate());
242 // If there is no sample rate given we use samples as unit
243 if (samplerate == 0.0)
249 const unordered_set< shared_ptr<view::Signal> > Session::signals() const
251 shared_lock<shared_mutex> lock(signals_mutex_);
256 bool Session::add_decoder(srd_decoder *const dec)
258 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
259 shared_ptr<data::DecoderStack> decoder_stack;
262 lock_guard<boost::shared_mutex> lock(signals_mutex_);
264 // Create the decoder
265 decoder_stack = shared_ptr<data::DecoderStack>(
266 new data::DecoderStack(*this, dec));
268 // Make a list of all the channels
269 std::vector<const srd_channel*> all_channels;
270 for (const GSList *i = dec->channels; i; i = i->next)
271 all_channels.push_back((const srd_channel*)i->data);
272 for (const GSList *i = dec->opt_channels; i; i = i->next)
273 all_channels.push_back((const srd_channel*)i->data);
275 // Auto select the initial channels
276 for (const srd_channel *pdch : all_channels)
277 for (shared_ptr<view::Signal> s : signals_) {
278 shared_ptr<view::LogicSignal> l =
279 dynamic_pointer_cast<view::LogicSignal>(s);
280 if (l && QString::fromUtf8(pdch->name).
282 l->name().toLower()))
286 assert(decoder_stack);
287 assert(!decoder_stack->stack().empty());
288 assert(decoder_stack->stack().front());
289 decoder_stack->stack().front()->set_channels(channels);
291 // Create the decode signal
292 shared_ptr<view::DecodeTrace> d(
293 new view::DecodeTrace(*this, decoder_stack,
294 decode_traces_.size()));
295 decode_traces_.push_back(d);
296 } catch (std::runtime_error e) {
302 // Do an initial decode
303 decoder_stack->begin_decode();
308 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
310 shared_lock<shared_mutex> lock(signals_mutex_);
311 return decode_traces_;
314 void Session::remove_decode_signal(view::DecodeTrace *signal)
316 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
317 if ((*i).get() == signal) {
318 decode_traces_.erase(i);
325 void Session::set_capture_state(capture_state state)
330 lock_guard<mutex> lock(sampling_mutex_);
331 changed = capture_state_ != state;
332 capture_state_ = state;
336 capture_state_changed(state);
339 void Session::update_signals()
343 lock_guard<recursive_mutex> lock(data_mutex_);
345 const shared_ptr<sigrok::Device> sr_dev = device_->device();
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; });
359 // Create data containers for the logic data segments
361 lock_guard<recursive_mutex> data_lock(data_mutex_);
363 if (logic_channel_count == 0) {
365 } else if (!logic_data_ ||
366 logic_data_->num_channels() != logic_channel_count) {
367 logic_data_.reset(new data::Logic(
368 logic_channel_count));
373 // Make the Signals list
375 unique_lock<shared_mutex> lock(signals_mutex_);
377 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
380 for (auto channel : sr_dev->channels()) {
381 shared_ptr<view::Signal> signal;
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;
389 if (iter != prev_sigs.end()) {
390 // Copy the signal from the old set to the new
392 auto logic_signal = dynamic_pointer_cast<
393 view::LogicSignal>(signal);
395 logic_signal->set_logic_data(
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,
407 case SR_CHANNEL_ANALOG:
409 shared_ptr<data::Analog> data(
411 signal = shared_ptr<view::Signal>(
412 new view::AnalogSignal(
413 *this, channel, data));
424 signals_.insert(signal);
431 shared_ptr<view::Signal> Session::signal_from_channel(
432 shared_ptr<Channel> channel) const
434 lock_guard<boost::shared_mutex> lock(signals_mutex_);
435 for (shared_ptr<view::Signal> sig : signals_) {
437 if (sig->channel() == channel)
440 return shared_ptr<view::Signal>();
443 void Session::sample_thread_proc(shared_ptr<devices::Device> device,
444 function<void (const QString)> error_handler)
447 assert(error_handler);
451 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
453 out_of_memory_ = false;
458 error_handler(e.what());
462 set_capture_state(device_->session()->trigger() ?
463 AwaitingTrigger : Running);
466 set_capture_state(Stopped);
468 // Confirm that SR_DF_END was received
469 if (cur_logic_segment_) {
470 qDebug("SR_DF_END was not received.");
475 error_handler(tr("Out of memory, acquisition stopped."));
478 void Session::feed_in_header()
480 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
483 void Session::feed_in_meta(shared_ptr<Meta> meta)
485 for (auto entry : meta->config()) {
486 switch (entry.first->id()) {
487 case SR_CONF_SAMPLERATE:
488 // We can't rely on the header to always contain the sample rate,
489 // so in case it's supplied via a meta packet, we use it.
490 if (!cur_samplerate_)
491 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
493 /// @todo handle samplerate changes
496 // Unknown metadata is not an error.
504 void Session::feed_in_trigger()
506 // The channel containing most samples should be most accurate
507 uint64_t sample_count = 0;
509 for (const shared_ptr<pv::data::SignalData> d : get_data()) {
511 uint64_t temp_count = 0;
513 const vector< shared_ptr<pv::data::Segment> > segments =
515 for (const shared_ptr<pv::data::Segment> &s : segments)
516 temp_count += s->get_sample_count();
518 if (temp_count > sample_count)
519 sample_count = temp_count;
522 trigger_event(sample_count / get_samplerate());
525 void Session::feed_in_frame_begin()
527 if (cur_logic_segment_ || !cur_analog_segments_.empty())
531 void Session::feed_in_logic(shared_ptr<Logic> logic)
533 lock_guard<recursive_mutex> lock(data_mutex_);
535 const size_t sample_count = logic->data_length() / logic->unit_size();
538 // The only reason logic_data_ would not have been created is
539 // if it was not possible to determine the signals when the
540 // device was created.
544 if (!cur_logic_segment_) {
545 // This could be the first packet after a trigger
546 set_capture_state(Running);
548 // Create a new data segment
549 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
550 new data::LogicSegment(
551 logic, cur_samplerate_, sample_count));
552 logic_data_->push_segment(cur_logic_segment_);
554 // @todo Putting this here means that only listeners querying
555 // for logic will be notified. Currently the only user of
556 // frame_began is DecoderStack, but in future we need to signal
557 // this after both analog and logic sweeps have begun.
560 // Append to the existing data segment
561 cur_logic_segment_->append_payload(logic);
567 void Session::feed_in_analog(shared_ptr<Analog> analog)
569 lock_guard<recursive_mutex> lock(data_mutex_);
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;
577 if (signals_.empty())
580 for (auto channel : channels) {
581 shared_ptr<data::AnalogSegment> segment;
583 // Try to get the segment of the channel
584 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
585 iterator iter = cur_analog_segments_.find(channel);
586 if (iter != cur_analog_segments_.end())
587 segment = (*iter).second;
589 // If no segment was found, this means we haven't
590 // created one yet. i.e. this is the first packet
591 // in the sweep containing this segment.
592 sweep_beginning = true;
594 // Create a segment, keep it in the maps of channels
595 segment = shared_ptr<data::AnalogSegment>(
596 new data::AnalogSegment(
597 cur_samplerate_, sample_count));
598 cur_analog_segments_[channel] = segment;
600 // Find the analog data associated with the channel
601 shared_ptr<view::AnalogSignal> sig =
602 dynamic_pointer_cast<view::AnalogSignal>(
603 signal_from_channel(channel));
606 shared_ptr<data::Analog> data(sig->analog_data());
609 // Push the segment into the analog data.
610 data->push_segment(segment);
615 // Append the samples in the segment
616 segment->append_interleaved_samples(data++, sample_count,
620 if (sweep_beginning) {
621 // This could be the first packet after a trigger
622 set_capture_state(Running);
628 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
629 shared_ptr<Packet> packet)
634 assert(device == device_->device());
637 switch (packet->type()->id()) {
643 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
650 case SR_DF_FRAME_BEGIN:
651 feed_in_frame_begin();
656 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
657 } catch (std::bad_alloc) {
658 out_of_memory_ = true;
665 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
666 } catch (std::bad_alloc) {
667 out_of_memory_ = true;
675 lock_guard<recursive_mutex> lock(data_mutex_);
676 cur_logic_segment_.reset();
677 cur_analog_segments_.clear();