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"
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<DevInst> SigSession::get_device() const
93 void SigSession::set_device(shared_ptr<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<DevInst> dev_inst)
110 assert(_capture_state == Stopped);
111 _dev_inst = shared_ptr<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<DevInst> dev_inst(
130 new 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<DevInst>(new DevInst(in->sdi)));
150 read_sample_rate(in->sdi);
152 _sampling_thread = boost::thread(
153 &SigSession::load_input_thread_proc, this,
154 name, in, error_handler);
158 SigSession::capture_state SigSession::get_capture_state() const
160 lock_guard<mutex> lock(_sampling_mutex);
161 return _capture_state;
164 void SigSession::start_capture(function<void (const QString)> error_handler)
168 // Check that a device instance has been selected.
170 qDebug() << "No device selected";
174 assert(_dev_inst->dev_inst());
176 // Check that at least one probe is enabled
178 for (l = _dev_inst->dev_inst()->probes; l; l = l->next) {
179 sr_probe *const probe = (sr_probe*)l->data;
186 error_handler(tr("No probes enabled."));
191 _sampling_thread = boost::thread(
192 &SigSession::sample_thread_proc, this, _dev_inst,
196 void SigSession::stop_capture()
198 if (get_capture_state() == Stopped)
203 // Check that sampling stopped
204 if (_sampling_thread.joinable())
205 _sampling_thread.join();
208 set< shared_ptr<data::SignalData> > SigSession::get_data() const
210 lock_guard<mutex> lock(_signals_mutex);
211 set< shared_ptr<data::SignalData> > data;
212 BOOST_FOREACH(const shared_ptr<view::Signal> sig, _signals) {
214 data.insert(sig->data());
220 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
222 lock_guard<mutex> lock(_signals_mutex);
227 bool SigSession::add_decoder(srd_decoder *const dec)
229 map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
230 shared_ptr<data::DecoderStack> decoder_stack;
234 lock_guard<mutex> lock(_signals_mutex);
236 // Create the decoder
237 decoder_stack = shared_ptr<data::DecoderStack>(
238 new data::DecoderStack(dec));
240 // Make a list of all the probes
241 std::vector<const srd_probe*> all_probes;
242 for(const GSList *i = dec->probes; i; i = i->next)
243 all_probes.push_back((const srd_probe*)i->data);
244 for(const GSList *i = dec->opt_probes; i; i = i->next)
245 all_probes.push_back((const srd_probe*)i->data);
247 // Auto select the initial probes
248 BOOST_FOREACH(const srd_probe *probe, all_probes)
249 BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
251 shared_ptr<view::LogicSignal> l =
252 dynamic_pointer_cast<view::LogicSignal>(s);
253 if (l && QString::fromUtf8(probe->name).
255 l->get_name().toLower()))
259 assert(decoder_stack);
260 assert(!decoder_stack->stack().empty());
261 assert(decoder_stack->stack().front());
262 decoder_stack->stack().front()->set_probes(probes);
264 // Create the decode signal
265 shared_ptr<view::DecodeTrace> d(
266 new view::DecodeTrace(*this, decoder_stack,
267 _decode_traces.size()));
268 _decode_traces.push_back(d);
270 catch(std::runtime_error e)
277 // Do an initial decode
278 decoder_stack->begin_decode();
283 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
285 lock_guard<mutex> lock(_signals_mutex);
286 return _decode_traces;
289 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
291 for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
292 _decode_traces.begin();
293 i != _decode_traces.end();
295 if ((*i).get() == signal)
297 _decode_traces.erase(i);
304 void SigSession::set_capture_state(capture_state state)
306 lock_guard<mutex> lock(_sampling_mutex);
307 const bool changed = _capture_state != state;
308 _capture_state = state;
310 capture_state_changed(state);
314 * Attempts to autodetect the format. Failing that
315 * @param filename The filename of the input file.
316 * @return A pointer to the 'struct sr_input_format' that should be used,
317 * or NULL if no input format was selected or auto-detected.
319 sr_input_format* SigSession::determine_input_file_format(
320 const string &filename)
324 /* If there are no input formats, return NULL right away. */
325 sr_input_format *const *const inputs = sr_input_list();
327 g_critical("No supported input formats available.");
331 /* Otherwise, try to find an input module that can handle this file. */
332 for (i = 0; inputs[i]; i++) {
333 if (inputs[i]->format_match(filename.c_str()))
337 /* Return NULL if no input module wanted to touch this. */
339 g_critical("Error: no matching input module found.");
346 sr_input* SigSession::load_input_file_format(const string &filename,
347 function<void (const QString)> error_handler,
348 sr_input_format *format)
353 if (!format && !(format =
354 determine_input_file_format(filename.c_str()))) {
355 /* The exact cause was already logged. */
359 if (stat(filename.c_str(), &st) == -1) {
360 error_handler(tr("Failed to load file"));
364 /* Initialize the input module. */
365 if (!(in = new sr_input)) {
366 qDebug("Failed to allocate input module.\n");
372 if (in->format->init &&
373 in->format->init(in, filename.c_str()) != SR_OK) {
374 qDebug("Input format init failed.\n");
380 if (sr_session_dev_add(in->sdi) != SR_OK) {
381 qDebug("Failed to use device.\n");
382 sr_session_destroy();
389 void SigSession::update_signals(shared_ptr<DevInst> dev_inst)
392 assert(_capture_state == Stopped);
394 unsigned int logic_probe_count = 0;
396 // Clear the decode traces
397 _decode_traces.clear();
399 // Detect what data types we will receive
401 assert(dev_inst->dev_inst());
402 for (const GSList *l = dev_inst->dev_inst()->probes;
404 const sr_probe *const probe = (const sr_probe *)l->data;
408 switch(probe->type) {
416 // Create data containers for the logic data snapshots
418 lock_guard<mutex> data_lock(_data_mutex);
421 if (logic_probe_count != 0) {
422 _logic_data.reset(new data::Logic(
428 // Make the Signals list
430 lock_guard<mutex> lock(_signals_mutex);
437 assert(dev_inst->dev_inst());
438 for (const GSList *l = dev_inst->dev_inst()->probes;
440 shared_ptr<view::Signal> signal;
441 sr_probe *const probe = (sr_probe *)l->data;
444 switch(probe->type) {
446 signal = shared_ptr<view::Signal>(
447 new view::LogicSignal(dev_inst,
448 probe, _logic_data));
451 case SR_PROBE_ANALOG:
453 shared_ptr<data::Analog> data(
455 signal = shared_ptr<view::Signal>(
456 new view::AnalogSignal(dev_inst,
467 _signals.push_back(signal);
475 bool SigSession::is_trigger_enabled() const
478 assert(_dev_inst->dev_inst());
479 for (const GSList *l = _dev_inst->dev_inst()->probes; l; l = l->next) {
480 const sr_probe *const p = (const sr_probe *)l->data;
482 if (p->trigger && p->trigger[0] != '\0')
489 shared_ptr<view::Signal> SigSession::signal_from_probe(
490 const sr_probe *probe) const
492 lock_guard<mutex> lock(_signals_mutex);
493 BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
495 if (sig->probe() == probe)
498 return shared_ptr<view::Signal>();
501 void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
504 uint64_t sample_rate = 0;
506 // Read out the sample rate
509 const int ret = sr_config_get(sdi->driver, sdi, NULL,
510 SR_CONF_SAMPLERATE, &gvar);
512 qDebug("Failed to get samplerate\n");
516 sample_rate = g_variant_get_uint64(gvar);
517 g_variant_unref(gvar);
520 // Set the sample rate of all data
521 const set< shared_ptr<data::SignalData> > data_set = get_data();
522 BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
524 data->set_samplerate(sample_rate);
528 void SigSession::load_session_thread_proc(
529 function<void (const QString)> error_handler)
533 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
535 set_capture_state(Running);
539 sr_session_destroy();
540 set_capture_state(Stopped);
542 // Confirm that SR_DF_END was received
543 assert(!_cur_logic_snapshot);
544 assert(_cur_analog_snapshots.empty());
547 void SigSession::load_input_thread_proc(const string name,
548 sr_input *in, function<void (const QString)> error_handler)
555 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
557 set_capture_state(Running);
559 in->format->loadfile(in, name.c_str());
561 sr_session_destroy();
562 set_capture_state(Stopped);
564 // Confirm that SR_DF_END was received
565 assert(!_cur_logic_snapshot);
566 assert(_cur_analog_snapshots.empty());
571 void SigSession::sample_thread_proc(shared_ptr<DevInst> dev_inst,
572 function<void (const QString)> error_handler)
575 assert(dev_inst->dev_inst());
576 assert(error_handler);
579 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
581 if (sr_session_dev_add(dev_inst->dev_inst()) != SR_OK) {
582 error_handler(tr("Failed to use device."));
583 sr_session_destroy();
587 if (sr_session_start() != SR_OK) {
588 error_handler(tr("Failed to start session."));
592 set_capture_state(is_trigger_enabled() ? AwaitingTrigger : Running);
595 sr_session_destroy();
597 set_capture_state(Stopped);
599 // Confirm that SR_DF_END was received
600 if (_cur_logic_snapshot)
602 qDebug("SR_DF_END was not received.");
607 void SigSession::feed_in_header(const sr_dev_inst *sdi)
609 read_sample_rate(sdi);
612 void SigSession::feed_in_meta(const sr_dev_inst *sdi,
613 const sr_datafeed_meta &meta)
617 for (const GSList *l = meta.config; l; l = l->next) {
618 const sr_config *const src = (const sr_config*)l->data;
620 case SR_CONF_SAMPLERATE:
621 /// @todo handle samplerate changes
622 /// samplerate = (uint64_t *)src->value;
625 // Unknown metadata is not an error.
633 void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
635 lock_guard<mutex> lock(_data_mutex);
639 qDebug() << "Unexpected logic packet";
643 if (!_cur_logic_snapshot)
645 // This could be the first packet after a trigger
646 set_capture_state(Running);
648 // Create a new data snapshot
649 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
650 new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
651 _logic_data->push_snapshot(_cur_logic_snapshot);
655 // Append to the existing data snapshot
656 _cur_logic_snapshot->append_payload(logic);
662 void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
664 lock_guard<mutex> lock(_data_mutex);
666 const unsigned int probe_count = g_slist_length(analog.probes);
667 const size_t sample_count = analog.num_samples / probe_count;
668 const float *data = analog.data;
669 bool sweep_beginning = false;
671 for (GSList *p = analog.probes; p; p = p->next)
673 shared_ptr<data::AnalogSnapshot> snapshot;
675 sr_probe *const probe = (sr_probe*)p->data;
678 // Try to get the snapshot of the probe
679 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
680 iterator iter = _cur_analog_snapshots.find(probe);
681 if (iter != _cur_analog_snapshots.end())
682 snapshot = (*iter).second;
685 // If no snapshot was found, this means we havn't
686 // created one yet. i.e. this is the first packet
687 // in the sweep containing this snapshot.
688 sweep_beginning = true;
690 // Create a snapshot, keep it in the maps of probes
691 snapshot = shared_ptr<data::AnalogSnapshot>(
692 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
693 _cur_analog_snapshots[probe] = snapshot;
695 // Find the annalog data associated with the probe
696 shared_ptr<view::AnalogSignal> sig =
697 dynamic_pointer_cast<view::AnalogSignal>(
698 signal_from_probe(probe));
701 shared_ptr<data::Analog> data(sig->analog_data());
704 // Push the snapshot into the analog data.
705 data->push_snapshot(snapshot);
710 // Append the samples in the snapshot
711 snapshot->append_interleaved_samples(data++, sample_count,
715 if (sweep_beginning) {
716 // This could be the first packet after a trigger
717 set_capture_state(Running);
723 void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
724 const struct sr_datafeed_packet *packet)
729 switch (packet->type) {
735 assert(packet->payload);
737 *(const sr_datafeed_meta*)packet->payload);
741 assert(packet->payload);
742 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
746 assert(packet->payload);
747 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
753 lock_guard<mutex> lock(_data_mutex);
754 _cur_logic_snapshot.reset();
755 _cur_analog_snapshots.clear();
763 void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
764 const struct sr_datafeed_packet *packet, void *cb_data)
768 _session->data_feed_in(sdi, packet);