]> sigrok.org Git - pulseview.git/blob - pv/sigsession.cpp
719f9ded3610b948438c65a2ebda098d76555f53
[pulseview.git] / pv / sigsession.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012 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::string;
57 using std::vector;
58
59 namespace pv {
60
61 // TODO: This should not be necessary
62 SigSession* SigSession::_session = NULL;
63
64 SigSession::SigSession(DeviceManager &device_manager) :
65         _device_manager(device_manager),
66         _sdi(NULL),
67         _capture_state(Stopped)
68 {
69         // TODO: This should not be necessary
70         _session = this;
71 }
72
73 SigSession::~SigSession()
74 {
75         stop_capture();
76
77         _sampling_thread.join();
78
79         if (_sdi)
80                 _device_manager.release_device(_sdi);
81         _sdi = NULL;
82
83         // TODO: This should not be necessary
84         _session = NULL;
85 }
86
87 struct sr_dev_inst* SigSession::get_device() const
88 {
89         return _sdi;
90 }
91
92 void SigSession::set_device(struct sr_dev_inst *sdi)
93 {
94         // Ensure we are not capturing before setting the device
95         stop_capture();
96
97         if (_sdi)
98                 _device_manager.release_device(_sdi);
99         if (sdi)
100                 _device_manager.use_device(sdi, this);
101         _sdi = sdi;
102         update_signals(sdi);
103 }
104
105 void SigSession::release_device(struct sr_dev_inst *sdi)
106 {
107         (void)sdi;
108
109         assert(_capture_state == Stopped);
110         _sdi = NULL;
111         update_signals(NULL);
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                 sr_dev_inst *const sdi = (sr_dev_inst*)devlist->data;
130                 g_slist_free(devlist);
131
132                 _decode_traces.clear();
133                 update_signals(sdi);
134                 read_sample_rate(sdi);
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(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(uint64_t record_length,
164         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,
191                 record_length, error_handler);
192 }
193
194 void SigSession::stop_capture()
195 {
196         if (get_capture_state() == Stopped)
197                 return;
198
199         sr_session_stop();
200
201         // Check that sampling stopped
202         _sampling_thread.join();
203 }
204
205 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
206 {
207         lock_guard<mutex> lock(_signals_mutex);
208         return _signals;
209 }
210
211 boost::shared_ptr<data::Logic> SigSession::get_data()
212 {
213         return _logic_data;
214 }
215
216 #ifdef ENABLE_DECODE
217 bool SigSession::add_decoder(srd_decoder *const dec)
218 {
219         map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
220         shared_ptr<data::DecoderStack> decoder_stack;
221
222         try
223         {
224                 lock_guard<mutex> lock(_signals_mutex);
225
226                 // Create the decoder
227                 decoder_stack = shared_ptr<data::DecoderStack>(
228                         new data::DecoderStack(dec));
229
230                 // Auto select the initial probes
231                 for(const GSList *i = dec->probes; i; i = i->next)
232                 {
233                         const srd_probe *const probe = (const srd_probe*)i->data;
234                         BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
235                         {
236                                 shared_ptr<view::LogicSignal> l =
237                                         dynamic_pointer_cast<view::LogicSignal>(s);
238                                 if (l && QString::fromUtf8(probe->name).
239                                         toLower().contains(
240                                         l->get_name().toLower()))
241                                         probes[probe] = l;
242                         }
243                 }
244
245                 assert(decoder_stack);
246                 assert(!decoder_stack->stack().empty());
247                 assert(decoder_stack->stack().front());
248                 decoder_stack->stack().front()->set_probes(probes);
249
250                 // Create the decode signal
251                 shared_ptr<view::DecodeTrace> d(
252                         new view::DecodeTrace(*this, decoder_stack,
253                                 _decode_traces.size()));
254                 _decode_traces.push_back(d);
255         }
256         catch(std::runtime_error e)
257         {
258                 return false;
259         }
260
261         signals_changed();
262
263         // Do an initial decode
264         decoder_stack->begin_decode();
265
266         return true;
267 }
268
269 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
270 {
271         lock_guard<mutex> lock(_signals_mutex);
272         return _decode_traces;
273 }
274
275 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
276 {
277         for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
278                 _decode_traces.begin();
279                 i != _decode_traces.end();
280                 i++)
281                 if ((*i).get() == signal)
282                 {
283                         _decode_traces.erase(i);
284                         signals_changed();
285                         return;
286                 }
287 }
288 #endif
289
290 void SigSession::set_capture_state(capture_state state)
291 {
292         lock_guard<mutex> lock(_sampling_mutex);
293         const bool changed = _capture_state != state;
294         _capture_state = state;
295         if(changed)
296                 capture_state_changed(state);
297 }
298
299 /**
300  * Attempts to autodetect the format. Failing that
301  * @param filename The filename of the input file.
302  * @return A pointer to the 'struct sr_input_format' that should be used,
303  *         or NULL if no input format was selected or auto-detected.
304  */
305 sr_input_format* SigSession::determine_input_file_format(
306         const string &filename)
307 {
308         int i;
309
310         /* If there are no input formats, return NULL right away. */
311         sr_input_format *const *const inputs = sr_input_list();
312         if (!inputs) {
313                 g_critical("No supported input formats available.");
314                 return NULL;
315         }
316
317         /* Otherwise, try to find an input module that can handle this file. */
318         for (i = 0; inputs[i]; i++) {
319                 if (inputs[i]->format_match(filename.c_str()))
320                         break;
321         }
322
323         /* Return NULL if no input module wanted to touch this. */
324         if (!inputs[i]) {
325                 g_critical("Error: no matching input module found.");
326                 return NULL;
327         }
328
329         return inputs[i];
330 }
331
332 sr_input* SigSession::load_input_file_format(const string &filename,
333         function<void (const QString)> error_handler,
334         sr_input_format *format)
335 {
336         struct stat st;
337         sr_input *in;
338
339         if (!format && !(format =
340                 determine_input_file_format(filename.c_str()))) {
341                 /* The exact cause was already logged. */
342                 return NULL;
343         }
344
345         if (stat(filename.c_str(), &st) == -1) {
346                 error_handler(tr("Failed to load file"));
347                 return NULL;
348         }
349
350         /* Initialize the input module. */
351         if (!(in = new sr_input)) {
352                 qDebug("Failed to allocate input module.\n");
353                 return NULL;
354         }
355
356         in->format = format;
357         in->param = NULL;
358         if (in->format->init &&
359                 in->format->init(in, filename.c_str()) != SR_OK) {
360                 qDebug("Input format init failed.\n");
361                 return NULL;
362         }
363
364         sr_session_new();
365
366         if (sr_session_dev_add(in->sdi) != SR_OK) {
367                 qDebug("Failed to use device.\n");
368                 sr_session_destroy();
369                 return NULL;
370         }
371
372         return in;
373 }
374
375 void SigSession::update_signals(const sr_dev_inst *const sdi)
376 {
377         assert(_capture_state == Stopped);
378
379         shared_ptr<view::Signal> signal;
380         unsigned int logic_probe_count = 0;
381         unsigned int analog_probe_count = 0;
382
383         // Clear the decode traces
384         _decode_traces.clear();
385
386         // Detect what data types we will receive
387         if(sdi) {
388                 for (const GSList *l = sdi->probes; l; l = l->next) {
389                         const sr_probe *const probe = (const sr_probe *)l->data;
390                         if (!probe->enabled)
391                                 continue;
392
393                         switch(probe->type) {
394                         case SR_PROBE_LOGIC:
395                                 logic_probe_count++;
396                                 break;
397
398                         case SR_PROBE_ANALOG:
399                                 analog_probe_count++;
400                                 break;
401                         }
402                 }
403         }
404
405         // Create data containers for the 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                 _analog_data.reset();
417                 if (analog_probe_count != 0) {
418                         _analog_data.reset(new data::Analog());
419                         assert(_analog_data);
420                 }
421         }
422
423         // Make the Signals list
424         {
425                 lock_guard<mutex> lock(_signals_mutex);
426
427                 _signals.clear();
428
429                 if(sdi) {
430                         for (const GSList *l = sdi->probes; l; l = l->next) {
431                                 sr_probe *const probe = (sr_probe *)l->data;
432                                 assert(probe);
433
434                                 switch(probe->type) {
435                                 case SR_PROBE_LOGIC:
436                                         signal = shared_ptr<view::Signal>(
437                                                 new view::LogicSignal(*this, probe,
438                                                         _logic_data));
439                                         break;
440
441                                 case SR_PROBE_ANALOG:
442                                         signal = shared_ptr<view::Signal>(
443                                                 new view::AnalogSignal(*this, probe,
444                                                         _analog_data));
445                                         break;
446                                 }
447
448                                 _signals.push_back(signal);
449                         }
450                 }
451         }
452
453         signals_changed();
454 }
455
456 bool SigSession::is_trigger_enabled() const
457 {
458         assert(_sdi);
459         for (const GSList *l = _sdi->probes; l; l = l->next) {
460                 const sr_probe *const p = (const sr_probe *)l->data;
461                 assert(p);
462                 if (p->trigger && p->trigger[0] != '\0')
463                         return true;
464         }
465
466         return false;
467 }
468
469 void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
470 {
471         GVariant *gvar;
472         uint64_t sample_rate = 0;
473
474         // Read out the sample rate
475         if(sdi->driver)
476         {
477                 const int ret = sr_config_get(sdi->driver, sdi, NULL,
478                         SR_CONF_SAMPLERATE, &gvar);
479                 if (ret != SR_OK) {
480                         qDebug("Failed to get samplerate\n");
481                         return;
482                 }
483
484                 sample_rate = g_variant_get_uint64(gvar);
485                 g_variant_unref(gvar);
486         }
487
488         if(_analog_data)
489                 _analog_data->set_samplerate(sample_rate);
490         if(_logic_data)
491                 _logic_data->set_samplerate(sample_rate);
492 }
493
494 void SigSession::load_session_thread_proc(
495         function<void (const QString)> error_handler)
496 {
497         (void)error_handler;
498
499         sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
500
501         set_capture_state(Running);
502
503         sr_session_run();
504
505         sr_session_destroy();
506         set_capture_state(Stopped);
507
508         // Confirm that SR_DF_END was received
509         assert(!_cur_logic_snapshot);
510         assert(!_cur_analog_snapshot);
511 }
512
513 void SigSession::load_input_thread_proc(const string name,
514         sr_input *in, function<void (const QString)> error_handler)
515 {
516         (void)error_handler;
517
518         assert(in);
519         assert(in->format);
520
521         sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
522
523         set_capture_state(Running);
524
525         in->format->loadfile(in, name.c_str());
526
527         sr_session_destroy();
528         set_capture_state(Stopped);
529
530         // Confirm that SR_DF_END was received
531         assert(!_cur_logic_snapshot);
532         assert(!_cur_analog_snapshot);
533
534         delete in;
535 }
536
537 void SigSession::sample_thread_proc(struct sr_dev_inst *sdi,
538         uint64_t record_length,
539         function<void (const QString)> error_handler)
540 {
541         assert(sdi);
542         assert(error_handler);
543
544         sr_session_new();
545         sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
546
547         if (sr_session_dev_add(sdi) != SR_OK) {
548                 error_handler(tr("Failed to use device."));
549                 sr_session_destroy();
550                 return;
551         }
552
553         // Set the sample limit
554         if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES,
555                 g_variant_new_uint64(record_length)) != SR_OK) {
556                 error_handler(tr("Failed to configure "
557                         "time-based sample limit."));
558                 sr_session_destroy();
559                 return;
560         }
561
562         if (sr_session_start() != SR_OK) {
563                 error_handler(tr("Failed to start session."));
564                 return;
565         }
566
567         set_capture_state(is_trigger_enabled() ? AwaitingTrigger : Running);
568
569         sr_session_run();
570         sr_session_destroy();
571
572         set_capture_state(Stopped);
573
574         // Confirm that SR_DF_END was received
575         assert(!_cur_logic_snapshot);
576         assert(!_cur_analog_snapshot);
577 }
578
579 void SigSession::feed_in_header(const sr_dev_inst *sdi)
580 {
581         read_sample_rate(sdi);
582 }
583
584 void SigSession::feed_in_meta(const sr_dev_inst *sdi,
585         const sr_datafeed_meta &meta)
586 {
587         (void)sdi;
588
589         for (const GSList *l = meta.config; l; l = l->next) {
590                 const sr_config *const src = (const sr_config*)l->data;
591                 switch (src->key) {
592                 case SR_CONF_SAMPLERATE:
593                         /// @todo handle samplerate changes
594                         /// samplerate = (uint64_t *)src->value;
595                         break;
596                 default:
597                         // Unknown metadata is not an error.
598                         break;
599                 }
600         }
601
602         signals_changed();
603 }
604
605 void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
606 {
607         lock_guard<mutex> lock(_data_mutex);
608
609         if (!_logic_data)
610         {
611                 qDebug() << "Unexpected logic packet";
612                 return;
613         }
614
615         if (!_cur_logic_snapshot)
616         {
617                 set_capture_state(Running);
618
619                 // Create a new data snapshot
620                 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
621                         new data::LogicSnapshot(logic));
622                 _logic_data->push_snapshot(_cur_logic_snapshot);
623         }
624         else
625         {
626                 // Append to the existing data snapshot
627                 _cur_logic_snapshot->append_payload(logic);
628         }
629
630         data_updated();
631 }
632
633 void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
634 {
635         lock_guard<mutex> lock(_data_mutex);
636
637         if(!_analog_data)
638         {
639                 qDebug() << "Unexpected analog packet";
640                 return; // This analog packet was not expected.
641         }
642
643         if (!_cur_analog_snapshot)
644         {
645                 set_capture_state(Running);
646
647                 // Create a new data snapshot
648                 _cur_analog_snapshot = shared_ptr<data::AnalogSnapshot>(
649                         new data::AnalogSnapshot(analog));
650                 _analog_data->push_snapshot(_cur_analog_snapshot);
651         }
652         else
653         {
654                 // Append to the existing data snapshot
655                 _cur_analog_snapshot->append_payload(analog);
656         }
657
658         data_updated();
659 }
660
661 void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
662         const struct sr_datafeed_packet *packet)
663 {
664         assert(sdi);
665         assert(packet);
666
667         switch (packet->type) {
668         case SR_DF_HEADER:
669                 feed_in_header(sdi);
670                 break;
671
672         case SR_DF_META:
673                 assert(packet->payload);
674                 feed_in_meta(sdi,
675                         *(const sr_datafeed_meta*)packet->payload);
676                 break;
677
678         case SR_DF_LOGIC:
679                 assert(packet->payload);
680                 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
681                 break;
682
683         case SR_DF_ANALOG:
684                 assert(packet->payload);
685                 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
686                 break;
687
688         case SR_DF_END:
689         {
690                 {
691                         lock_guard<mutex> lock(_data_mutex);
692                         _cur_logic_snapshot.reset();
693                         _cur_analog_snapshot.reset();
694                 }
695                 data_updated();
696                 break;
697         }
698         }
699 }
700
701 void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
702         const struct sr_datafeed_packet *packet, void *cb_data)
703 {
704         (void) cb_data;
705         assert(_session);
706         _session->data_feed_in(sdi, packet);
707 }
708
709 } // namespace pv