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