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();
85 // TODO: This should not be necessary
89 shared_ptr<device::DevInst> SigSession::get_device() const
94 void SigSession::set_device(shared_ptr<device::DevInst> dev_inst)
96 using pv::device::Device;
98 // Ensure we are not capturing before setting the device
102 _dev_inst->release();
107 _dev_inst = dev_inst;
108 update_signals(dev_inst);
111 void SigSession::release_device(device::DevInst *dev_inst)
114 assert(_dev_inst.get() == dev_inst);
116 assert(_capture_state == Stopped);
117 _dev_inst = shared_ptr<device::DevInst>();
120 void SigSession::load_file(const string &name,
121 function<void (const QString)> error_handler)
125 if (sr_session_load(name.c_str()) == SR_OK) {
126 GSList *devlist = NULL;
127 sr_session_dev_list(&devlist);
129 if (!devlist || !devlist->data ||
130 sr_session_start() != SR_OK) {
131 error_handler(tr("Failed to start session."));
135 shared_ptr<device::DevInst> dev_inst(
136 new device::Device((sr_dev_inst*)devlist->data));
137 g_slist_free(devlist);
139 _decode_traces.clear();
140 update_signals(dev_inst);
141 read_sample_rate(dev_inst->dev_inst());
143 _sampling_thread = boost::thread(
144 &SigSession::load_session_thread_proc, this,
150 if (!(in = load_input_file_format(name.c_str(),
154 _decode_traces.clear();
155 update_signals(shared_ptr<device::DevInst>(
156 new device::Device(in->sdi)));
157 read_sample_rate(in->sdi);
159 _sampling_thread = boost::thread(
160 &SigSession::load_input_thread_proc, this,
161 name, in, error_handler);
165 SigSession::capture_state SigSession::get_capture_state() const
167 lock_guard<mutex> lock(_sampling_mutex);
168 return _capture_state;
171 void SigSession::start_capture(function<void (const QString)> error_handler)
175 // Check that a device instance has been selected.
177 qDebug() << "No device selected";
181 assert(_dev_inst->dev_inst());
183 // Check that at least one probe is enabled
185 for (l = _dev_inst->dev_inst()->probes; l; l = l->next) {
186 sr_probe *const probe = (sr_probe*)l->data;
193 error_handler(tr("No probes enabled."));
198 _sampling_thread = boost::thread(
199 &SigSession::sample_thread_proc, this, _dev_inst,
203 void SigSession::stop_capture()
205 if (get_capture_state() == Stopped)
210 // Check that sampling stopped
211 if (_sampling_thread.joinable())
212 _sampling_thread.join();
215 set< shared_ptr<data::SignalData> > SigSession::get_data() const
217 lock_guard<mutex> lock(_signals_mutex);
218 set< shared_ptr<data::SignalData> > data;
219 BOOST_FOREACH(const shared_ptr<view::Signal> sig, _signals) {
221 data.insert(sig->data());
227 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
229 lock_guard<mutex> lock(_signals_mutex);
234 bool SigSession::add_decoder(srd_decoder *const dec)
236 map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
237 shared_ptr<data::DecoderStack> decoder_stack;
241 lock_guard<mutex> lock(_signals_mutex);
243 // Create the decoder
244 decoder_stack = shared_ptr<data::DecoderStack>(
245 new data::DecoderStack(dec));
247 // Make a list of all the probes
248 std::vector<const srd_probe*> all_probes;
249 for(const GSList *i = dec->probes; i; i = i->next)
250 all_probes.push_back((const srd_probe*)i->data);
251 for(const GSList *i = dec->opt_probes; i; i = i->next)
252 all_probes.push_back((const srd_probe*)i->data);
254 // Auto select the initial probes
255 BOOST_FOREACH(const srd_probe *probe, all_probes)
256 BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
258 shared_ptr<view::LogicSignal> l =
259 dynamic_pointer_cast<view::LogicSignal>(s);
260 if (l && QString::fromUtf8(probe->name).
262 l->get_name().toLower()))
266 assert(decoder_stack);
267 assert(!decoder_stack->stack().empty());
268 assert(decoder_stack->stack().front());
269 decoder_stack->stack().front()->set_probes(probes);
271 // Create the decode signal
272 shared_ptr<view::DecodeTrace> d(
273 new view::DecodeTrace(*this, decoder_stack,
274 _decode_traces.size()));
275 _decode_traces.push_back(d);
277 catch(std::runtime_error e)
284 // Do an initial decode
285 decoder_stack->begin_decode();
290 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
292 lock_guard<mutex> lock(_signals_mutex);
293 return _decode_traces;
296 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
298 for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
299 _decode_traces.begin();
300 i != _decode_traces.end();
302 if ((*i).get() == signal)
304 _decode_traces.erase(i);
311 void SigSession::set_capture_state(capture_state state)
313 lock_guard<mutex> lock(_sampling_mutex);
314 const bool changed = _capture_state != state;
315 _capture_state = state;
317 capture_state_changed(state);
321 * Attempts to autodetect the format. Failing that
322 * @param filename The filename of the input file.
323 * @return A pointer to the 'struct sr_input_format' that should be used,
324 * or NULL if no input format was selected or auto-detected.
326 sr_input_format* SigSession::determine_input_file_format(
327 const string &filename)
331 /* If there are no input formats, return NULL right away. */
332 sr_input_format *const *const inputs = sr_input_list();
334 g_critical("No supported input formats available.");
338 /* Otherwise, try to find an input module that can handle this file. */
339 for (i = 0; inputs[i]; i++) {
340 if (inputs[i]->format_match(filename.c_str()))
344 /* Return NULL if no input module wanted to touch this. */
346 g_critical("Error: no matching input module found.");
353 sr_input* SigSession::load_input_file_format(const string &filename,
354 function<void (const QString)> error_handler,
355 sr_input_format *format)
360 if (!format && !(format =
361 determine_input_file_format(filename.c_str()))) {
362 /* The exact cause was already logged. */
366 if (stat(filename.c_str(), &st) == -1) {
367 error_handler(tr("Failed to load file"));
371 /* Initialize the input module. */
372 if (!(in = new sr_input)) {
373 qDebug("Failed to allocate input module.\n");
379 if (in->format->init &&
380 in->format->init(in, filename.c_str()) != SR_OK) {
381 qDebug("Input format init failed.\n");
387 if (sr_session_dev_add(in->sdi) != SR_OK) {
388 qDebug("Failed to use device.\n");
389 sr_session_destroy();
396 void SigSession::update_signals(shared_ptr<device::DevInst> dev_inst)
399 assert(_capture_state == Stopped);
401 unsigned int logic_probe_count = 0;
403 // Clear the decode traces
404 _decode_traces.clear();
406 // Detect what data types we will receive
408 assert(dev_inst->dev_inst());
409 for (const GSList *l = dev_inst->dev_inst()->probes;
411 const sr_probe *const probe = (const sr_probe *)l->data;
415 switch(probe->type) {
423 // Create data containers for the logic data snapshots
425 lock_guard<mutex> data_lock(_data_mutex);
428 if (logic_probe_count != 0) {
429 _logic_data.reset(new data::Logic(
435 // Make the Signals list
437 lock_guard<mutex> lock(_signals_mutex);
444 assert(dev_inst->dev_inst());
445 for (const GSList *l = dev_inst->dev_inst()->probes;
447 shared_ptr<view::Signal> signal;
448 sr_probe *const probe = (sr_probe *)l->data;
451 switch(probe->type) {
453 signal = shared_ptr<view::Signal>(
454 new view::LogicSignal(dev_inst,
455 probe, _logic_data));
458 case SR_PROBE_ANALOG:
460 shared_ptr<data::Analog> data(
462 signal = shared_ptr<view::Signal>(
463 new view::AnalogSignal(dev_inst,
474 _signals.push_back(signal);
482 shared_ptr<view::Signal> SigSession::signal_from_probe(
483 const sr_probe *probe) const
485 lock_guard<mutex> lock(_signals_mutex);
486 BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
488 if (sig->probe() == probe)
491 return shared_ptr<view::Signal>();
494 void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
497 uint64_t sample_rate = 0;
499 // Read out the sample rate
502 const int ret = sr_config_get(sdi->driver, sdi, NULL,
503 SR_CONF_SAMPLERATE, &gvar);
505 qDebug("Failed to get samplerate\n");
509 sample_rate = g_variant_get_uint64(gvar);
510 g_variant_unref(gvar);
513 // Set the sample rate of all data
514 const set< shared_ptr<data::SignalData> > data_set = get_data();
515 BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
517 data->set_samplerate(sample_rate);
521 void SigSession::load_session_thread_proc(
522 function<void (const QString)> error_handler)
526 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
528 set_capture_state(Running);
532 sr_session_destroy();
533 set_capture_state(Stopped);
535 // Confirm that SR_DF_END was received
536 assert(!_cur_logic_snapshot);
537 assert(_cur_analog_snapshots.empty());
540 void SigSession::load_input_thread_proc(const string name,
541 sr_input *in, function<void (const QString)> error_handler)
548 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
550 set_capture_state(Running);
552 in->format->loadfile(in, name.c_str());
554 sr_session_destroy();
555 set_capture_state(Stopped);
557 // Confirm that SR_DF_END was received
558 assert(!_cur_logic_snapshot);
559 assert(_cur_analog_snapshots.empty());
564 void SigSession::sample_thread_proc(shared_ptr<device::DevInst> dev_inst,
565 function<void (const QString)> error_handler)
568 assert(dev_inst->dev_inst());
569 assert(error_handler);
572 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
574 if (sr_session_dev_add(dev_inst->dev_inst()) != SR_OK) {
575 error_handler(tr("Failed to use device."));
576 sr_session_destroy();
580 if (sr_session_start() != SR_OK) {
581 error_handler(tr("Failed to start session."));
585 set_capture_state(dev_inst->is_trigger_enabled() ?
586 AwaitingTrigger : Running);
589 sr_session_destroy();
591 set_capture_state(Stopped);
593 // Confirm that SR_DF_END was received
594 if (_cur_logic_snapshot)
596 qDebug("SR_DF_END was not received.");
601 void SigSession::feed_in_header(const sr_dev_inst *sdi)
603 read_sample_rate(sdi);
606 void SigSession::feed_in_meta(const sr_dev_inst *sdi,
607 const sr_datafeed_meta &meta)
611 for (const GSList *l = meta.config; l; l = l->next) {
612 const sr_config *const src = (const sr_config*)l->data;
614 case SR_CONF_SAMPLERATE:
615 /// @todo handle samplerate changes
616 /// samplerate = (uint64_t *)src->value;
619 // Unknown metadata is not an error.
627 void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
629 lock_guard<mutex> lock(_data_mutex);
633 qDebug() << "Unexpected logic packet";
637 if (!_cur_logic_snapshot)
639 // This could be the first packet after a trigger
640 set_capture_state(Running);
642 // Create a new data snapshot
643 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
644 new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
645 _logic_data->push_snapshot(_cur_logic_snapshot);
649 // Append to the existing data snapshot
650 _cur_logic_snapshot->append_payload(logic);
656 void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
658 lock_guard<mutex> lock(_data_mutex);
660 const unsigned int probe_count = g_slist_length(analog.probes);
661 const size_t sample_count = analog.num_samples / probe_count;
662 const float *data = analog.data;
663 bool sweep_beginning = false;
665 for (GSList *p = analog.probes; p; p = p->next)
667 shared_ptr<data::AnalogSnapshot> snapshot;
669 sr_probe *const probe = (sr_probe*)p->data;
672 // Try to get the snapshot of the probe
673 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
674 iterator iter = _cur_analog_snapshots.find(probe);
675 if (iter != _cur_analog_snapshots.end())
676 snapshot = (*iter).second;
679 // If no snapshot was found, this means we havn't
680 // created one yet. i.e. this is the first packet
681 // in the sweep containing this snapshot.
682 sweep_beginning = true;
684 // Create a snapshot, keep it in the maps of probes
685 snapshot = shared_ptr<data::AnalogSnapshot>(
686 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
687 _cur_analog_snapshots[probe] = snapshot;
689 // Find the annalog data associated with the probe
690 shared_ptr<view::AnalogSignal> sig =
691 dynamic_pointer_cast<view::AnalogSignal>(
692 signal_from_probe(probe));
695 shared_ptr<data::Analog> data(sig->analog_data());
698 // Push the snapshot into the analog data.
699 data->push_snapshot(snapshot);
704 // Append the samples in the snapshot
705 snapshot->append_interleaved_samples(data++, sample_count,
709 if (sweep_beginning) {
710 // This could be the first packet after a trigger
711 set_capture_state(Running);
717 void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
718 const struct sr_datafeed_packet *packet)
723 switch (packet->type) {
729 assert(packet->payload);
731 *(const sr_datafeed_meta*)packet->payload);
735 assert(packet->payload);
736 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
740 assert(packet->payload);
741 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
747 lock_guard<mutex> lock(_data_mutex);
748 _cur_logic_snapshot.reset();
749 _cur_analog_snapshots.clear();
757 void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
758 const struct sr_datafeed_packet *packet, void *cb_data)
762 _session->data_feed_in(sdi, packet);