]> sigrok.org Git - pulseview.git/blame_incremental - pv/sigsession.cpp
Feed analog data into separate deinterleaved analog data objects per channel
[pulseview.git] / pv / sigsession.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
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.
10 *
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.
15 *
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
19 */
20
21#ifdef ENABLE_DECODE
22#include <libsigrokdecode/libsigrokdecode.h>
23#endif
24
25#include "sigsession.h"
26
27#include "devicemanager.h"
28
29#include "data/analog.h"
30#include "data/analogsnapshot.h"
31#include "data/decoderstack.h"
32#include "data/logic.h"
33#include "data/logicsnapshot.h"
34#include "data/decode/decoder.h"
35
36#include "view/analogsignal.h"
37#include "view/decodetrace.h"
38#include "view/logicsignal.h"
39
40#include <assert.h>
41
42#include <stdexcept>
43
44#include <boost/foreach.hpp>
45
46#include <sys/stat.h>
47
48#include <QDebug>
49
50using boost::dynamic_pointer_cast;
51using boost::function;
52using boost::lock_guard;
53using boost::mutex;
54using boost::shared_ptr;
55using std::map;
56using std::set;
57using std::string;
58using std::vector;
59
60namespace pv {
61
62// TODO: This should not be necessary
63SigSession* SigSession::_session = NULL;
64
65SigSession::SigSession(DeviceManager &device_manager) :
66 _device_manager(device_manager),
67 _sdi(NULL),
68 _capture_state(Stopped)
69{
70 // TODO: This should not be necessary
71 _session = this;
72}
73
74SigSession::~SigSession()
75{
76 stop_capture();
77
78 _sampling_thread.join();
79
80 if (_sdi)
81 _device_manager.release_device(_sdi);
82 _sdi = NULL;
83
84 // TODO: This should not be necessary
85 _session = NULL;
86}
87
88struct sr_dev_inst* SigSession::get_device() const
89{
90 return _sdi;
91}
92
93void SigSession::set_device(struct sr_dev_inst *sdi)
94{
95 // Ensure we are not capturing before setting the device
96 stop_capture();
97
98 if (_sdi)
99 _device_manager.release_device(_sdi);
100 if (sdi)
101 _device_manager.use_device(sdi, this);
102 _sdi = sdi;
103 update_signals(sdi);
104}
105
106void SigSession::release_device(struct sr_dev_inst *sdi)
107{
108 (void)sdi;
109
110 assert(_capture_state == Stopped);
111 _sdi = NULL;
112 update_signals(NULL);
113}
114
115void SigSession::load_file(const string &name,
116 function<void (const QString)> error_handler)
117{
118 stop_capture();
119
120 if (sr_session_load(name.c_str()) == SR_OK) {
121 GSList *devlist = NULL;
122 sr_session_dev_list(&devlist);
123
124 if (!devlist || !devlist->data ||
125 sr_session_start() != SR_OK) {
126 error_handler(tr("Failed to start session."));
127 return;
128 }
129
130 sr_dev_inst *const sdi = (sr_dev_inst*)devlist->data;
131 g_slist_free(devlist);
132
133 _decode_traces.clear();
134 update_signals(sdi);
135 read_sample_rate(sdi);
136
137 _sampling_thread = boost::thread(
138 &SigSession::load_session_thread_proc, this,
139 error_handler);
140
141 } else {
142 sr_input *in = NULL;
143
144 if (!(in = load_input_file_format(name.c_str(),
145 error_handler)))
146 return;
147
148 _decode_traces.clear();
149 update_signals(in->sdi);
150 read_sample_rate(in->sdi);
151
152 _sampling_thread = boost::thread(
153 &SigSession::load_input_thread_proc, this,
154 name, in, error_handler);
155 }
156}
157
158SigSession::capture_state SigSession::get_capture_state() const
159{
160 lock_guard<mutex> lock(_sampling_mutex);
161 return _capture_state;
162}
163
164void SigSession::start_capture(uint64_t record_length,
165 function<void (const QString)> error_handler)
166{
167 stop_capture();
168
169 // Check that a device instance has been selected.
170 if (!_sdi) {
171 qDebug() << "No device selected";
172 return;
173 }
174
175 // Check that at least one probe is enabled
176 const GSList *l;
177 for (l = _sdi->probes; l; l = l->next) {
178 sr_probe *const probe = (sr_probe*)l->data;
179 assert(probe);
180 if (probe->enabled)
181 break;
182 }
183
184 if (!l) {
185 error_handler(tr("No probes enabled."));
186 return;
187 }
188
189 // Begin the session
190 _sampling_thread = boost::thread(
191 &SigSession::sample_thread_proc, this, _sdi,
192 record_length, error_handler);
193}
194
195void SigSession::stop_capture()
196{
197 if (get_capture_state() == Stopped)
198 return;
199
200 sr_session_stop();
201
202 // Check that sampling stopped
203 _sampling_thread.join();
204}
205
206set< shared_ptr<data::SignalData> > SigSession::get_data() const
207{
208 lock_guard<mutex> lock(_signals_mutex);
209 set< shared_ptr<data::SignalData> > data;
210 BOOST_FOREACH(const shared_ptr<view::Signal> sig, _signals) {
211 assert(sig);
212 data.insert(sig->data());
213 }
214
215 return data;
216}
217
218vector< shared_ptr<view::Signal> > SigSession::get_signals() const
219{
220 lock_guard<mutex> lock(_signals_mutex);
221 return _signals;
222}
223
224#ifdef ENABLE_DECODE
225bool SigSession::add_decoder(srd_decoder *const dec)
226{
227 map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
228 shared_ptr<data::DecoderStack> decoder_stack;
229
230 try
231 {
232 lock_guard<mutex> lock(_signals_mutex);
233
234 // Create the decoder
235 decoder_stack = shared_ptr<data::DecoderStack>(
236 new data::DecoderStack(dec));
237
238 // Auto select the initial probes
239 for(const GSList *i = dec->probes; i; i = i->next)
240 {
241 const srd_probe *const probe = (const srd_probe*)i->data;
242 BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
243 {
244 shared_ptr<view::LogicSignal> l =
245 dynamic_pointer_cast<view::LogicSignal>(s);
246 if (l && QString::fromUtf8(probe->name).
247 toLower().contains(
248 l->get_name().toLower()))
249 probes[probe] = l;
250 }
251 }
252
253 assert(decoder_stack);
254 assert(!decoder_stack->stack().empty());
255 assert(decoder_stack->stack().front());
256 decoder_stack->stack().front()->set_probes(probes);
257
258 // Create the decode signal
259 shared_ptr<view::DecodeTrace> d(
260 new view::DecodeTrace(*this, decoder_stack,
261 _decode_traces.size()));
262 _decode_traces.push_back(d);
263 }
264 catch(std::runtime_error e)
265 {
266 return false;
267 }
268
269 signals_changed();
270
271 // Do an initial decode
272 decoder_stack->begin_decode();
273
274 return true;
275}
276
277vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
278{
279 lock_guard<mutex> lock(_signals_mutex);
280 return _decode_traces;
281}
282
283void SigSession::remove_decode_signal(view::DecodeTrace *signal)
284{
285 for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
286 _decode_traces.begin();
287 i != _decode_traces.end();
288 i++)
289 if ((*i).get() == signal)
290 {
291 _decode_traces.erase(i);
292 signals_changed();
293 return;
294 }
295}
296#endif
297
298void SigSession::set_capture_state(capture_state state)
299{
300 lock_guard<mutex> lock(_sampling_mutex);
301 const bool changed = _capture_state != state;
302 _capture_state = state;
303 if(changed)
304 capture_state_changed(state);
305}
306
307/**
308 * Attempts to autodetect the format. Failing that
309 * @param filename The filename of the input file.
310 * @return A pointer to the 'struct sr_input_format' that should be used,
311 * or NULL if no input format was selected or auto-detected.
312 */
313sr_input_format* SigSession::determine_input_file_format(
314 const string &filename)
315{
316 int i;
317
318 /* If there are no input formats, return NULL right away. */
319 sr_input_format *const *const inputs = sr_input_list();
320 if (!inputs) {
321 g_critical("No supported input formats available.");
322 return NULL;
323 }
324
325 /* Otherwise, try to find an input module that can handle this file. */
326 for (i = 0; inputs[i]; i++) {
327 if (inputs[i]->format_match(filename.c_str()))
328 break;
329 }
330
331 /* Return NULL if no input module wanted to touch this. */
332 if (!inputs[i]) {
333 g_critical("Error: no matching input module found.");
334 return NULL;
335 }
336
337 return inputs[i];
338}
339
340sr_input* SigSession::load_input_file_format(const string &filename,
341 function<void (const QString)> error_handler,
342 sr_input_format *format)
343{
344 struct stat st;
345 sr_input *in;
346
347 if (!format && !(format =
348 determine_input_file_format(filename.c_str()))) {
349 /* The exact cause was already logged. */
350 return NULL;
351 }
352
353 if (stat(filename.c_str(), &st) == -1) {
354 error_handler(tr("Failed to load file"));
355 return NULL;
356 }
357
358 /* Initialize the input module. */
359 if (!(in = new sr_input)) {
360 qDebug("Failed to allocate input module.\n");
361 return NULL;
362 }
363
364 in->format = format;
365 in->param = NULL;
366 if (in->format->init &&
367 in->format->init(in, filename.c_str()) != SR_OK) {
368 qDebug("Input format init failed.\n");
369 return NULL;
370 }
371
372 sr_session_new();
373
374 if (sr_session_dev_add(in->sdi) != SR_OK) {
375 qDebug("Failed to use device.\n");
376 sr_session_destroy();
377 return NULL;
378 }
379
380 return in;
381}
382
383void SigSession::update_signals(const sr_dev_inst *const sdi)
384{
385 assert(_capture_state == Stopped);
386
387 unsigned int logic_probe_count = 0;
388
389 // Clear the decode traces
390 _decode_traces.clear();
391
392 // Detect what data types we will receive
393 if(sdi) {
394 for (const GSList *l = sdi->probes; l; l = l->next) {
395 const sr_probe *const probe = (const sr_probe *)l->data;
396 if (!probe->enabled)
397 continue;
398
399 switch(probe->type) {
400 case SR_PROBE_LOGIC:
401 logic_probe_count++;
402 break;
403 }
404 }
405 }
406
407 // Create data containers for the logic data snapshots
408 {
409 lock_guard<mutex> data_lock(_data_mutex);
410
411 _logic_data.reset();
412 if (logic_probe_count != 0) {
413 _logic_data.reset(new data::Logic(
414 logic_probe_count));
415 assert(_logic_data);
416 }
417 }
418
419 // Make the Signals list
420 do {
421 lock_guard<mutex> lock(_signals_mutex);
422
423 _signals.clear();
424
425 if(!sdi)
426 break;
427
428 for (const GSList *l = sdi->probes; l; l = l->next) {
429 shared_ptr<view::Signal> signal;
430 sr_probe *const probe = (sr_probe *)l->data;
431 assert(probe);
432
433 switch(probe->type) {
434 case SR_PROBE_LOGIC:
435 signal = shared_ptr<view::Signal>(
436 new view::LogicSignal(*this, probe,
437 _logic_data));
438 break;
439
440 case SR_PROBE_ANALOG:
441 {
442 shared_ptr<data::Analog> data(
443 new data::Analog());
444 signal = shared_ptr<view::Signal>(
445 new view::AnalogSignal(*this, probe,
446 data));
447 break;
448 }
449
450 default:
451 assert(0);
452 break;
453 }
454
455 assert(signal);
456 _signals.push_back(signal);
457 }
458
459 } while(0);
460
461 signals_changed();
462}
463
464bool SigSession::is_trigger_enabled() const
465{
466 assert(_sdi);
467 for (const GSList *l = _sdi->probes; l; l = l->next) {
468 const sr_probe *const p = (const sr_probe *)l->data;
469 assert(p);
470 if (p->trigger && p->trigger[0] != '\0')
471 return true;
472 }
473
474 return false;
475}
476
477shared_ptr<view::Signal> SigSession::signal_from_probe(
478 const sr_probe *probe) const
479{
480 lock_guard<mutex> lock(_signals_mutex);
481 BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
482 assert(sig);
483 if (sig->probe() == probe)
484 return sig;
485 }
486 return shared_ptr<view::Signal>();
487}
488
489void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
490{
491 GVariant *gvar;
492 uint64_t sample_rate = 0;
493
494 // Read out the sample rate
495 if(sdi->driver)
496 {
497 const int ret = sr_config_get(sdi->driver, sdi, NULL,
498 SR_CONF_SAMPLERATE, &gvar);
499 if (ret != SR_OK) {
500 qDebug("Failed to get samplerate\n");
501 return;
502 }
503
504 sample_rate = g_variant_get_uint64(gvar);
505 g_variant_unref(gvar);
506 }
507
508 // Set the sample rate of all data
509 const set< shared_ptr<data::SignalData> > data_set = get_data();
510 BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
511 assert(data);
512 data->set_samplerate(sample_rate);
513 }
514}
515
516void SigSession::load_session_thread_proc(
517 function<void (const QString)> error_handler)
518{
519 (void)error_handler;
520
521 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
522
523 set_capture_state(Running);
524
525 sr_session_run();
526
527 sr_session_destroy();
528 set_capture_state(Stopped);
529
530 // Confirm that SR_DF_END was received
531 assert(!_cur_logic_snapshot);
532 assert(_cur_analog_snapshots.empty());
533}
534
535void SigSession::load_input_thread_proc(const string name,
536 sr_input *in, function<void (const QString)> error_handler)
537{
538 (void)error_handler;
539
540 assert(in);
541 assert(in->format);
542
543 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
544
545 set_capture_state(Running);
546
547 in->format->loadfile(in, name.c_str());
548
549 sr_session_destroy();
550 set_capture_state(Stopped);
551
552 // Confirm that SR_DF_END was received
553 assert(!_cur_logic_snapshot);
554 assert(_cur_analog_snapshots.empty());
555
556 delete in;
557}
558
559void SigSession::sample_thread_proc(struct sr_dev_inst *sdi,
560 uint64_t record_length,
561 function<void (const QString)> error_handler)
562{
563 assert(sdi);
564 assert(error_handler);
565
566 sr_session_new();
567 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
568
569 if (sr_session_dev_add(sdi) != SR_OK) {
570 error_handler(tr("Failed to use device."));
571 sr_session_destroy();
572 return;
573 }
574
575 // Set the sample limit
576 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES,
577 g_variant_new_uint64(record_length)) != SR_OK) {
578 error_handler(tr("Failed to configure "
579 "time-based sample limit."));
580 sr_session_destroy();
581 return;
582 }
583
584 if (sr_session_start() != SR_OK) {
585 error_handler(tr("Failed to start session."));
586 return;
587 }
588
589 set_capture_state(is_trigger_enabled() ? AwaitingTrigger : Running);
590
591 sr_session_run();
592 sr_session_destroy();
593
594 set_capture_state(Stopped);
595
596 // Confirm that SR_DF_END was received
597 if (_cur_logic_snapshot)
598 {
599 qDebug("SR_DF_END was not received.");
600 assert(0);
601 }
602}
603
604void SigSession::feed_in_header(const sr_dev_inst *sdi)
605{
606 read_sample_rate(sdi);
607}
608
609void SigSession::feed_in_meta(const sr_dev_inst *sdi,
610 const sr_datafeed_meta &meta)
611{
612 (void)sdi;
613
614 for (const GSList *l = meta.config; l; l = l->next) {
615 const sr_config *const src = (const sr_config*)l->data;
616 switch (src->key) {
617 case SR_CONF_SAMPLERATE:
618 /// @todo handle samplerate changes
619 /// samplerate = (uint64_t *)src->value;
620 break;
621 default:
622 // Unknown metadata is not an error.
623 break;
624 }
625 }
626
627 signals_changed();
628}
629
630void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
631{
632 lock_guard<mutex> lock(_data_mutex);
633
634 if (!_logic_data)
635 {
636 qDebug() << "Unexpected logic packet";
637 return;
638 }
639
640 if (!_cur_logic_snapshot)
641 {
642 // This could be the first packet after a trigger
643 set_capture_state(Running);
644
645 // Create a new data snapshot
646 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
647 new data::LogicSnapshot(logic));
648 _logic_data->push_snapshot(_cur_logic_snapshot);
649 }
650 else
651 {
652 // Append to the existing data snapshot
653 _cur_logic_snapshot->append_payload(logic);
654 }
655
656 data_updated();
657}
658
659void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
660{
661 lock_guard<mutex> lock(_data_mutex);
662
663 const unsigned int probe_count = g_slist_length(analog.probes);
664 const size_t sample_count = analog.num_samples / probe_count;
665 const float *data = analog.data;
666 bool sweep_beginning = false;
667
668 for (GSList *p = analog.probes; p; p = p->next)
669 {
670 shared_ptr<data::AnalogSnapshot> snapshot;
671
672 sr_probe *const probe = (sr_probe*)p->data;
673 assert(probe);
674
675 // Try to get the snapshot of the probe
676 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
677 iterator iter = _cur_analog_snapshots.find(probe);
678 if (iter != _cur_analog_snapshots.end())
679 snapshot = (*iter).second;
680 else
681 {
682 // If no snapshot was found, this means we havn't
683 // created one yet. i.e. this is the first packet
684 // in the sweep containing this snapshot.
685 sweep_beginning = true;
686
687 // Create a snapshot, keep it in the maps of probes
688 snapshot = shared_ptr<data::AnalogSnapshot>(
689 new data::AnalogSnapshot());
690 _cur_analog_snapshots[probe] = snapshot;
691
692 // Find the annalog data associated with the probe
693 shared_ptr<view::AnalogSignal> sig =
694 dynamic_pointer_cast<view::AnalogSignal>(
695 signal_from_probe(probe));
696 assert(sig);
697
698 shared_ptr<data::Analog> data(sig->analog_data());
699 assert(data);
700
701 // Push the snapshot into the analog data.
702 data->push_snapshot(snapshot);
703 }
704
705 assert(snapshot);
706
707 // Append the samples in the snapshot
708 snapshot->append_interleaved_samples(data++, sample_count,
709 probe_count);
710 }
711
712 if (sweep_beginning) {
713 // This could be the first packet after a trigger
714 set_capture_state(Running);
715 }
716
717 data_updated();
718}
719
720void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
721 const struct sr_datafeed_packet *packet)
722{
723 assert(sdi);
724 assert(packet);
725
726 switch (packet->type) {
727 case SR_DF_HEADER:
728 feed_in_header(sdi);
729 break;
730
731 case SR_DF_META:
732 assert(packet->payload);
733 feed_in_meta(sdi,
734 *(const sr_datafeed_meta*)packet->payload);
735 break;
736
737 case SR_DF_LOGIC:
738 assert(packet->payload);
739 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
740 break;
741
742 case SR_DF_ANALOG:
743 assert(packet->payload);
744 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
745 break;
746
747 case SR_DF_END:
748 {
749 {
750 lock_guard<mutex> lock(_data_mutex);
751 _cur_logic_snapshot.reset();
752 _cur_analog_snapshots.clear();
753 }
754 data_updated();
755 break;
756 }
757 }
758}
759
760void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
761 const struct sr_datafeed_packet *packet, void *cb_data)
762{
763 (void) cb_data;
764 assert(_session);
765 _session->data_feed_in(sdi, packet);
766}
767
768} // namespace pv