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