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 bool SigSession::is_trigger_enabled() const
485 assert(_dev_inst->dev_inst());
486 for (const GSList *l = _dev_inst->dev_inst()->probes; l; l = l->next) {
487 const sr_probe *const p = (const sr_probe *)l->data;
489 if (p->trigger && p->trigger[0] != '\0')
496 shared_ptr<view::Signal> SigSession::signal_from_probe(
497 const sr_probe *probe) const
499 lock_guard<mutex> lock(_signals_mutex);
500 BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
502 if (sig->probe() == probe)
505 return shared_ptr<view::Signal>();
508 void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
511 uint64_t sample_rate = 0;
513 // Read out the sample rate
516 const int ret = sr_config_get(sdi->driver, sdi, NULL,
517 SR_CONF_SAMPLERATE, &gvar);
519 qDebug("Failed to get samplerate\n");
523 sample_rate = g_variant_get_uint64(gvar);
524 g_variant_unref(gvar);
527 // Set the sample rate of all data
528 const set< shared_ptr<data::SignalData> > data_set = get_data();
529 BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
531 data->set_samplerate(sample_rate);
535 void SigSession::load_session_thread_proc(
536 function<void (const QString)> error_handler)
540 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
542 set_capture_state(Running);
546 sr_session_destroy();
547 set_capture_state(Stopped);
549 // Confirm that SR_DF_END was received
550 assert(!_cur_logic_snapshot);
551 assert(_cur_analog_snapshots.empty());
554 void SigSession::load_input_thread_proc(const string name,
555 sr_input *in, function<void (const QString)> error_handler)
562 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
564 set_capture_state(Running);
566 in->format->loadfile(in, name.c_str());
568 sr_session_destroy();
569 set_capture_state(Stopped);
571 // Confirm that SR_DF_END was received
572 assert(!_cur_logic_snapshot);
573 assert(_cur_analog_snapshots.empty());
578 void SigSession::sample_thread_proc(shared_ptr<device::DevInst> dev_inst,
579 function<void (const QString)> error_handler)
582 assert(dev_inst->dev_inst());
583 assert(error_handler);
586 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
588 if (sr_session_dev_add(dev_inst->dev_inst()) != SR_OK) {
589 error_handler(tr("Failed to use device."));
590 sr_session_destroy();
594 if (sr_session_start() != SR_OK) {
595 error_handler(tr("Failed to start session."));
599 set_capture_state(is_trigger_enabled() ? AwaitingTrigger : Running);
602 sr_session_destroy();
604 set_capture_state(Stopped);
606 // Confirm that SR_DF_END was received
607 if (_cur_logic_snapshot)
609 qDebug("SR_DF_END was not received.");
614 void SigSession::feed_in_header(const sr_dev_inst *sdi)
616 read_sample_rate(sdi);
619 void SigSession::feed_in_meta(const sr_dev_inst *sdi,
620 const sr_datafeed_meta &meta)
624 for (const GSList *l = meta.config; l; l = l->next) {
625 const sr_config *const src = (const sr_config*)l->data;
627 case SR_CONF_SAMPLERATE:
628 /// @todo handle samplerate changes
629 /// samplerate = (uint64_t *)src->value;
632 // Unknown metadata is not an error.
640 void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
642 lock_guard<mutex> lock(_data_mutex);
646 qDebug() << "Unexpected logic packet";
650 if (!_cur_logic_snapshot)
652 // This could be the first packet after a trigger
653 set_capture_state(Running);
655 // Create a new data snapshot
656 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
657 new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
658 _logic_data->push_snapshot(_cur_logic_snapshot);
662 // Append to the existing data snapshot
663 _cur_logic_snapshot->append_payload(logic);
669 void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
671 lock_guard<mutex> lock(_data_mutex);
673 const unsigned int probe_count = g_slist_length(analog.probes);
674 const size_t sample_count = analog.num_samples / probe_count;
675 const float *data = analog.data;
676 bool sweep_beginning = false;
678 for (GSList *p = analog.probes; p; p = p->next)
680 shared_ptr<data::AnalogSnapshot> snapshot;
682 sr_probe *const probe = (sr_probe*)p->data;
685 // Try to get the snapshot of the probe
686 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
687 iterator iter = _cur_analog_snapshots.find(probe);
688 if (iter != _cur_analog_snapshots.end())
689 snapshot = (*iter).second;
692 // If no snapshot was found, this means we havn't
693 // created one yet. i.e. this is the first packet
694 // in the sweep containing this snapshot.
695 sweep_beginning = true;
697 // Create a snapshot, keep it in the maps of probes
698 snapshot = shared_ptr<data::AnalogSnapshot>(
699 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
700 _cur_analog_snapshots[probe] = snapshot;
702 // Find the annalog data associated with the probe
703 shared_ptr<view::AnalogSignal> sig =
704 dynamic_pointer_cast<view::AnalogSignal>(
705 signal_from_probe(probe));
708 shared_ptr<data::Analog> data(sig->analog_data());
711 // Push the snapshot into the analog data.
712 data->push_snapshot(snapshot);
717 // Append the samples in the snapshot
718 snapshot->append_interleaved_samples(data++, sample_count,
722 if (sweep_beginning) {
723 // This could be the first packet after a trigger
724 set_capture_state(Running);
730 void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
731 const struct sr_datafeed_packet *packet)
736 switch (packet->type) {
742 assert(packet->payload);
744 *(const sr_datafeed_meta*)packet->payload);
748 assert(packet->payload);
749 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
753 assert(packet->payload);
754 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
760 lock_guard<mutex> lock(_data_mutex);
761 _cur_logic_snapshot.reset();
762 _cur_analog_snapshots.clear();
770 void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
771 const struct sr_datafeed_packet *packet, void *cb_data)
775 _session->data_feed_in(sdi, packet);