]> sigrok.org Git - pulseview.git/blame_incremental - pv/session.cpp
Reduce include bloat by including boost/thread/{locks,shared_mutex}.hpp directly
[pulseview.git] / pv / session.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#include <boost/thread/locks.hpp>
22#include <boost/thread/shared_mutex.hpp>
23
24#ifdef ENABLE_DECODE
25#include <libsigrokdecode/libsigrokdecode.h>
26#endif
27
28#include "session.hpp"
29
30#include "devicemanager.hpp"
31
32#include "data/analog.hpp"
33#include "data/analogsegment.hpp"
34#include "data/decoderstack.hpp"
35#include "data/logic.hpp"
36#include "data/logicsegment.hpp"
37#include "data/decode/decoder.hpp"
38
39#include "devices/hardwaredevice.hpp"
40#include "devices/sessionfile.hpp"
41
42#include "view/analogsignal.hpp"
43#include "view/decodetrace.hpp"
44#include "view/logicsignal.hpp"
45
46#include <cassert>
47#include <mutex>
48#include <stdexcept>
49
50#include <sys/stat.h>
51
52#include <QDebug>
53
54#include <libsigrokcxx/libsigrokcxx.hpp>
55
56using boost::shared_lock;
57using boost::shared_mutex;
58using boost::unique_lock;
59
60using std::dynamic_pointer_cast;
61using std::function;
62using std::lock_guard;
63using std::list;
64using std::map;
65using std::mutex;
66using std::recursive_mutex;
67using std::set;
68using std::shared_ptr;
69using std::string;
70using std::unordered_set;
71using std::vector;
72
73using sigrok::Analog;
74using sigrok::Channel;
75using sigrok::ChannelType;
76using sigrok::ConfigKey;
77using sigrok::DatafeedCallbackFunction;
78using sigrok::Error;
79using sigrok::Header;
80using sigrok::Logic;
81using sigrok::Meta;
82using sigrok::Packet;
83using sigrok::PacketPayload;
84using sigrok::Session;
85using sigrok::SessionDevice;
86
87using Glib::VariantBase;
88using Glib::Variant;
89
90namespace pv {
91Session::Session(DeviceManager &device_manager) :
92 device_manager_(device_manager),
93 capture_state_(Stopped),
94 cur_samplerate_(0)
95{
96}
97
98Session::~Session()
99{
100 // Stop and join to the thread
101 stop_capture();
102}
103
104DeviceManager& Session::device_manager()
105{
106 return device_manager_;
107}
108
109const DeviceManager& Session::device_manager() const
110{
111 return device_manager_;
112}
113
114shared_ptr<sigrok::Session> Session::session() const
115{
116 if (!device_)
117 return shared_ptr<sigrok::Session>();
118 return device_->session();
119}
120
121shared_ptr<devices::Device> Session::device() const
122{
123 return device_;
124}
125
126void Session::set_device(shared_ptr<devices::Device> device)
127{
128 assert(device);
129
130 // Ensure we are not capturing before setting the device
131 stop_capture();
132
133 if (device_)
134 device_->close();
135
136 device_ = std::move(device);
137 device_->open();
138 device_->session()->add_datafeed_callback([=]
139 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
140 data_feed_in(device, packet);
141 });
142 update_signals();
143
144 decode_traces_.clear();
145
146 device_selected();
147}
148
149void Session::set_default_device()
150{
151 const list< shared_ptr<devices::HardwareDevice> > &devices =
152 device_manager_.devices();
153
154 if (devices.empty())
155 return;
156
157 // Try and find the demo device and select that by default
158 const auto iter = std::find_if(devices.begin(), devices.end(),
159 [] (const shared_ptr<devices::HardwareDevice> &d) {
160 return d->hardware_device()->driver()->name() ==
161 "demo"; });
162 set_device((iter == devices.end()) ? devices.front() : *iter);
163}
164
165Session::capture_state Session::get_capture_state() const
166{
167 lock_guard<mutex> lock(sampling_mutex_);
168 return capture_state_;
169}
170
171void Session::start_capture(function<void (const QString)> error_handler)
172{
173 stop_capture();
174
175 // Check that at least one channel is enabled
176 assert(device_);
177 const shared_ptr<sigrok::Device> sr_dev = device_->device();
178 if (sr_dev) {
179 const auto channels = sr_dev->channels();
180 if (!std::any_of(channels.begin(), channels.end(),
181 [](shared_ptr<Channel> channel) {
182 return channel->enabled(); })) {
183 error_handler(tr("No channels enabled."));
184 return;
185 }
186 }
187
188 // Clear signal data
189 for (const shared_ptr<data::SignalData> d : get_data())
190 d->clear();
191
192 // Begin the session
193 sampling_thread_ = std::thread(
194 &Session::sample_thread_proc, this, device_,
195 error_handler);
196}
197
198void Session::stop_capture()
199{
200 if (get_capture_state() != Stopped)
201 device_->stop();
202
203 // Check that sampling stopped
204 if (sampling_thread_.joinable())
205 sampling_thread_.join();
206}
207
208set< shared_ptr<data::SignalData> > Session::get_data() const
209{
210 shared_lock<shared_mutex> lock(signals_mutex_);
211 set< shared_ptr<data::SignalData> > data;
212 for (const shared_ptr<view::Signal> sig : signals_) {
213 assert(sig);
214 data.insert(sig->data());
215 }
216
217 return data;
218}
219
220boost::shared_mutex& Session::signals_mutex() const
221{
222 return signals_mutex_;
223}
224
225const unordered_set< shared_ptr<view::Signal> >& Session::signals() const
226{
227 return signals_;
228}
229
230#ifdef ENABLE_DECODE
231bool Session::add_decoder(srd_decoder *const dec)
232{
233 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
234 shared_ptr<data::DecoderStack> decoder_stack;
235
236 try
237 {
238 lock_guard<boost::shared_mutex> lock(signals_mutex_);
239
240 // Create the decoder
241 decoder_stack = shared_ptr<data::DecoderStack>(
242 new data::DecoderStack(*this, dec));
243
244 // Make a list of all the channels
245 std::vector<const srd_channel*> all_channels;
246 for (const GSList *i = dec->channels; i; i = i->next)
247 all_channels.push_back((const srd_channel*)i->data);
248 for (const GSList *i = dec->opt_channels; i; i = i->next)
249 all_channels.push_back((const srd_channel*)i->data);
250
251 // Auto select the initial channels
252 for (const srd_channel *pdch : all_channels)
253 for (shared_ptr<view::Signal> s : signals_)
254 {
255 shared_ptr<view::LogicSignal> l =
256 dynamic_pointer_cast<view::LogicSignal>(s);
257 if (l && QString::fromUtf8(pdch->name).
258 toLower().contains(
259 l->name().toLower()))
260 channels[pdch] = l;
261 }
262
263 assert(decoder_stack);
264 assert(!decoder_stack->stack().empty());
265 assert(decoder_stack->stack().front());
266 decoder_stack->stack().front()->set_channels(channels);
267
268 // Create the decode signal
269 shared_ptr<view::DecodeTrace> d(
270 new view::DecodeTrace(*this, decoder_stack,
271 decode_traces_.size()));
272 decode_traces_.push_back(d);
273 }
274 catch(std::runtime_error e)
275 {
276 return false;
277 }
278
279 signals_changed();
280
281 // Do an initial decode
282 decoder_stack->begin_decode();
283
284 return true;
285}
286
287vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
288{
289 shared_lock<shared_mutex> lock(signals_mutex_);
290 return decode_traces_;
291}
292
293void Session::remove_decode_signal(view::DecodeTrace *signal)
294{
295 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
296 if ((*i).get() == signal)
297 {
298 decode_traces_.erase(i);
299 signals_changed();
300 return;
301 }
302}
303#endif
304
305void Session::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
314void Session::update_signals()
315{
316 assert(device_);
317
318 lock_guard<recursive_mutex> lock(data_mutex_);
319
320 const shared_ptr<sigrok::Device> sr_dev = device_->device();
321 if (!sr_dev) {
322 signals_.clear();
323 logic_data_.reset();
324 return;
325 }
326
327 // Detect what data types we will receive
328 auto channels = sr_dev->channels();
329 unsigned int logic_channel_count = std::count_if(
330 channels.begin(), channels.end(),
331 [] (shared_ptr<Channel> channel) {
332 return channel->type() == ChannelType::LOGIC; });
333
334 // Create data containers for the logic data segments
335 {
336 lock_guard<recursive_mutex> data_lock(data_mutex_);
337
338 if (logic_channel_count == 0) {
339 logic_data_.reset();
340 } else if (!logic_data_ ||
341 logic_data_->num_channels() != logic_channel_count) {
342 logic_data_.reset(new data::Logic(
343 logic_channel_count));
344 assert(logic_data_);
345 }
346 }
347
348 // Make the Signals list
349 {
350 unique_lock<shared_mutex> lock(signals_mutex_);
351
352 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
353 signals_.clear();
354
355 for (auto channel : sr_dev->channels()) {
356 shared_ptr<view::Signal> signal;
357
358 // Find the channel in the old signals
359 const auto iter = std::find_if(
360 prev_sigs.cbegin(), prev_sigs.cend(),
361 [&](const shared_ptr<view::Signal> &s) {
362 return s->channel() == channel;
363 });
364 if (iter != prev_sigs.end()) {
365 // Copy the signal from the old set to the new
366 signal = *iter;
367 auto logic_signal = dynamic_pointer_cast<
368 view::LogicSignal>(signal);
369 if (logic_signal)
370 logic_signal->set_logic_data(
371 logic_data_);
372 } else {
373 // Create a new signal
374 switch(channel->type()->id()) {
375 case SR_CHANNEL_LOGIC:
376 signal = shared_ptr<view::Signal>(
377 new view::LogicSignal(*this,
378 device_, channel,
379 logic_data_));
380 break;
381
382 case SR_CHANNEL_ANALOG:
383 {
384 shared_ptr<data::Analog> data(
385 new data::Analog());
386 signal = shared_ptr<view::Signal>(
387 new view::AnalogSignal(
388 *this, channel, data));
389 break;
390 }
391
392 default:
393 assert(0);
394 break;
395 }
396 }
397
398 assert(signal);
399 signals_.insert(signal);
400 }
401 }
402
403 signals_changed();
404}
405
406shared_ptr<view::Signal> Session::signal_from_channel(
407 shared_ptr<Channel> channel) const
408{
409 lock_guard<boost::shared_mutex> lock(signals_mutex_);
410 for (shared_ptr<view::Signal> sig : signals_) {
411 assert(sig);
412 if (sig->channel() == channel)
413 return sig;
414 }
415 return shared_ptr<view::Signal>();
416}
417
418void Session::sample_thread_proc(shared_ptr<devices::Device> device,
419 function<void (const QString)> error_handler)
420{
421 assert(device);
422 assert(error_handler);
423
424 (void)device;
425
426 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
427
428 out_of_memory_ = false;
429
430 try {
431 device_->start();
432 } catch(Error e) {
433 error_handler(e.what());
434 return;
435 }
436
437 set_capture_state(device_->session()->trigger() ?
438 AwaitingTrigger : Running);
439
440 device_->run();
441 set_capture_state(Stopped);
442
443 // Confirm that SR_DF_END was received
444 if (cur_logic_segment_)
445 {
446 qDebug("SR_DF_END was not received.");
447 assert(0);
448 }
449
450 if (out_of_memory_)
451 error_handler(tr("Out of memory, acquisition stopped."));
452}
453
454void Session::feed_in_header()
455{
456 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
457}
458
459void Session::feed_in_meta(shared_ptr<Meta> meta)
460{
461 for (auto entry : meta->config()) {
462 switch (entry.first->id()) {
463 case SR_CONF_SAMPLERATE:
464 /// @todo handle samplerate changes
465 break;
466 default:
467 // Unknown metadata is not an error.
468 break;
469 }
470 }
471
472 signals_changed();
473}
474
475void Session::feed_in_frame_begin()
476{
477 if (cur_logic_segment_ || !cur_analog_segments_.empty())
478 frame_began();
479}
480
481void Session::feed_in_logic(shared_ptr<Logic> logic)
482{
483 lock_guard<recursive_mutex> lock(data_mutex_);
484
485 const size_t sample_count = logic->data_length() / logic->unit_size();
486
487 if (!logic_data_)
488 {
489 // The only reason logic_data_ would not have been created is
490 // if it was not possible to determine the signals when the
491 // device was created.
492 update_signals();
493 }
494
495 if (!cur_logic_segment_)
496 {
497 // This could be the first packet after a trigger
498 set_capture_state(Running);
499
500 // Create a new data segment
501 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
502 new data::LogicSegment(
503 logic, cur_samplerate_, sample_count));
504 logic_data_->push_segment(cur_logic_segment_);
505
506 // @todo Putting this here means that only listeners querying
507 // for logic will be notified. Currently the only user of
508 // frame_began is DecoderStack, but in future we need to signal
509 // this after both analog and logic sweeps have begun.
510 frame_began();
511 }
512 else
513 {
514 // Append to the existing data segment
515 cur_logic_segment_->append_payload(logic);
516 }
517
518 data_received();
519}
520
521void Session::feed_in_analog(shared_ptr<Analog> analog)
522{
523 lock_guard<recursive_mutex> lock(data_mutex_);
524
525 const vector<shared_ptr<Channel>> channels = analog->channels();
526 const unsigned int channel_count = channels.size();
527 const size_t sample_count = analog->num_samples() / channel_count;
528 const float *data = analog->data_pointer();
529 bool sweep_beginning = false;
530
531 for (auto channel : channels)
532 {
533 shared_ptr<data::AnalogSegment> segment;
534
535 // Try to get the segment of the channel
536 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
537 iterator iter = cur_analog_segments_.find(channel);
538 if (iter != cur_analog_segments_.end())
539 segment = (*iter).second;
540 else
541 {
542 // If no segment was found, this means we havn't
543 // created one yet. i.e. this is the first packet
544 // in the sweep containing this segment.
545 sweep_beginning = true;
546
547 // Create a segment, keep it in the maps of channels
548 segment = shared_ptr<data::AnalogSegment>(
549 new data::AnalogSegment(
550 cur_samplerate_, sample_count));
551 cur_analog_segments_[channel] = segment;
552
553 // Find the analog data associated with the channel
554 shared_ptr<view::AnalogSignal> sig =
555 dynamic_pointer_cast<view::AnalogSignal>(
556 signal_from_channel(channel));
557 assert(sig);
558
559 shared_ptr<data::Analog> data(sig->analog_data());
560 assert(data);
561
562 // Push the segment into the analog data.
563 data->push_segment(segment);
564 }
565
566 assert(segment);
567
568 // Append the samples in the segment
569 segment->append_interleaved_samples(data++, sample_count,
570 channel_count);
571 }
572
573 if (sweep_beginning) {
574 // This could be the first packet after a trigger
575 set_capture_state(Running);
576 }
577
578 data_received();
579}
580
581void Session::data_feed_in(shared_ptr<sigrok::Device> device,
582 shared_ptr<Packet> packet)
583{
584 (void)device;
585
586 assert(device);
587 assert(device == device_->device());
588 assert(packet);
589
590 switch (packet->type()->id()) {
591 case SR_DF_HEADER:
592 feed_in_header();
593 break;
594
595 case SR_DF_META:
596 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
597 break;
598
599 case SR_DF_FRAME_BEGIN:
600 feed_in_frame_begin();
601 break;
602
603 case SR_DF_LOGIC:
604 try {
605 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
606 } catch (std::bad_alloc) {
607 out_of_memory_ = true;
608 device_->stop();
609 }
610 break;
611
612 case SR_DF_ANALOG:
613 try {
614 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
615 } catch (std::bad_alloc) {
616 out_of_memory_ = true;
617 device_->stop();
618 }
619 break;
620
621 case SR_DF_END:
622 {
623 {
624 lock_guard<recursive_mutex> lock(data_mutex_);
625 cur_logic_segment_.reset();
626 cur_analog_segments_.clear();
627 }
628 frame_ended();
629 break;
630 }
631 default:
632 break;
633 }
634}
635
636} // namespace pv