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