]> sigrok.org Git - pulseview.git/blame - pv/session.cpp
Use the "default" keyword.
[pulseview.git] / pv / session.cpp
CommitLineData
2953961c 1/*
b3f22de0 2 * This file is part of the PulseView project.
2953961c 3 *
1bc6525b 4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
2953961c
JH
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
efdec55a 17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
2953961c
JH
18 */
19
35750e4d
UH
20#ifdef _WIN32
21// Windows: Avoid boost/thread namespace pollution (which includes windows.h).
22#define NOGDI
23#define NORESOURCE
24#endif
e71eb81c
JH
25#include <boost/thread/locks.hpp>
26#include <boost/thread/shared_mutex.hpp>
27
43017494
SA
28#include <QFileInfo>
29
1e4d7c4d
SA
30#include <cassert>
31#include <mutex>
32#include <stdexcept>
4e5a4405 33
1e4d7c4d 34#include <sys/stat.h>
2953961c 35
1e4d7c4d 36#include "session.hpp"
2acdb232 37#include "devicemanager.hpp"
119aff65 38
2acdb232 39#include "data/analog.hpp"
f3d66e52 40#include "data/analogsegment.hpp"
2acdb232
JH
41#include "data/decoderstack.hpp"
42#include "data/logic.hpp"
f3d66e52 43#include "data/logicsegment.hpp"
bf0edd2b 44#include "data/signalbase.hpp"
2acdb232 45#include "data/decode/decoder.hpp"
82c7f640 46
da30ecb7 47#include "devices/hardwaredevice.hpp"
fd22c71c 48#include "devices/inputfile.hpp"
da30ecb7
JH
49#include "devices/sessionfile.hpp"
50
0f8f8c18
SA
51#include "toolbars/mainbar.hpp"
52
2acdb232
JH
53#include "view/analogsignal.hpp"
54#include "view/decodetrace.hpp"
55#include "view/logicsignal.hpp"
47e9e7bb
SA
56#include "view/signal.hpp"
57#include "view/view.hpp"
28a4c9c5 58
fe3a1c21 59#include <libsigrokcxx/libsigrokcxx.hpp>
e8d00928 60
1e4d7c4d
SA
61#ifdef ENABLE_DECODE
62#include <libsigrokdecode/libsigrokdecode.h>
63#endif
64
aca64cac
JH
65using boost::shared_lock;
66using boost::shared_mutex;
67using boost::unique_lock;
68
f9abf97e 69using std::dynamic_pointer_cast;
d2344534 70using std::function;
3b68d03d 71using std::lock_guard;
d873f4d6 72using std::list;
819f4c25 73using std::map;
aca64cac 74using std::mutex;
fd22c71c 75using std::pair;
8524a597 76using std::recursive_mutex;
02412f0b 77using std::set;
f9abf97e 78using std::shared_ptr;
067bb624 79using std::make_shared;
819f4c25 80using std::string;
78b0af3e 81using std::unordered_set;
819f4c25 82using std::vector;
28a4c9c5 83
e8d00928
ML
84using sigrok::Analog;
85using sigrok::Channel;
86using sigrok::ChannelType;
87using sigrok::ConfigKey;
88using sigrok::DatafeedCallbackFunction;
e8d00928 89using sigrok::Error;
e8d00928 90using sigrok::Header;
fd22c71c 91using sigrok::InputFormat;
e8d00928
ML
92using sigrok::Logic;
93using sigrok::Meta;
fd22c71c 94using sigrok::OutputFormat;
e8d00928
ML
95using sigrok::Packet;
96using sigrok::PacketPayload;
97using sigrok::Session;
98using sigrok::SessionDevice;
99
100using Glib::VariantBase;
101using Glib::Variant;
51e77110 102
e8d00928 103namespace pv {
101e7a9b 104Session::Session(DeviceManager &device_manager, QString name) :
8dbbc7f0 105 device_manager_(device_manager),
33e1afbe 106 default_name_(name),
101e7a9b 107 name_(name),
ff008de6 108 capture_state_(Stopped),
5ccfc97e
SA
109 cur_samplerate_(0),
110 data_saved_(true)
2953961c 111{
2953961c
JH
112}
113
2b81ae46 114Session::~Session()
2953961c 115{
04463625 116 // Stop and join to the thread
5b7cf66c 117 stop_capture();
2953961c
JH
118}
119
2b81ae46 120DeviceManager& Session::device_manager()
4cb0b033 121{
8dbbc7f0 122 return device_manager_;
4cb0b033
JH
123}
124
2b81ae46 125const DeviceManager& Session::device_manager() const
4cb0b033 126{
8dbbc7f0 127 return device_manager_;
4cb0b033
JH
128}
129
da30ecb7 130shared_ptr<sigrok::Session> Session::session() const
1f4caa77 131{
da30ecb7
JH
132 if (!device_)
133 return shared_ptr<sigrok::Session>();
134 return device_->session();
1f4caa77
JH
135}
136
da30ecb7 137shared_ptr<devices::Device> Session::device() const
dc0867ff 138{
8dbbc7f0 139 return device_;
dc0867ff
JH
140}
141
101e7a9b
SA
142QString Session::name() const
143{
144 return name_;
145}
146
147void Session::set_name(QString name)
148{
149 if (default_name_.isEmpty())
150 default_name_ = name;
151
152 name_ = name;
153
154 name_changed();
155}
156
f4e57597 157const std::list< std::shared_ptr<views::ViewBase> > Session::views() const
36a8185e
SA
158{
159 return views_;
160}
161
f4e57597 162std::shared_ptr<views::ViewBase> Session::main_view() const
0f8f8c18
SA
163{
164 return main_view_;
165}
166
167void Session::set_main_bar(std::shared_ptr<pv::toolbars::MainBar> main_bar)
168{
169 main_bar_ = main_bar;
170}
171
172shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
173{
174 return main_bar_;
175}
176
5ccfc97e
SA
177bool Session::data_saved() const
178{
179 return data_saved_;
180}
181
101e7a9b
SA
182void Session::save_settings(QSettings &settings) const
183{
184 map<string, string> dev_info;
185 list<string> key_list;
3a21afa6 186 int stacks = 0, views = 0;
101e7a9b
SA
187
188 if (device_) {
43017494
SA
189 shared_ptr<devices::HardwareDevice> hw_device =
190 dynamic_pointer_cast< devices::HardwareDevice >(device_);
191
192 if (hw_device) {
193 settings.setValue("device_type", "hardware");
194 settings.beginGroup("device");
195
326cf6fe
UH
196 key_list.emplace_back("vendor");
197 key_list.emplace_back("model");
198 key_list.emplace_back("version");
199 key_list.emplace_back("serial_num");
200 key_list.emplace_back("connection_id");
43017494
SA
201
202 dev_info = device_manager_.get_device_info(device_);
203
204 for (string key : key_list) {
205 if (dev_info.count(key))
206 settings.setValue(QString::fromUtf8(key.c_str()),
207 QString::fromUtf8(dev_info.at(key).c_str()));
208 else
209 settings.remove(QString::fromUtf8(key.c_str()));
210 }
101e7a9b 211
43017494
SA
212 settings.endGroup();
213 }
101e7a9b 214
43017494
SA
215 shared_ptr<devices::SessionFile> sessionfile_device =
216 dynamic_pointer_cast< devices::SessionFile >(device_);
217
218 if (sessionfile_device) {
219 settings.setValue("device_type", "sessionfile");
220 settings.beginGroup("device");
221 settings.setValue("filename", QString::fromStdString(
222 sessionfile_device->full_name()));
223 settings.endGroup();
101e7a9b
SA
224 }
225
aecae05c
SA
226 // Save channels and decoders
227 for (shared_ptr<data::SignalBase> base : signalbases_) {
228#ifdef ENABLE_DECODE
229 if (base->is_decode_signal()) {
230 shared_ptr<pv::data::DecoderStack> decoder_stack =
231 base->decoder_stack();
232 std::shared_ptr<data::decode::Decoder> top_decoder =
233 decoder_stack->stack().front();
234
235 settings.beginGroup("decoder_stack" + QString::number(stacks++));
236 settings.setValue("id", top_decoder->decoder()->id);
237 settings.setValue("name", top_decoder->decoder()->name);
238 settings.endGroup();
239 } else
240#endif
241 {
242 settings.beginGroup(base->internal_name());
6de38b17 243 base->save_settings(settings);
aecae05c
SA
244 settings.endGroup();
245 }
246 }
101e7a9b 247
aecae05c 248 settings.setValue("decoder_stacks", stacks);
3a21afa6
SA
249
250 // Save view states and their signal settings
251 // Note: main_view must be saved as view0
252 settings.beginGroup("view" + QString::number(views++));
253 main_view_->save_settings(settings);
254 settings.endGroup();
255
f4e57597 256 for (shared_ptr<views::ViewBase> view : views_) {
3a21afa6
SA
257 if (view != main_view_) {
258 settings.beginGroup("view" + QString::number(views++));
259 view->save_settings(settings);
260 settings.endGroup();
261 }
262 }
263
264 settings.setValue("views", views);
101e7a9b
SA
265 }
266}
267
268void Session::restore_settings(QSettings &settings)
269{
43017494
SA
270 shared_ptr<devices::Device> device;
271
272 QString device_type = settings.value("device_type").toString();
273
274 if (device_type == "hardware") {
275 map<string, string> dev_info;
276 list<string> key_list;
277
278 // Re-select last used device if possible but only if it's not demo
279 settings.beginGroup("device");
326cf6fe
UH
280 key_list.emplace_back("vendor");
281 key_list.emplace_back("model");
282 key_list.emplace_back("version");
283 key_list.emplace_back("serial_num");
284 key_list.emplace_back("connection_id");
43017494
SA
285
286 for (string key : key_list) {
287 const QString k = QString::fromStdString(key);
288 if (!settings.contains(k))
289 continue;
290
291 const string value = settings.value(k).toString().toStdString();
292 if (!value.empty())
293 dev_info.insert(std::make_pair(key, value));
294 }
295
296 if (dev_info.count("model") > 0)
297 device = device_manager_.find_device_from_info(dev_info);
298
299 if (device)
300 set_device(device);
301
302 settings.endGroup();
101e7a9b
SA
303 }
304
43017494
SA
305 if (device_type == "sessionfile") {
306 settings.beginGroup("device");
307 QString filename = settings.value("filename").toString();
308 settings.endGroup();
101e7a9b 309
43017494 310 if (QFileInfo(filename).isReadable()) {
067bb624 311 device = make_shared<devices::SessionFile>(device_manager_.context(),
43017494
SA
312 filename.toStdString());
313 set_device(device);
101e7a9b 314
43017494
SA
315 // TODO Perform error handling
316 start_capture([](QString infoMessage) { (void)infoMessage; });
33e1afbe
SA
317
318 set_name(QFileInfo(filename).fileName());
43017494
SA
319 }
320 }
321
322 if (device) {
aecae05c
SA
323 // Restore channels
324 for (shared_ptr<data::SignalBase> base : signalbases_) {
325 settings.beginGroup(base->internal_name());
6de38b17 326 base->restore_settings(settings);
aecae05c
SA
327 settings.endGroup();
328 }
329
330 // Restore decoders
331#ifdef ENABLE_DECODE
332 int stacks = settings.value("decoder_stacks").toInt();
333
334 for (int i = 0; i < stacks; i++) {
335 settings.beginGroup("decoder_stack" + QString::number(i++));
336
337 QString id = settings.value("id").toString();
338 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
339
340 settings.endGroup();
341 }
342#endif
3a21afa6
SA
343
344 // Restore views
345 int views = settings.value("views").toInt();
346
347 for (int i = 0; i < views; i++) {
348 settings.beginGroup("view" + QString::number(i));
349
350 if (i > 0) {
f4e57597 351 views::ViewType type = (views::ViewType)settings.value("type").toInt();
3a21afa6
SA
352 add_view(name_, type, this);
353 views_.back()->restore_settings(settings);
354 } else
355 main_view_->restore_settings(settings);
356
357 settings.endGroup();
358 }
101e7a9b 359 }
101e7a9b
SA
360}
361
fd22c71c
SA
362void Session::select_device(shared_ptr<devices::Device> device)
363{
364 try {
365 if (device)
366 set_device(device);
367 else
368 set_default_device();
369 } catch (const QString &e) {
370 main_bar_->session_error(tr("Failed to Select Device"),
371 tr("Failed to Select Device"));
372 }
373}
374
da30ecb7 375void Session::set_device(shared_ptr<devices::Device> device)
d64d1596 376{
da30ecb7
JH
377 assert(device);
378
82596f46
JH
379 // Ensure we are not capturing before setting the device
380 stop_capture();
381
4d6c6ea3
SA
382 if (device_)
383 device_->close();
384
86123e2e
SA
385 device_.reset();
386
7b254679 387 // Revert name back to default name (e.g. "Session 1") as the data is gone
101e7a9b
SA
388 name_ = default_name_;
389 name_changed();
390
cc9a7898 391 // Remove all stored data
f4e57597 392 for (std::shared_ptr<views::ViewBase> view : views_) {
47e9e7bb 393 view->clear_signals();
bb7dd726 394#ifdef ENABLE_DECODE
f4e57597 395 view->clear_decode_signals();
bb7dd726
SA
396#endif
397 }
47e9e7bb
SA
398 for (const shared_ptr<data::SignalData> d : all_signal_data_)
399 d->clear();
cc9a7898 400 all_signal_data_.clear();
47e9e7bb 401 signalbases_.clear();
4b0d7046
SA
402 cur_logic_segment_.reset();
403
404 for (auto entry : cur_analog_segments_) {
405 shared_ptr<sigrok::Channel>(entry.first).reset();
406 shared_ptr<data::AnalogSegment>(entry.second).reset();
407 }
408
409 logic_data_.reset();
4b0d7046 410
86123e2e
SA
411 signals_changed();
412
da30ecb7 413 device_ = std::move(device);
7e0c99bf
SA
414
415 try {
416 device_->open();
417 } catch (const QString &e) {
418 device_.reset();
7e0c99bf
SA
419 }
420
bcd64b9b
SA
421 if (device_) {
422 device_->session()->add_datafeed_callback([=]
423 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
424 data_feed_in(device, packet);
425 });
426
427 update_signals();
428 }
ae2d1bc5 429
91f8fe8c 430 device_changed();
ae2d1bc5 431}
85843b14 432
2b81ae46 433void Session::set_default_device()
6fd0b639 434{
da30ecb7 435 const list< shared_ptr<devices::HardwareDevice> > &devices =
8dbbc7f0 436 device_manager_.devices();
6fd0b639 437
da30ecb7
JH
438 if (devices.empty())
439 return;
dc0867ff 440
da30ecb7
JH
441 // Try and find the demo device and select that by default
442 const auto iter = std::find_if(devices.begin(), devices.end(),
443 [] (const shared_ptr<devices::HardwareDevice> &d) {
444 return d->hardware_device()->driver()->name() ==
445 "demo"; });
446 set_device((iter == devices.end()) ? devices.front() : *iter);
dc0867ff
JH
447}
448
fd22c71c
SA
449void Session::load_init_file(const std::string &file_name,
450 const std::string &format)
451{
452 shared_ptr<InputFormat> input_format;
453
454 if (!format.empty()) {
455 const map<string, shared_ptr<InputFormat> > formats =
456 device_manager_.context()->input_formats();
457 const auto iter = find_if(formats.begin(), formats.end(),
458 [&](const pair<string, shared_ptr<InputFormat> > f) {
459 return f.first == format; });
460 if (iter == formats.end()) {
461 main_bar_->session_error(tr("Error"),
462 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
463 return;
464 }
465
466 input_format = (*iter).second;
467 }
468
469 load_file(QString::fromStdString(file_name), input_format);
470}
471
472void Session::load_file(QString file_name,
473 std::shared_ptr<sigrok::InputFormat> format,
474 const std::map<std::string, Glib::VariantBase> &options)
475{
476 const QString errorMessage(
477 QString("Failed to load file %1").arg(file_name));
478
479 try {
480 if (format)
481 set_device(shared_ptr<devices::Device>(
482 new devices::InputFile(
483 device_manager_.context(),
484 file_name.toStdString(),
485 format, options)));
486 else
487 set_device(shared_ptr<devices::Device>(
488 new devices::SessionFile(
489 device_manager_.context(),
490 file_name.toStdString())));
491 } catch (Error e) {
492 main_bar_->session_error(tr("Failed to load ") + file_name, e.what());
493 set_default_device();
494 main_bar_->update_device_list();
495 return;
496 }
497
498 main_bar_->update_device_list();
499
500 start_capture([&, errorMessage](QString infoMessage) {
501 main_bar_->session_error(errorMessage, infoMessage); });
502
503 set_name(QFileInfo(file_name).fileName());
504}
505
2b81ae46 506Session::capture_state Session::get_capture_state() const
5b7cf66c 507{
8dbbc7f0
JH
508 lock_guard<mutex> lock(sampling_mutex_);
509 return capture_state_;
5b7cf66c
JH
510}
511
2b81ae46 512void Session::start_capture(function<void (const QString)> error_handler)
2e2946fe 513{
34c11fa7
SA
514 if (!device_) {
515 error_handler(tr("No active device set, can't start acquisition."));
516 return;
517 }
518
5b7cf66c
JH
519 stop_capture();
520
6ac6242b 521 // Check that at least one channel is enabled
e6c1382e
JH
522 const shared_ptr<sigrok::Device> sr_dev = device_->device();
523 if (sr_dev) {
524 const auto channels = sr_dev->channels();
525 if (!std::any_of(channels.begin(), channels.end(),
526 [](shared_ptr<Channel> channel) {
527 return channel->enabled(); })) {
528 error_handler(tr("No channels enabled."));
529 return;
530 }
9c48fa57
JH
531 }
532
53ea4c6c 533 // Clear signal data
47e9e7bb
SA
534 for (const shared_ptr<data::SignalData> d : all_signal_data_)
535 d->clear();
53ea4c6c 536
7b254679 537 // Revert name back to default name (e.g. "Session 1") as the data is gone
101e7a9b
SA
538 name_ = default_name_;
539 name_changed();
540
9c48fa57 541 // Begin the session
8dbbc7f0 542 sampling_thread_ = std::thread(
2b05d311 543 &Session::sample_thread_proc, this, error_handler);
2e2946fe
JH
544}
545
2b81ae46 546void Session::stop_capture()
5b7cf66c 547{
04463625 548 if (get_capture_state() != Stopped)
da30ecb7 549 device_->stop();
5b7cf66c
JH
550
551 // Check that sampling stopped
8dbbc7f0
JH
552 if (sampling_thread_.joinable())
553 sampling_thread_.join();
5b7cf66c
JH
554}
555
f4e57597 556void Session::register_view(std::shared_ptr<views::ViewBase> view)
47e9e7bb 557{
0f8f8c18
SA
558 if (views_.empty()) {
559 main_view_ = view;
560 }
561
3a21afa6 562 views_.push_back(view);
53e8927d
SA
563
564 update_signals();
47e9e7bb
SA
565}
566
f4e57597 567void Session::deregister_view(std::shared_ptr<views::ViewBase> view)
47e9e7bb 568{
f4e57597 569 views_.remove_if([&](std::shared_ptr<views::ViewBase> v) {
3a21afa6 570 return v == view; });
0f8f8c18
SA
571
572 if (views_.empty()) {
573 main_view_.reset();
574
575 // Without a view there can be no main bar
576 main_bar_.reset();
577 }
47e9e7bb
SA
578}
579
f4e57597 580bool Session::has_view(std::shared_ptr<views::ViewBase> view)
101e7a9b 581{
f4e57597 582 for (std::shared_ptr<views::ViewBase> v : views_)
3a21afa6
SA
583 if (v == view)
584 return true;
585
586 return false;
101e7a9b
SA
587}
588
2220e942
SA
589double Session::get_samplerate() const
590{
591 double samplerate = 0.0;
592
47e9e7bb
SA
593 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
594 assert(d);
595 const vector< shared_ptr<pv::data::Segment> > segments =
596 d->segments();
597 for (const shared_ptr<pv::data::Segment> &s : segments)
598 samplerate = std::max(samplerate, s->samplerate());
2220e942 599 }
2220e942
SA
600 // If there is no sample rate given we use samples as unit
601 if (samplerate == 0.0)
602 samplerate = 1.0;
603
604 return samplerate;
605}
606
47e9e7bb
SA
607const std::unordered_set< std::shared_ptr<data::SignalBase> >
608 Session::signalbases() const
2e2946fe 609{
47e9e7bb 610 return signalbases_;
2e2946fe
JH
611}
612
269528f5 613#ifdef ENABLE_DECODE
2b81ae46 614bool Session::add_decoder(srd_decoder *const dec)
82c7f640 615{
04394ded 616 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
7491a29f 617 shared_ptr<data::DecoderStack> decoder_stack;
4e5a4405 618
2ad82c2e 619 try {
4e5a4405 620 // Create the decoder
067bb624 621 decoder_stack = make_shared<data::DecoderStack>(*this, dec);
4e5a4405 622
6ac6242b
ML
623 // Make a list of all the channels
624 std::vector<const srd_channel*> all_channels;
f3290553 625 for (const GSList *i = dec->channels; i; i = i->next)
6ac6242b 626 all_channels.push_back((const srd_channel*)i->data);
f3290553 627 for (const GSList *i = dec->opt_channels; i; i = i->next)
6ac6242b 628 all_channels.push_back((const srd_channel*)i->data);
d2f46d27 629
6ac6242b
ML
630 // Auto select the initial channels
631 for (const srd_channel *pdch : all_channels)
04394ded
SA
632 for (shared_ptr<data::SignalBase> b : signalbases_) {
633 if (b->type() == ChannelType::LOGIC) {
634 if (QString::fromUtf8(pdch->name).toLower().
635 contains(b->name().toLower()))
636 channels[pdch] = b;
637 }
4e5a4405 638 }
4e5a4405 639
7491a29f
JH
640 assert(decoder_stack);
641 assert(!decoder_stack->stack().empty());
642 assert(decoder_stack->stack().front());
6ac6242b 643 decoder_stack->stack().front()->set_channels(channels);
4e5a4405
JH
644
645 // Create the decode signal
bf0edd2b 646 shared_ptr<data::SignalBase> signalbase =
067bb624 647 make_shared<data::SignalBase>(nullptr);
bf0edd2b 648
bb7dd726 649 signalbase->set_decoder_stack(decoder_stack);
aecae05c 650 signalbases_.insert(signalbase);
bb7dd726 651
f4e57597
SA
652 for (std::shared_ptr<views::ViewBase> view : views_)
653 view->add_decode_signal(signalbase);
2ad82c2e 654 } catch (std::runtime_error e) {
e92cd4e4
JH
655 return false;
656 }
657
82c7f640 658 signals_changed();
e92cd4e4 659
7491a29f
JH
660 // Do an initial decode
661 decoder_stack->begin_decode();
662
e92cd4e4 663 return true;
82c7f640
JH
664}
665
bb7dd726 666void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
38eeddea 667{
2d25fc47
SA
668 signalbases_.erase(signalbase);
669
f4e57597
SA
670 for (std::shared_ptr<views::ViewBase> view : views_)
671 view->remove_decode_signal(signalbase);
2d25fc47
SA
672
673 signals_changed();
c51482b3 674}
269528f5 675#endif
c51482b3 676
2b81ae46 677void Session::set_capture_state(capture_state state)
6ac96c2e 678{
896936e5
TS
679 bool changed;
680
681 {
682 lock_guard<mutex> lock(sampling_mutex_);
683 changed = capture_state_ != state;
684 capture_state_ = state;
685 }
686
f3290553 687 if (changed)
2b49eeb0 688 capture_state_changed(state);
6ac96c2e
JH
689}
690
ffe00119 691void Session::update_signals()
b087ba7f 692{
076eefa4 693 if (!device_) {
47e9e7bb 694 signalbases_.clear();
076eefa4 695 logic_data_.reset();
f4e57597 696 for (std::shared_ptr<views::ViewBase> view : views_) {
47e9e7bb 697 view->clear_signals();
bb7dd726 698#ifdef ENABLE_DECODE
f4e57597 699 view->clear_decode_signals();
bb7dd726
SA
700#endif
701 }
076eefa4
SA
702 return;
703 }
e6c1382e
JH
704
705 lock_guard<recursive_mutex> lock(data_mutex_);
b087ba7f 706
ffe00119 707 const shared_ptr<sigrok::Device> sr_dev = device_->device();
c6412b47 708 if (!sr_dev) {
47e9e7bb 709 signalbases_.clear();
c6412b47 710 logic_data_.reset();
f4e57597 711 for (std::shared_ptr<views::ViewBase> view : views_) {
47e9e7bb 712 view->clear_signals();
bb7dd726 713#ifdef ENABLE_DECODE
f4e57597 714 view->clear_decode_signals();
bb7dd726
SA
715#endif
716 }
c6412b47
JH
717 return;
718 }
719
b087ba7f 720 // Detect what data types we will receive
c6412b47 721 auto channels = sr_dev->channels();
e8d00928
ML
722 unsigned int logic_channel_count = std::count_if(
723 channels.begin(), channels.end(),
724 [] (shared_ptr<Channel> channel) {
725 return channel->type() == ChannelType::LOGIC; });
b087ba7f 726
f3d66e52 727 // Create data containers for the logic data segments
b087ba7f 728 {
8524a597 729 lock_guard<recursive_mutex> data_lock(data_mutex_);
b087ba7f 730
3917ba77
JH
731 if (logic_channel_count == 0) {
732 logic_data_.reset();
733 } else if (!logic_data_ ||
734 logic_data_->num_channels() != logic_channel_count) {
8dbbc7f0 735 logic_data_.reset(new data::Logic(
6ac6242b 736 logic_channel_count));
8dbbc7f0 737 assert(logic_data_);
b087ba7f 738 }
b087ba7f
JH
739 }
740
47e9e7bb 741 // Make the signals list
f4e57597
SA
742 for (std::shared_ptr<views::ViewBase> viewbase : views_) {
743 views::TraceView::View *trace_view =
744 qobject_cast<views::TraceView::View*>(viewbase.get());
745
746 if (trace_view) {
747 unordered_set< shared_ptr<views::TraceView::Signal> >
748 prev_sigs(trace_view->signals());
749 trace_view->clear_signals();
750
751 for (auto channel : sr_dev->channels()) {
752 shared_ptr<data::SignalBase> signalbase;
753 shared_ptr<views::TraceView::Signal> signal;
754
755 // Find the channel in the old signals
756 const auto iter = std::find_if(
757 prev_sigs.cbegin(), prev_sigs.cend(),
758 [&](const shared_ptr<views::TraceView::Signal> &s) {
759 return s->base()->channel() == channel;
760 });
761 if (iter != prev_sigs.end()) {
762 // Copy the signal from the old set to the new
763 signal = *iter;
764 trace_view->add_signal(signal);
765 } else {
766 // Find the signalbase for this channel if possible
767 signalbase.reset();
768 for (const shared_ptr<data::SignalBase> b : signalbases_)
769 if (b->channel() == channel)
770 signalbase = b;
771
772 switch(channel->type()->id()) {
773 case SR_CHANNEL_LOGIC:
774 if (!signalbase) {
067bb624 775 signalbase = make_shared<data::SignalBase>(channel);
f4e57597
SA
776 signalbases_.insert(signalbase);
777
778 all_signal_data_.insert(logic_data_);
779 signalbase->set_data(logic_data_);
780 }
781
782 signal = shared_ptr<views::TraceView::Signal>(
783 new views::TraceView::LogicSignal(*this,
784 device_, signalbase));
785 trace_view->add_signal(signal);
786 break;
787
788 case SR_CHANNEL_ANALOG:
789 {
790 if (!signalbase) {
067bb624 791 signalbase = make_shared<data::SignalBase>(channel);
f4e57597
SA
792 signalbases_.insert(signalbase);
793
794 shared_ptr<data::Analog> data(new data::Analog());
795 all_signal_data_.insert(data);
796 signalbase->set_data(data);
797 }
798
799 signal = shared_ptr<views::TraceView::Signal>(
800 new views::TraceView::AnalogSignal(
801 *this, signalbase));
802 trace_view->add_signal(signal);
803 break;
47e9e7bb
SA
804 }
805
f4e57597
SA
806 default:
807 assert(0);
808 break;
47e9e7bb 809 }
3917ba77 810 }
b087ba7f
JH
811 }
812 }
fbd3e234 813 }
b087ba7f
JH
814
815 signals_changed();
816}
817
cbd2a2de 818shared_ptr<data::SignalBase> Session::signalbase_from_channel(
bf0edd2b 819 shared_ptr<sigrok::Channel> channel) const
3ddcc083 820{
bf0edd2b 821 for (shared_ptr<data::SignalBase> sig : signalbases_) {
3ddcc083 822 assert(sig);
6ac6242b 823 if (sig->channel() == channel)
3ddcc083
JH
824 return sig;
825 }
bf0edd2b 826 return shared_ptr<data::SignalBase>();
3ddcc083
JH
827}
828
2b05d311 829void Session::sample_thread_proc(function<void (const QString)> error_handler)
274d4f13 830{
f2edb557 831 assert(error_handler);
be73bdfa 832
34c11fa7
SA
833 if (!device_)
834 return;
45f0c7c9 835
b48daed6 836 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
274d4f13 837
e7216ae0
SA
838 out_of_memory_ = false;
839
ae2d1bc5 840 try {
5237f0c5 841 device_->start();
2ad82c2e 842 } catch (Error e) {
e8d00928 843 error_handler(e.what());
eec446e1
JH
844 return;
845 }
846
da30ecb7 847 set_capture_state(device_->session()->trigger() ?
07dcf561 848 AwaitingTrigger : Running);
eec446e1 849
da30ecb7 850 device_->run();
eec446e1 851 set_capture_state(Stopped);
1a2fe44c
JH
852
853 // Confirm that SR_DF_END was received
2ad82c2e 854 if (cur_logic_segment_) {
bb2cdfff
JH
855 qDebug("SR_DF_END was not received.");
856 assert(0);
857 }
e7216ae0 858
5e6967cb
SA
859 // Optimize memory usage
860 free_unused_memory();
861
5ccfc97e
SA
862 // We now have unsaved data unless we just "captured" from a file
863 shared_ptr<devices::File> file_device =
864 dynamic_pointer_cast<devices::File>(device_);
865
866 if (!file_device)
867 data_saved_ = false;
868
e7216ae0
SA
869 if (out_of_memory_)
870 error_handler(tr("Out of memory, acquisition stopped."));
eec446e1
JH
871}
872
5e6967cb
SA
873void Session::free_unused_memory()
874{
875 for (shared_ptr<data::SignalData> data : all_signal_data_) {
876 const vector< shared_ptr<data::Segment> > segments = data->segments();
877
878 for (shared_ptr<data::Segment> segment : segments) {
879 segment->free_unused_memory();
880 }
881 }
882}
883
da30ecb7 884void Session::feed_in_header()
eec446e1 885{
b48daed6 886 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
be73bdfa
JH
887}
888
da30ecb7 889void Session::feed_in_meta(shared_ptr<Meta> meta)
be73bdfa 890{
e8d00928
ML
891 for (auto entry : meta->config()) {
892 switch (entry.first->id()) {
be73bdfa 893 case SR_CONF_SAMPLERATE:
8a7b603b
SA
894 // We can't rely on the header to always contain the sample rate,
895 // so in case it's supplied via a meta packet, we use it.
896 if (!cur_samplerate_)
897 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
898
be73bdfa 899 /// @todo handle samplerate changes
be73bdfa
JH
900 break;
901 default:
902 // Unknown metadata is not an error.
903 break;
904 }
aba1dd16 905 }
74043039
JH
906
907 signals_changed();
aba1dd16
JH
908}
909
48257a69
SA
910void Session::feed_in_trigger()
911{
912 // The channel containing most samples should be most accurate
913 uint64_t sample_count = 0;
914
cc9a7898 915 {
cc9a7898
SA
916 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
917 assert(d);
918 uint64_t temp_count = 0;
919
920 const vector< shared_ptr<pv::data::Segment> > segments =
921 d->segments();
922 for (const shared_ptr<pv::data::Segment> &s : segments)
923 temp_count += s->get_sample_count();
924
925 if (temp_count > sample_count)
926 sample_count = temp_count;
927 }
48257a69
SA
928 }
929
930 trigger_event(sample_count / get_samplerate());
931}
932
2b81ae46 933void Session::feed_in_frame_begin()
82f50b10 934{
f3d66e52 935 if (cur_logic_segment_ || !cur_analog_segments_.empty())
82f50b10
JH
936 frame_began();
937}
938
2b81ae46 939void Session::feed_in_logic(shared_ptr<Logic> logic)
9c112671 940{
8524a597 941 lock_guard<recursive_mutex> lock(data_mutex_);
79efbc53 942
2ad82c2e 943 if (!logic_data_) {
e6c1382e
JH
944 // The only reason logic_data_ would not have been created is
945 // if it was not possible to determine the signals when the
946 // device was created.
947 update_signals();
79efbc53 948 }
be73bdfa 949
2ad82c2e 950 if (!cur_logic_segment_) {
bb2cdfff 951 // This could be the first packet after a trigger
2b49eeb0
JH
952 set_capture_state(Running);
953
f3d66e52 954 // Create a new data segment
067bb624
UH
955 cur_logic_segment_ = make_shared<data::LogicSegment>(
956 *logic_data_, logic, cur_samplerate_);
f3d66e52 957 logic_data_->push_segment(cur_logic_segment_);
82f50b10
JH
958
959 // @todo Putting this here means that only listeners querying
960 // for logic will be notified. Currently the only user of
961 // frame_began is DecoderStack, but in future we need to signal
962 // this after both analog and logic sweeps have begun.
963 frame_began();
2ad82c2e 964 } else {
f3d66e52
JH
965 // Append to the existing data segment
966 cur_logic_segment_->append_payload(logic);
9c112671
JH
967 }
968
1f374035 969 data_received();
9c112671
JH
970}
971
2b81ae46 972void Session::feed_in_analog(shared_ptr<Analog> analog)
aba1dd16 973{
8524a597 974 lock_guard<recursive_mutex> lock(data_mutex_);
79efbc53 975
e8d00928
ML
976 const vector<shared_ptr<Channel>> channels = analog->channels();
977 const unsigned int channel_count = channels.size();
978 const size_t sample_count = analog->num_samples() / channel_count;
475f4d08 979 const float *data = static_cast<const float *>(analog->data_pointer());
bb2cdfff 980 bool sweep_beginning = false;
be73bdfa 981
47e9e7bb 982 if (signalbases_.empty())
a3f678a7 983 update_signals();
a3f678a7 984
2ad82c2e 985 for (auto channel : channels) {
f3d66e52 986 shared_ptr<data::AnalogSegment> segment;
2b49eeb0 987
f3d66e52
JH
988 // Try to get the segment of the channel
989 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
990 iterator iter = cur_analog_segments_.find(channel);
991 if (iter != cur_analog_segments_.end())
992 segment = (*iter).second;
2ad82c2e 993 else {
39ccf9c3 994 // If no segment was found, this means we haven't
bb2cdfff 995 // created one yet. i.e. this is the first packet
f3d66e52 996 // in the sweep containing this segment.
bb2cdfff
JH
997 sweep_beginning = true;
998
ff4bf6bd 999 // Find the analog data associated with the channel
cbd2a2de
SA
1000 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1001 assert(base);
bb2cdfff 1002
cbd2a2de 1003 shared_ptr<data::Analog> data(base->analog_data());
bb2cdfff
JH
1004 assert(data);
1005
7db61e77 1006 // Create a segment, keep it in the maps of channels
067bb624
UH
1007 segment = make_shared<data::AnalogSegment>(
1008 *data, cur_samplerate_);
7db61e77
SA
1009 cur_analog_segments_[channel] = segment;
1010
f3d66e52
JH
1011 // Push the segment into the analog data.
1012 data->push_segment(segment);
bb2cdfff
JH
1013 }
1014
f3d66e52 1015 assert(segment);
bb2cdfff 1016
f3d66e52
JH
1017 // Append the samples in the segment
1018 segment->append_interleaved_samples(data++, sample_count,
6ac6242b 1019 channel_count);
aba1dd16 1020 }
bb2cdfff
JH
1021
1022 if (sweep_beginning) {
1023 // This could be the first packet after a trigger
1024 set_capture_state(Running);
aba1dd16
JH
1025 }
1026
1f374035 1027 data_received();
aba1dd16 1028}
9c112671 1029
da30ecb7
JH
1030void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1031 shared_ptr<Packet> packet)
b0e1d01d 1032{
0a4162a4
SA
1033 static bool frame_began=false;
1034
da30ecb7
JH
1035 (void)device;
1036
e8d00928 1037 assert(device);
da30ecb7 1038 assert(device == device_->device());
b0e1d01d
JH
1039 assert(packet);
1040
e8d00928 1041 switch (packet->type()->id()) {
b0e1d01d 1042 case SR_DF_HEADER:
da30ecb7 1043 feed_in_header();
b0e1d01d
JH
1044 break;
1045
be73bdfa 1046 case SR_DF_META:
da30ecb7 1047 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
aba1dd16
JH
1048 break;
1049
48257a69
SA
1050 case SR_DF_TRIGGER:
1051 feed_in_trigger();
1052 break;
1053
82f50b10
JH
1054 case SR_DF_FRAME_BEGIN:
1055 feed_in_frame_begin();
0a4162a4 1056 frame_began = true;
82f50b10
JH
1057 break;
1058
2e2946fe 1059 case SR_DF_LOGIC:
e7216ae0
SA
1060 try {
1061 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1062 } catch (std::bad_alloc) {
1063 out_of_memory_ = true;
1064 device_->stop();
1065 }
2953961c
JH
1066 break;
1067
aba1dd16 1068 case SR_DF_ANALOG:
e7216ae0
SA
1069 try {
1070 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1071 } catch (std::bad_alloc) {
1072 out_of_memory_ = true;
1073 device_->stop();
1074 }
aba1dd16
JH
1075 break;
1076
0a4162a4 1077 case SR_DF_FRAME_END:
2953961c 1078 case SR_DF_END:
2e2946fe
JH
1079 {
1080 {
8524a597 1081 lock_guard<recursive_mutex> lock(data_mutex_);
f3d66e52
JH
1082 cur_logic_segment_.reset();
1083 cur_analog_segments_.clear();
2e2946fe 1084 }
0a4162a4
SA
1085 if (frame_began) {
1086 frame_began = false;
1087 frame_ended();
1088 }
2953961c
JH
1089 break;
1090 }
adb0a983
ML
1091 default:
1092 break;
2e2946fe 1093 }
2953961c
JH
1094}
1095
5ccfc97e
SA
1096void Session::on_data_saved()
1097{
1098 data_saved_ = true;
1099}
1100
51e77110 1101} // namespace pv