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