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