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