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/devinst.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()
78 if (_sampling_thread.joinable())
79 _sampling_thread.join();
82 _device_manager.release_device(_dev_inst);
84 // TODO: This should not be necessary
88 shared_ptr<device::DevInst> SigSession::get_device() const
93 void SigSession::set_device(shared_ptr<device::DevInst> dev_inst)
95 // Ensure we are not capturing before setting the device
99 _device_manager.release_device(_dev_inst);
101 _device_manager.use_device(dev_inst, this);
102 _dev_inst = dev_inst;
103 update_signals(dev_inst);
106 void SigSession::release_device(shared_ptr<device::DevInst> dev_inst)
110 assert(_capture_state == Stopped);
111 _dev_inst = shared_ptr<device::DevInst>();
114 void SigSession::load_file(const string &name,
115 function<void (const QString)> error_handler)
119 if (sr_session_load(name.c_str()) == SR_OK) {
120 GSList *devlist = NULL;
121 sr_session_dev_list(&devlist);
123 if (!devlist || !devlist->data ||
124 sr_session_start() != SR_OK) {
125 error_handler(tr("Failed to start session."));
129 shared_ptr<device::DevInst> dev_inst(
130 new device::DevInst((sr_dev_inst*)devlist->data));
131 g_slist_free(devlist);
133 _decode_traces.clear();
134 update_signals(dev_inst);
135 read_sample_rate(dev_inst->dev_inst());
137 _sampling_thread = boost::thread(
138 &SigSession::load_session_thread_proc, this,
144 if (!(in = load_input_file_format(name.c_str(),
148 _decode_traces.clear();
149 update_signals(shared_ptr<device::DevInst>(
150 new device::DevInst(in->sdi)));
151 read_sample_rate(in->sdi);
153 _sampling_thread = boost::thread(
154 &SigSession::load_input_thread_proc, this,
155 name, in, error_handler);
159 SigSession::capture_state SigSession::get_capture_state() const
161 lock_guard<mutex> lock(_sampling_mutex);
162 return _capture_state;
165 void SigSession::start_capture(function<void (const QString)> error_handler)
169 // Check that a device instance has been selected.
171 qDebug() << "No device selected";
175 assert(_dev_inst->dev_inst());
177 // Check that at least one probe is enabled
179 for (l = _dev_inst->dev_inst()->probes; l; l = l->next) {
180 sr_probe *const probe = (sr_probe*)l->data;
187 error_handler(tr("No probes enabled."));
192 _sampling_thread = boost::thread(
193 &SigSession::sample_thread_proc, this, _dev_inst,
197 void SigSession::stop_capture()
199 if (get_capture_state() == Stopped)
204 // Check that sampling stopped
205 if (_sampling_thread.joinable())
206 _sampling_thread.join();
209 set< shared_ptr<data::SignalData> > SigSession::get_data() const
211 lock_guard<mutex> lock(_signals_mutex);
212 set< shared_ptr<data::SignalData> > data;
213 BOOST_FOREACH(const shared_ptr<view::Signal> sig, _signals) {
215 data.insert(sig->data());
221 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
223 lock_guard<mutex> lock(_signals_mutex);
228 bool SigSession::add_decoder(srd_decoder *const dec)
230 map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
231 shared_ptr<data::DecoderStack> decoder_stack;
235 lock_guard<mutex> lock(_signals_mutex);
237 // Create the decoder
238 decoder_stack = shared_ptr<data::DecoderStack>(
239 new data::DecoderStack(dec));
241 // Make a list of all the probes
242 std::vector<const srd_probe*> all_probes;
243 for(const GSList *i = dec->probes; i; i = i->next)
244 all_probes.push_back((const srd_probe*)i->data);
245 for(const GSList *i = dec->opt_probes; i; i = i->next)
246 all_probes.push_back((const srd_probe*)i->data);
248 // Auto select the initial probes
249 BOOST_FOREACH(const srd_probe *probe, all_probes)
250 BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
252 shared_ptr<view::LogicSignal> l =
253 dynamic_pointer_cast<view::LogicSignal>(s);
254 if (l && QString::fromUtf8(probe->name).
256 l->get_name().toLower()))
260 assert(decoder_stack);
261 assert(!decoder_stack->stack().empty());
262 assert(decoder_stack->stack().front());
263 decoder_stack->stack().front()->set_probes(probes);
265 // Create the decode signal
266 shared_ptr<view::DecodeTrace> d(
267 new view::DecodeTrace(*this, decoder_stack,
268 _decode_traces.size()));
269 _decode_traces.push_back(d);
271 catch(std::runtime_error e)
278 // Do an initial decode
279 decoder_stack->begin_decode();
284 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
286 lock_guard<mutex> lock(_signals_mutex);
287 return _decode_traces;
290 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
292 for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
293 _decode_traces.begin();
294 i != _decode_traces.end();
296 if ((*i).get() == signal)
298 _decode_traces.erase(i);
305 void SigSession::set_capture_state(capture_state state)
307 lock_guard<mutex> lock(_sampling_mutex);
308 const bool changed = _capture_state != state;
309 _capture_state = state;
311 capture_state_changed(state);
315 * Attempts to autodetect the format. Failing that
316 * @param filename The filename of the input file.
317 * @return A pointer to the 'struct sr_input_format' that should be used,
318 * or NULL if no input format was selected or auto-detected.
320 sr_input_format* SigSession::determine_input_file_format(
321 const string &filename)
325 /* If there are no input formats, return NULL right away. */
326 sr_input_format *const *const inputs = sr_input_list();
328 g_critical("No supported input formats available.");
332 /* Otherwise, try to find an input module that can handle this file. */
333 for (i = 0; inputs[i]; i++) {
334 if (inputs[i]->format_match(filename.c_str()))
338 /* Return NULL if no input module wanted to touch this. */
340 g_critical("Error: no matching input module found.");
347 sr_input* SigSession::load_input_file_format(const string &filename,
348 function<void (const QString)> error_handler,
349 sr_input_format *format)
354 if (!format && !(format =
355 determine_input_file_format(filename.c_str()))) {
356 /* The exact cause was already logged. */
360 if (stat(filename.c_str(), &st) == -1) {
361 error_handler(tr("Failed to load file"));
365 /* Initialize the input module. */
366 if (!(in = new sr_input)) {
367 qDebug("Failed to allocate input module.\n");
373 if (in->format->init &&
374 in->format->init(in, filename.c_str()) != SR_OK) {
375 qDebug("Input format init failed.\n");
381 if (sr_session_dev_add(in->sdi) != SR_OK) {
382 qDebug("Failed to use device.\n");
383 sr_session_destroy();
390 void SigSession::update_signals(shared_ptr<device::DevInst> dev_inst)
393 assert(_capture_state == Stopped);
395 unsigned int logic_probe_count = 0;
397 // Clear the decode traces
398 _decode_traces.clear();
400 // Detect what data types we will receive
402 assert(dev_inst->dev_inst());
403 for (const GSList *l = dev_inst->dev_inst()->probes;
405 const sr_probe *const probe = (const sr_probe *)l->data;
409 switch(probe->type) {
417 // Create data containers for the logic data snapshots
419 lock_guard<mutex> data_lock(_data_mutex);
422 if (logic_probe_count != 0) {
423 _logic_data.reset(new data::Logic(
429 // Make the Signals list
431 lock_guard<mutex> lock(_signals_mutex);
438 assert(dev_inst->dev_inst());
439 for (const GSList *l = dev_inst->dev_inst()->probes;
441 shared_ptr<view::Signal> signal;
442 sr_probe *const probe = (sr_probe *)l->data;
445 switch(probe->type) {
447 signal = shared_ptr<view::Signal>(
448 new view::LogicSignal(dev_inst,
449 probe, _logic_data));
452 case SR_PROBE_ANALOG:
454 shared_ptr<data::Analog> data(
456 signal = shared_ptr<view::Signal>(
457 new view::AnalogSignal(dev_inst,
468 _signals.push_back(signal);
476 bool SigSession::is_trigger_enabled() const
479 assert(_dev_inst->dev_inst());
480 for (const GSList *l = _dev_inst->dev_inst()->probes; l; l = l->next) {
481 const sr_probe *const p = (const sr_probe *)l->data;
483 if (p->trigger && p->trigger[0] != '\0')
490 shared_ptr<view::Signal> SigSession::signal_from_probe(
491 const sr_probe *probe) const
493 lock_guard<mutex> lock(_signals_mutex);
494 BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
496 if (sig->probe() == probe)
499 return shared_ptr<view::Signal>();
502 void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
505 uint64_t sample_rate = 0;
507 // Read out the sample rate
510 const int ret = sr_config_get(sdi->driver, sdi, NULL,
511 SR_CONF_SAMPLERATE, &gvar);
513 qDebug("Failed to get samplerate\n");
517 sample_rate = g_variant_get_uint64(gvar);
518 g_variant_unref(gvar);
521 // Set the sample rate of all data
522 const set< shared_ptr<data::SignalData> > data_set = get_data();
523 BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
525 data->set_samplerate(sample_rate);
529 void SigSession::load_session_thread_proc(
530 function<void (const QString)> error_handler)
534 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
536 set_capture_state(Running);
540 sr_session_destroy();
541 set_capture_state(Stopped);
543 // Confirm that SR_DF_END was received
544 assert(!_cur_logic_snapshot);
545 assert(_cur_analog_snapshots.empty());
548 void SigSession::load_input_thread_proc(const string name,
549 sr_input *in, function<void (const QString)> error_handler)
556 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
558 set_capture_state(Running);
560 in->format->loadfile(in, name.c_str());
562 sr_session_destroy();
563 set_capture_state(Stopped);
565 // Confirm that SR_DF_END was received
566 assert(!_cur_logic_snapshot);
567 assert(_cur_analog_snapshots.empty());
572 void SigSession::sample_thread_proc(shared_ptr<device::DevInst> dev_inst,
573 function<void (const QString)> error_handler)
576 assert(dev_inst->dev_inst());
577 assert(error_handler);
580 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
582 if (sr_session_dev_add(dev_inst->dev_inst()) != SR_OK) {
583 error_handler(tr("Failed to use device."));
584 sr_session_destroy();
588 if (sr_session_start() != SR_OK) {
589 error_handler(tr("Failed to start session."));
593 set_capture_state(is_trigger_enabled() ? AwaitingTrigger : Running);
596 sr_session_destroy();
598 set_capture_state(Stopped);
600 // Confirm that SR_DF_END was received
601 if (_cur_logic_snapshot)
603 qDebug("SR_DF_END was not received.");
608 void SigSession::feed_in_header(const sr_dev_inst *sdi)
610 read_sample_rate(sdi);
613 void SigSession::feed_in_meta(const sr_dev_inst *sdi,
614 const sr_datafeed_meta &meta)
618 for (const GSList *l = meta.config; l; l = l->next) {
619 const sr_config *const src = (const sr_config*)l->data;
621 case SR_CONF_SAMPLERATE:
622 /// @todo handle samplerate changes
623 /// samplerate = (uint64_t *)src->value;
626 // Unknown metadata is not an error.
634 void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
636 lock_guard<mutex> lock(_data_mutex);
640 qDebug() << "Unexpected logic packet";
644 if (!_cur_logic_snapshot)
646 // This could be the first packet after a trigger
647 set_capture_state(Running);
649 // Create a new data snapshot
650 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
651 new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
652 _logic_data->push_snapshot(_cur_logic_snapshot);
656 // Append to the existing data snapshot
657 _cur_logic_snapshot->append_payload(logic);
663 void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
665 lock_guard<mutex> lock(_data_mutex);
667 const unsigned int probe_count = g_slist_length(analog.probes);
668 const size_t sample_count = analog.num_samples / probe_count;
669 const float *data = analog.data;
670 bool sweep_beginning = false;
672 for (GSList *p = analog.probes; p; p = p->next)
674 shared_ptr<data::AnalogSnapshot> snapshot;
676 sr_probe *const probe = (sr_probe*)p->data;
679 // Try to get the snapshot of the probe
680 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
681 iterator iter = _cur_analog_snapshots.find(probe);
682 if (iter != _cur_analog_snapshots.end())
683 snapshot = (*iter).second;
686 // If no snapshot was found, this means we havn't
687 // created one yet. i.e. this is the first packet
688 // in the sweep containing this snapshot.
689 sweep_beginning = true;
691 // Create a snapshot, keep it in the maps of probes
692 snapshot = shared_ptr<data::AnalogSnapshot>(
693 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
694 _cur_analog_snapshots[probe] = snapshot;
696 // Find the annalog data associated with the probe
697 shared_ptr<view::AnalogSignal> sig =
698 dynamic_pointer_cast<view::AnalogSignal>(
699 signal_from_probe(probe));
702 shared_ptr<data::Analog> data(sig->analog_data());
705 // Push the snapshot into the analog data.
706 data->push_snapshot(snapshot);
711 // Append the samples in the snapshot
712 snapshot->append_interleaved_samples(data++, sample_count,
716 if (sweep_beginning) {
717 // This could be the first packet after a trigger
718 set_capture_state(Running);
724 void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
725 const struct sr_datafeed_packet *packet)
730 switch (packet->type) {
736 assert(packet->payload);
738 *(const sr_datafeed_meta*)packet->payload);
742 assert(packet->payload);
743 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
747 assert(packet->payload);
748 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
754 lock_guard<mutex> lock(_data_mutex);
755 _cur_logic_snapshot.reset();
756 _cur_analog_snapshots.clear();
764 void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
765 const struct sr_datafeed_packet *packet, void *cb_data)
769 _session->data_feed_in(sdi, packet);