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 #include <libsigrokdecode/libsigrokdecode.h>
25 #include "sigsession.h"
27 #include "devicemanager.h"
28 #include "device/device.h"
30 #include "data/analog.h"
31 #include "data/analogsnapshot.h"
32 #include "data/decoderstack.h"
33 #include "data/logic.h"
34 #include "data/logicsnapshot.h"
35 #include "data/decode/decoder.h"
37 #include "view/analogsignal.h"
38 #include "view/decodetrace.h"
39 #include "view/logicsignal.h"
45 #include <boost/foreach.hpp>
51 using boost::dynamic_pointer_cast;
52 using boost::function;
53 using boost::lock_guard;
55 using boost::shared_ptr;
63 // TODO: This should not be necessary
64 SigSession* SigSession::_session = NULL;
66 SigSession::SigSession(DeviceManager &device_manager) :
67 _device_manager(device_manager),
68 _capture_state(Stopped)
70 // TODO: This should not be necessary
74 SigSession::~SigSession()
76 using pv::device::Device;
80 if (_sampling_thread.joinable())
81 _sampling_thread.join();
83 shared_ptr<Device> device(dynamic_pointer_cast<Device>(_dev_inst));
85 _device_manager.release_device(device);
87 // TODO: This should not be necessary
91 shared_ptr<device::DevInst> SigSession::get_device() const
96 void SigSession::set_device(shared_ptr<device::DevInst> dev_inst)
98 using pv::device::Device;
100 // Ensure we are not capturing before setting the device
103 shared_ptr<Device> old_device(dynamic_pointer_cast<Device>(_dev_inst));
105 _device_manager.release_device(old_device);
107 shared_ptr<Device> new_device(dynamic_pointer_cast<Device>(dev_inst));
109 _device_manager.use_device(new_device, this);
111 _dev_inst = dev_inst;
112 update_signals(dev_inst);
115 void SigSession::release_device(shared_ptr<device::DevInst> dev_inst)
119 assert(_capture_state == Stopped);
120 _dev_inst = shared_ptr<device::DevInst>();
123 void SigSession::load_file(const string &name,
124 function<void (const QString)> error_handler)
128 if (sr_session_load(name.c_str()) == SR_OK) {
129 GSList *devlist = NULL;
130 sr_session_dev_list(&devlist);
132 if (!devlist || !devlist->data ||
133 sr_session_start() != SR_OK) {
134 error_handler(tr("Failed to start session."));
138 shared_ptr<device::DevInst> dev_inst(
139 new device::Device((sr_dev_inst*)devlist->data));
140 g_slist_free(devlist);
142 _decode_traces.clear();
143 update_signals(dev_inst);
144 read_sample_rate(dev_inst->dev_inst());
146 _sampling_thread = boost::thread(
147 &SigSession::load_session_thread_proc, this,
153 if (!(in = load_input_file_format(name.c_str(),
157 _decode_traces.clear();
158 update_signals(shared_ptr<device::DevInst>(
159 new device::Device(in->sdi)));
160 read_sample_rate(in->sdi);
162 _sampling_thread = boost::thread(
163 &SigSession::load_input_thread_proc, this,
164 name, in, error_handler);
168 SigSession::capture_state SigSession::get_capture_state() const
170 lock_guard<mutex> lock(_sampling_mutex);
171 return _capture_state;
174 void SigSession::start_capture(function<void (const QString)> error_handler)
178 // Check that a device instance has been selected.
180 qDebug() << "No device selected";
184 assert(_dev_inst->dev_inst());
186 // Check that at least one probe is enabled
188 for (l = _dev_inst->dev_inst()->probes; l; l = l->next) {
189 sr_probe *const probe = (sr_probe*)l->data;
196 error_handler(tr("No probes enabled."));
201 _sampling_thread = boost::thread(
202 &SigSession::sample_thread_proc, this, _dev_inst,
206 void SigSession::stop_capture()
208 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> > SigSession::get_data() const
220 lock_guard<mutex> lock(_signals_mutex);
221 set< shared_ptr<data::SignalData> > data;
222 BOOST_FOREACH(const shared_ptr<view::Signal> sig, _signals) {
224 data.insert(sig->data());
230 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
232 lock_guard<mutex> lock(_signals_mutex);
237 bool SigSession::add_decoder(srd_decoder *const dec)
239 map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
240 shared_ptr<data::DecoderStack> decoder_stack;
244 lock_guard<mutex> lock(_signals_mutex);
246 // Create the decoder
247 decoder_stack = shared_ptr<data::DecoderStack>(
248 new data::DecoderStack(dec));
250 // Make a list of all the probes
251 std::vector<const srd_probe*> all_probes;
252 for(const GSList *i = dec->probes; i; i = i->next)
253 all_probes.push_back((const srd_probe*)i->data);
254 for(const GSList *i = dec->opt_probes; i; i = i->next)
255 all_probes.push_back((const srd_probe*)i->data);
257 // Auto select the initial probes
258 BOOST_FOREACH(const srd_probe *probe, all_probes)
259 BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
261 shared_ptr<view::LogicSignal> l =
262 dynamic_pointer_cast<view::LogicSignal>(s);
263 if (l && QString::fromUtf8(probe->name).
265 l->get_name().toLower()))
269 assert(decoder_stack);
270 assert(!decoder_stack->stack().empty());
271 assert(decoder_stack->stack().front());
272 decoder_stack->stack().front()->set_probes(probes);
274 // Create the decode signal
275 shared_ptr<view::DecodeTrace> d(
276 new view::DecodeTrace(*this, decoder_stack,
277 _decode_traces.size()));
278 _decode_traces.push_back(d);
280 catch(std::runtime_error e)
287 // Do an initial decode
288 decoder_stack->begin_decode();
293 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
295 lock_guard<mutex> lock(_signals_mutex);
296 return _decode_traces;
299 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
301 for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
302 _decode_traces.begin();
303 i != _decode_traces.end();
305 if ((*i).get() == signal)
307 _decode_traces.erase(i);
314 void SigSession::set_capture_state(capture_state state)
316 lock_guard<mutex> lock(_sampling_mutex);
317 const bool changed = _capture_state != state;
318 _capture_state = state;
320 capture_state_changed(state);
324 * Attempts to autodetect the format. Failing that
325 * @param filename The filename of the input file.
326 * @return A pointer to the 'struct sr_input_format' that should be used,
327 * or NULL if no input format was selected or auto-detected.
329 sr_input_format* SigSession::determine_input_file_format(
330 const string &filename)
334 /* If there are no input formats, return NULL right away. */
335 sr_input_format *const *const inputs = sr_input_list();
337 g_critical("No supported input formats available.");
341 /* Otherwise, try to find an input module that can handle this file. */
342 for (i = 0; inputs[i]; i++) {
343 if (inputs[i]->format_match(filename.c_str()))
347 /* Return NULL if no input module wanted to touch this. */
349 g_critical("Error: no matching input module found.");
356 sr_input* SigSession::load_input_file_format(const string &filename,
357 function<void (const QString)> error_handler,
358 sr_input_format *format)
363 if (!format && !(format =
364 determine_input_file_format(filename.c_str()))) {
365 /* The exact cause was already logged. */
369 if (stat(filename.c_str(), &st) == -1) {
370 error_handler(tr("Failed to load file"));
374 /* Initialize the input module. */
375 if (!(in = new sr_input)) {
376 qDebug("Failed to allocate input module.\n");
382 if (in->format->init &&
383 in->format->init(in, filename.c_str()) != SR_OK) {
384 qDebug("Input format init failed.\n");
390 if (sr_session_dev_add(in->sdi) != SR_OK) {
391 qDebug("Failed to use device.\n");
392 sr_session_destroy();
399 void SigSession::update_signals(shared_ptr<device::DevInst> dev_inst)
402 assert(_capture_state == Stopped);
404 unsigned int logic_probe_count = 0;
406 // Clear the decode traces
407 _decode_traces.clear();
409 // Detect what data types we will receive
411 assert(dev_inst->dev_inst());
412 for (const GSList *l = dev_inst->dev_inst()->probes;
414 const sr_probe *const probe = (const sr_probe *)l->data;
418 switch(probe->type) {
426 // Create data containers for the logic data snapshots
428 lock_guard<mutex> data_lock(_data_mutex);
431 if (logic_probe_count != 0) {
432 _logic_data.reset(new data::Logic(
438 // Make the Signals list
440 lock_guard<mutex> lock(_signals_mutex);
447 assert(dev_inst->dev_inst());
448 for (const GSList *l = dev_inst->dev_inst()->probes;
450 shared_ptr<view::Signal> signal;
451 sr_probe *const probe = (sr_probe *)l->data;
454 switch(probe->type) {
456 signal = shared_ptr<view::Signal>(
457 new view::LogicSignal(dev_inst,
458 probe, _logic_data));
461 case SR_PROBE_ANALOG:
463 shared_ptr<data::Analog> data(
465 signal = shared_ptr<view::Signal>(
466 new view::AnalogSignal(dev_inst,
477 _signals.push_back(signal);
485 bool SigSession::is_trigger_enabled() const
488 assert(_dev_inst->dev_inst());
489 for (const GSList *l = _dev_inst->dev_inst()->probes; l; l = l->next) {
490 const sr_probe *const p = (const sr_probe *)l->data;
492 if (p->trigger && p->trigger[0] != '\0')
499 shared_ptr<view::Signal> SigSession::signal_from_probe(
500 const sr_probe *probe) const
502 lock_guard<mutex> lock(_signals_mutex);
503 BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
505 if (sig->probe() == probe)
508 return shared_ptr<view::Signal>();
511 void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
514 uint64_t sample_rate = 0;
516 // Read out the sample rate
519 const int ret = sr_config_get(sdi->driver, sdi, NULL,
520 SR_CONF_SAMPLERATE, &gvar);
522 qDebug("Failed to get samplerate\n");
526 sample_rate = g_variant_get_uint64(gvar);
527 g_variant_unref(gvar);
530 // Set the sample rate of all data
531 const set< shared_ptr<data::SignalData> > data_set = get_data();
532 BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
534 data->set_samplerate(sample_rate);
538 void SigSession::load_session_thread_proc(
539 function<void (const QString)> error_handler)
543 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
545 set_capture_state(Running);
549 sr_session_destroy();
550 set_capture_state(Stopped);
552 // Confirm that SR_DF_END was received
553 assert(!_cur_logic_snapshot);
554 assert(_cur_analog_snapshots.empty());
557 void SigSession::load_input_thread_proc(const string name,
558 sr_input *in, function<void (const QString)> error_handler)
565 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
567 set_capture_state(Running);
569 in->format->loadfile(in, name.c_str());
571 sr_session_destroy();
572 set_capture_state(Stopped);
574 // Confirm that SR_DF_END was received
575 assert(!_cur_logic_snapshot);
576 assert(_cur_analog_snapshots.empty());
581 void SigSession::sample_thread_proc(shared_ptr<device::DevInst> dev_inst,
582 function<void (const QString)> error_handler)
585 assert(dev_inst->dev_inst());
586 assert(error_handler);
589 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
591 if (sr_session_dev_add(dev_inst->dev_inst()) != SR_OK) {
592 error_handler(tr("Failed to use device."));
593 sr_session_destroy();
597 if (sr_session_start() != SR_OK) {
598 error_handler(tr("Failed to start session."));
602 set_capture_state(is_trigger_enabled() ? AwaitingTrigger : Running);
605 sr_session_destroy();
607 set_capture_state(Stopped);
609 // Confirm that SR_DF_END was received
610 if (_cur_logic_snapshot)
612 qDebug("SR_DF_END was not received.");
617 void SigSession::feed_in_header(const sr_dev_inst *sdi)
619 read_sample_rate(sdi);
622 void SigSession::feed_in_meta(const sr_dev_inst *sdi,
623 const sr_datafeed_meta &meta)
627 for (const GSList *l = meta.config; l; l = l->next) {
628 const sr_config *const src = (const sr_config*)l->data;
630 case SR_CONF_SAMPLERATE:
631 /// @todo handle samplerate changes
632 /// samplerate = (uint64_t *)src->value;
635 // Unknown metadata is not an error.
643 void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
645 lock_guard<mutex> lock(_data_mutex);
649 qDebug() << "Unexpected logic packet";
653 if (!_cur_logic_snapshot)
655 // This could be the first packet after a trigger
656 set_capture_state(Running);
658 // Create a new data snapshot
659 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
660 new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
661 _logic_data->push_snapshot(_cur_logic_snapshot);
665 // Append to the existing data snapshot
666 _cur_logic_snapshot->append_payload(logic);
672 void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
674 lock_guard<mutex> lock(_data_mutex);
676 const unsigned int probe_count = g_slist_length(analog.probes);
677 const size_t sample_count = analog.num_samples / probe_count;
678 const float *data = analog.data;
679 bool sweep_beginning = false;
681 for (GSList *p = analog.probes; p; p = p->next)
683 shared_ptr<data::AnalogSnapshot> snapshot;
685 sr_probe *const probe = (sr_probe*)p->data;
688 // Try to get the snapshot of the probe
689 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
690 iterator iter = _cur_analog_snapshots.find(probe);
691 if (iter != _cur_analog_snapshots.end())
692 snapshot = (*iter).second;
695 // If no snapshot was found, this means we havn't
696 // created one yet. i.e. this is the first packet
697 // in the sweep containing this snapshot.
698 sweep_beginning = true;
700 // Create a snapshot, keep it in the maps of probes
701 snapshot = shared_ptr<data::AnalogSnapshot>(
702 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
703 _cur_analog_snapshots[probe] = snapshot;
705 // Find the annalog data associated with the probe
706 shared_ptr<view::AnalogSignal> sig =
707 dynamic_pointer_cast<view::AnalogSignal>(
708 signal_from_probe(probe));
711 shared_ptr<data::Analog> data(sig->analog_data());
714 // Push the snapshot into the analog data.
715 data->push_snapshot(snapshot);
720 // Append the samples in the snapshot
721 snapshot->append_interleaved_samples(data++, sample_count,
725 if (sweep_beginning) {
726 // This could be the first packet after a trigger
727 set_capture_state(Running);
733 void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
734 const struct sr_datafeed_packet *packet)
739 switch (packet->type) {
745 assert(packet->payload);
747 *(const sr_datafeed_meta*)packet->payload);
751 assert(packet->payload);
752 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
756 assert(packet->payload);
757 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
763 lock_guard<mutex> lock(_data_mutex);
764 _cur_logic_snapshot.reset();
765 _cur_analog_snapshots.clear();
773 void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
774 const struct sr_datafeed_packet *packet, void *cb_data)
778 _session->data_feed_in(sdi, packet);