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