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