]> sigrok.org Git - pulseview.git/blame_incremental - pv/sigsession.cpp
DecoderStack: Fixed thread dead-lock
[pulseview.git] / pv / sigsession.cpp
... / ...
CommitLineData
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#include "device/file.h"
30
31#include "data/analog.h"
32#include "data/analogsnapshot.h"
33#include "data/decoderstack.h"
34#include "data/logic.h"
35#include "data/logicsnapshot.h"
36#include "data/decode/decoder.h"
37
38#include "view/analogsignal.h"
39#include "view/decodetrace.h"
40#include "view/logicsignal.h"
41
42#include <cassert>
43#include <mutex>
44#include <stdexcept>
45
46#include <sys/stat.h>
47
48#include <QDebug>
49
50using std::dynamic_pointer_cast;
51using std::function;
52using std::lock_guard;
53using std::mutex;
54using std::list;
55using std::map;
56using std::set;
57using std::shared_ptr;
58using std::string;
59using std::vector;
60
61namespace pv {
62
63// TODO: This should not be necessary
64SigSession* SigSession::_session = NULL;
65
66SigSession::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 set_default_device();
74}
75
76SigSession::~SigSession()
77{
78 using pv::device::Device;
79
80 // Stop and join to the thread
81 stop_capture();
82
83 _dev_inst->release();
84
85 // TODO: This should not be necessary
86 _session = NULL;
87}
88
89shared_ptr<device::DevInst> SigSession::get_device() const
90{
91 return _dev_inst;
92}
93
94void SigSession::set_device(
95 shared_ptr<device::DevInst> dev_inst) throw(QString)
96{
97 using pv::device::Device;
98
99 // Ensure we are not capturing before setting the device
100 stop_capture();
101
102 if (_dev_inst) {
103 sr_session_datafeed_callback_remove_all();
104 _dev_inst->release();
105 }
106
107 _dev_inst = dev_inst;
108 _decode_traces.clear();
109
110 if (dev_inst) {
111 dev_inst->use(this);
112 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
113 update_signals(dev_inst);
114 }
115}
116
117void SigSession::set_file(const string &name) throw(QString)
118{
119 // Deselect the old device, because file type detection in File::create
120 // destroys the old session inside libsigrok.
121 set_device(shared_ptr<device::DevInst>());
122 set_device(shared_ptr<device::DevInst>(device::File::create(name)));
123}
124
125void SigSession::set_default_device()
126{
127 shared_ptr<pv::device::DevInst> default_device;
128 const list< shared_ptr<device::Device> > &devices =
129 _device_manager.devices();
130
131 if (!devices.empty()) {
132 // Fall back to the first device in the list.
133 default_device = devices.front();
134
135 // Try and find the demo device and select that by default
136 for (shared_ptr<pv::device::Device> dev : devices)
137 if (strcmp(dev->dev_inst()->driver->name,
138 "demo") == 0) {
139 default_device = dev;
140 break;
141 }
142 }
143
144 set_device(default_device);
145}
146
147void SigSession::release_device(device::DevInst *dev_inst)
148{
149 (void)dev_inst;
150 assert(_dev_inst.get() == dev_inst);
151
152 assert(_capture_state == Stopped);
153 _dev_inst = shared_ptr<device::DevInst>();
154}
155
156SigSession::capture_state SigSession::get_capture_state() const
157{
158 lock_guard<mutex> lock(_sampling_mutex);
159 return _capture_state;
160}
161
162void SigSession::start_capture(function<void (const QString)> error_handler)
163{
164 stop_capture();
165
166 // Check that a device instance has been selected.
167 if (!_dev_inst) {
168 qDebug() << "No device selected";
169 return;
170 }
171
172 assert(_dev_inst->dev_inst());
173
174 // Check that at least one probe is enabled
175 const GSList *l;
176 for (l = _dev_inst->dev_inst()->channels; l; l = l->next) {
177 sr_channel *const probe = (sr_channel*)l->data;
178 assert(probe);
179 if (probe->enabled)
180 break;
181 }
182
183 if (!l) {
184 error_handler(tr("No channels enabled."));
185 return;
186 }
187
188 // Begin the session
189 _sampling_thread = std::thread(
190 &SigSession::sample_thread_proc, this, _dev_inst,
191 error_handler);
192}
193
194void SigSession::stop_capture()
195{
196 if (get_capture_state() != Stopped)
197 sr_session_stop();
198
199 // Check that sampling stopped
200 if (_sampling_thread.joinable())
201 _sampling_thread.join();
202}
203
204set< shared_ptr<data::SignalData> > SigSession::get_data() const
205{
206 lock_guard<mutex> lock(_signals_mutex);
207 set< shared_ptr<data::SignalData> > data;
208 for (const shared_ptr<view::Signal> sig : _signals) {
209 assert(sig);
210 data.insert(sig->data());
211 }
212
213 return data;
214}
215
216vector< shared_ptr<view::Signal> > SigSession::get_signals() const
217{
218 lock_guard<mutex> lock(_signals_mutex);
219 return _signals;
220}
221
222#ifdef ENABLE_DECODE
223bool SigSession::add_decoder(srd_decoder *const dec)
224{
225 map<const srd_channel*, shared_ptr<view::LogicSignal> > probes;
226 shared_ptr<data::DecoderStack> decoder_stack;
227
228 try
229 {
230 lock_guard<mutex> lock(_signals_mutex);
231
232 // Create the decoder
233 decoder_stack = shared_ptr<data::DecoderStack>(
234 new data::DecoderStack(*this, dec));
235
236 // Make a list of all the probes
237 std::vector<const srd_channel*> all_probes;
238 for(const GSList *i = dec->channels; i; i = i->next)
239 all_probes.push_back((const srd_channel*)i->data);
240 for(const GSList *i = dec->opt_channels; i; i = i->next)
241 all_probes.push_back((const srd_channel*)i->data);
242
243 // Auto select the initial probes
244 for (const srd_channel *pdch : all_probes)
245 for (shared_ptr<view::Signal> s : _signals)
246 {
247 shared_ptr<view::LogicSignal> l =
248 dynamic_pointer_cast<view::LogicSignal>(s);
249 if (l && QString::fromUtf8(pdch->name).
250 toLower().contains(
251 l->get_name().toLower()))
252 probes[pdch] = l;
253 }
254
255 assert(decoder_stack);
256 assert(!decoder_stack->stack().empty());
257 assert(decoder_stack->stack().front());
258 decoder_stack->stack().front()->set_probes(probes);
259
260 // Create the decode signal
261 shared_ptr<view::DecodeTrace> d(
262 new view::DecodeTrace(*this, decoder_stack,
263 _decode_traces.size()));
264 _decode_traces.push_back(d);
265 }
266 catch(std::runtime_error e)
267 {
268 return false;
269 }
270
271 signals_changed();
272
273 // Do an initial decode
274 decoder_stack->begin_decode();
275
276 return true;
277}
278
279vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
280{
281 lock_guard<mutex> lock(_signals_mutex);
282 return _decode_traces;
283}
284
285void SigSession::remove_decode_signal(view::DecodeTrace *signal)
286{
287 for (auto i = _decode_traces.begin(); i != _decode_traces.end(); i++)
288 if ((*i).get() == signal)
289 {
290 _decode_traces.erase(i);
291 signals_changed();
292 return;
293 }
294}
295#endif
296
297void SigSession::set_capture_state(capture_state state)
298{
299 lock_guard<mutex> lock(_sampling_mutex);
300 const bool changed = _capture_state != state;
301 _capture_state = state;
302 if(changed)
303 capture_state_changed(state);
304}
305
306void SigSession::update_signals(shared_ptr<device::DevInst> dev_inst)
307{
308 assert(dev_inst);
309 assert(_capture_state == Stopped);
310
311 unsigned int logic_probe_count = 0;
312
313 // Clear the decode traces
314 _decode_traces.clear();
315
316 // Detect what data types we will receive
317 if(dev_inst) {
318 assert(dev_inst->dev_inst());
319 for (const GSList *l = dev_inst->dev_inst()->channels;
320 l; l = l->next) {
321 const sr_channel *const probe = (const sr_channel *)l->data;
322 if (!probe->enabled)
323 continue;
324
325 switch(probe->type) {
326 case SR_CHANNEL_LOGIC:
327 logic_probe_count++;
328 break;
329 }
330 }
331 }
332
333 // Create data containers for the logic data snapshots
334 {
335 lock_guard<mutex> data_lock(_data_mutex);
336
337 _logic_data.reset();
338 if (logic_probe_count != 0) {
339 _logic_data.reset(new data::Logic(
340 logic_probe_count));
341 assert(_logic_data);
342 }
343 }
344
345 // Make the Signals list
346 do {
347 lock_guard<mutex> lock(_signals_mutex);
348
349 _signals.clear();
350
351 if(!dev_inst)
352 break;
353
354 assert(dev_inst->dev_inst());
355 for (const GSList *l = dev_inst->dev_inst()->channels;
356 l; l = l->next) {
357 shared_ptr<view::Signal> signal;
358 sr_channel *const probe = (sr_channel *)l->data;
359 assert(probe);
360
361 switch(probe->type) {
362 case SR_CHANNEL_LOGIC:
363 signal = shared_ptr<view::Signal>(
364 new view::LogicSignal(dev_inst,
365 probe, _logic_data));
366 break;
367
368 case SR_CHANNEL_ANALOG:
369 {
370 shared_ptr<data::Analog> data(
371 new data::Analog());
372 signal = shared_ptr<view::Signal>(
373 new view::AnalogSignal(dev_inst,
374 probe, data));
375 break;
376 }
377
378 default:
379 assert(0);
380 break;
381 }
382
383 assert(signal);
384 _signals.push_back(signal);
385 }
386
387 } while(0);
388
389 signals_changed();
390}
391
392shared_ptr<view::Signal> SigSession::signal_from_probe(
393 const sr_channel *probe) const
394{
395 lock_guard<mutex> lock(_signals_mutex);
396 for (shared_ptr<view::Signal> sig : _signals) {
397 assert(sig);
398 if (sig->probe() == probe)
399 return sig;
400 }
401 return shared_ptr<view::Signal>();
402}
403
404void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
405{
406 GVariant *gvar;
407 uint64_t sample_rate = 0;
408
409 // Read out the sample rate
410 if(sdi->driver)
411 {
412 const int ret = sr_config_get(sdi->driver, sdi, NULL,
413 SR_CONF_SAMPLERATE, &gvar);
414 if (ret != SR_OK) {
415 qDebug("Failed to get samplerate\n");
416 return;
417 }
418
419 sample_rate = g_variant_get_uint64(gvar);
420 g_variant_unref(gvar);
421 }
422
423 // Set the sample rate of all data
424 const set< shared_ptr<data::SignalData> > data_set = get_data();
425 for (shared_ptr<data::SignalData> data : data_set) {
426 assert(data);
427 data->set_samplerate(sample_rate);
428 }
429}
430
431void SigSession::sample_thread_proc(shared_ptr<device::DevInst> dev_inst,
432 function<void (const QString)> error_handler)
433{
434 assert(dev_inst);
435 assert(dev_inst->dev_inst());
436 assert(error_handler);
437
438 read_sample_rate(dev_inst->dev_inst());
439
440 try {
441 dev_inst->start();
442 } catch(const QString e) {
443 error_handler(e);
444 return;
445 }
446
447 set_capture_state(sr_session_trigger_get() ?
448 AwaitingTrigger : Running);
449
450 dev_inst->run();
451 set_capture_state(Stopped);
452
453 // Confirm that SR_DF_END was received
454 if (_cur_logic_snapshot)
455 {
456 qDebug("SR_DF_END was not received.");
457 assert(0);
458 }
459}
460
461void SigSession::feed_in_header(const sr_dev_inst *sdi)
462{
463 read_sample_rate(sdi);
464}
465
466void SigSession::feed_in_meta(const sr_dev_inst *sdi,
467 const sr_datafeed_meta &meta)
468{
469 (void)sdi;
470
471 for (const GSList *l = meta.config; l; l = l->next) {
472 const sr_config *const src = (const sr_config*)l->data;
473 switch (src->key) {
474 case SR_CONF_SAMPLERATE:
475 /// @todo handle samplerate changes
476 /// samplerate = (uint64_t *)src->value;
477 break;
478 default:
479 // Unknown metadata is not an error.
480 break;
481 }
482 }
483
484 signals_changed();
485}
486
487void SigSession::feed_in_frame_begin()
488{
489 if (_cur_logic_snapshot || !_cur_analog_snapshots.empty())
490 frame_began();
491}
492
493void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
494{
495 lock_guard<mutex> lock(_data_mutex);
496
497 if (!_logic_data)
498 {
499 qDebug() << "Unexpected logic packet";
500 return;
501 }
502
503 if (!_cur_logic_snapshot)
504 {
505 // This could be the first packet after a trigger
506 set_capture_state(Running);
507
508 // Create a new data snapshot
509 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
510 new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
511 _logic_data->push_snapshot(_cur_logic_snapshot);
512
513 // @todo Putting this here means that only listeners querying
514 // for logic will be notified. Currently the only user of
515 // frame_began is DecoderStack, but in future we need to signal
516 // this after both analog and logic sweeps have begun.
517 frame_began();
518 }
519 else
520 {
521 // Append to the existing data snapshot
522 _cur_logic_snapshot->append_payload(logic);
523 }
524
525 data_received();
526}
527
528void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
529{
530 lock_guard<mutex> lock(_data_mutex);
531
532 const unsigned int probe_count = g_slist_length(analog.channels);
533 const size_t sample_count = analog.num_samples / probe_count;
534 const float *data = analog.data;
535 bool sweep_beginning = false;
536
537 for (GSList *p = analog.channels; p; p = p->next)
538 {
539 shared_ptr<data::AnalogSnapshot> snapshot;
540
541 sr_channel *const probe = (sr_channel*)p->data;
542 assert(probe);
543
544 // Try to get the snapshot of the probe
545 const map< const sr_channel*, shared_ptr<data::AnalogSnapshot> >::
546 iterator iter = _cur_analog_snapshots.find(probe);
547 if (iter != _cur_analog_snapshots.end())
548 snapshot = (*iter).second;
549 else
550 {
551 // If no snapshot was found, this means we havn't
552 // created one yet. i.e. this is the first packet
553 // in the sweep containing this snapshot.
554 sweep_beginning = true;
555
556 // Create a snapshot, keep it in the maps of probes
557 snapshot = shared_ptr<data::AnalogSnapshot>(
558 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
559 _cur_analog_snapshots[probe] = snapshot;
560
561 // Find the annalog data associated with the probe
562 shared_ptr<view::AnalogSignal> sig =
563 dynamic_pointer_cast<view::AnalogSignal>(
564 signal_from_probe(probe));
565 assert(sig);
566
567 shared_ptr<data::Analog> data(sig->analog_data());
568 assert(data);
569
570 // Push the snapshot into the analog data.
571 data->push_snapshot(snapshot);
572 }
573
574 assert(snapshot);
575
576 // Append the samples in the snapshot
577 snapshot->append_interleaved_samples(data++, sample_count,
578 probe_count);
579 }
580
581 if (sweep_beginning) {
582 // This could be the first packet after a trigger
583 set_capture_state(Running);
584 }
585
586 data_received();
587}
588
589void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
590 const struct sr_datafeed_packet *packet)
591{
592 assert(sdi);
593 assert(packet);
594
595 switch (packet->type) {
596 case SR_DF_HEADER:
597 feed_in_header(sdi);
598 break;
599
600 case SR_DF_META:
601 assert(packet->payload);
602 feed_in_meta(sdi,
603 *(const sr_datafeed_meta*)packet->payload);
604 break;
605
606 case SR_DF_FRAME_BEGIN:
607 feed_in_frame_begin();
608 break;
609
610 case SR_DF_LOGIC:
611 assert(packet->payload);
612 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
613 break;
614
615 case SR_DF_ANALOG:
616 assert(packet->payload);
617 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
618 break;
619
620 case SR_DF_END:
621 {
622 {
623 lock_guard<mutex> lock(_data_mutex);
624 _cur_logic_snapshot.reset();
625 _cur_analog_snapshots.clear();
626 }
627 frame_ended();
628 break;
629 }
630 }
631}
632
633void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
634 const struct sr_datafeed_packet *packet, void *cb_data)
635{
636 (void) cb_data;
637 assert(_session);
638 _session->data_feed_in(sdi, packet);
639}
640
641} // namespace pv