]> sigrok.org Git - pulseview.git/blame - pv/session.cpp
Fix #1457 by adding markers, cursors and zero offset to session setup
[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
1e4d7c4d 20#include <cassert>
303eec78 21#include <memory>
1e4d7c4d
SA
22#include <mutex>
23#include <stdexcept>
4e5a4405 24
1e4d7c4d 25#include <sys/stat.h>
2953961c 26
e887fe9e
SA
27#include <QDebug>
28#include <QFileInfo>
29
2acdb232 30#include "devicemanager.hpp"
5e685656 31#include "mainwindow.hpp"
aca9aa83 32#include "session.hpp"
e887fe9e 33#include "util.hpp"
119aff65 34
2acdb232 35#include "data/analog.hpp"
f3d66e52 36#include "data/analogsegment.hpp"
aca9aa83 37#include "data/decode/decoder.hpp"
2acdb232 38#include "data/logic.hpp"
f3d66e52 39#include "data/logicsegment.hpp"
bf0edd2b 40#include "data/signalbase.hpp"
82c7f640 41
da30ecb7 42#include "devices/hardwaredevice.hpp"
fd22c71c 43#include "devices/inputfile.hpp"
da30ecb7
JH
44#include "devices/sessionfile.hpp"
45
0f8f8c18
SA
46#include "toolbars/mainbar.hpp"
47
1573bf16
SA
48#include "views/trace/analogsignal.hpp"
49#include "views/trace/decodetrace.hpp"
50#include "views/trace/logicsignal.hpp"
51#include "views/trace/signal.hpp"
52#include "views/trace/view.hpp"
28a4c9c5 53
fe3a1c21 54#include <libsigrokcxx/libsigrokcxx.hpp>
e8d00928 55
5f9a5209
SA
56#ifdef ENABLE_FLOW
57#include <gstreamermm.h>
58#include <libsigrokflow/libsigrokflow.hpp>
59#endif
60
1e4d7c4d
SA
61#ifdef ENABLE_DECODE
62#include <libsigrokdecode/libsigrokdecode.h>
ad908057 63#include "data/decodesignal.hpp"
1e4d7c4d
SA
64#endif
65
6f925ba9 66using std::bad_alloc;
f9abf97e 67using std::dynamic_pointer_cast;
6f925ba9 68using std::find_if;
d2344534 69using std::function;
3b68d03d 70using std::lock_guard;
d873f4d6 71using std::list;
6f925ba9
UH
72using std::make_pair;
73using std::make_shared;
819f4c25 74using std::map;
6f925ba9
UH
75using std::max;
76using std::move;
aca64cac 77using std::mutex;
fd22c71c 78using std::pair;
8524a597 79using std::recursive_mutex;
6f925ba9 80using std::runtime_error;
f9abf97e 81using std::shared_ptr;
819f4c25 82using std::string;
5f9a5209
SA
83#ifdef ENABLE_FLOW
84using std::unique_lock;
85#endif
303eec78 86using std::unique_ptr;
78b0af3e 87using std::unordered_set;
819f4c25 88using std::vector;
28a4c9c5 89
e8d00928
ML
90using sigrok::Analog;
91using sigrok::Channel;
e8d00928
ML
92using sigrok::ConfigKey;
93using sigrok::DatafeedCallbackFunction;
e8d00928 94using sigrok::Error;
fd22c71c 95using sigrok::InputFormat;
e8d00928
ML
96using sigrok::Logic;
97using sigrok::Meta;
98using sigrok::Packet;
e8d00928 99using sigrok::Session;
e8d00928
ML
100
101using Glib::VariantBase;
51e77110 102
5f9a5209
SA
103#ifdef ENABLE_FLOW
104using Gst::Bus;
105using Gst::ElementFactory;
106using Gst::Pipeline;
107#endif
108
e887fe9e 109using pv::util::Timestamp;
0a952555
SA
110using pv::views::trace::Signal;
111using pv::views::trace::AnalogSignal;
112using pv::views::trace::LogicSignal;
113
e8d00928 114namespace pv {
419ec4e1
SA
115
116shared_ptr<sigrok::Context> Session::sr_context;
117
101e7a9b 118Session::Session(DeviceManager &device_manager, QString name) :
8dbbc7f0 119 device_manager_(device_manager),
33e1afbe 120 default_name_(name),
101e7a9b 121 name_(name),
ff008de6 122 capture_state_(Stopped),
5ccfc97e
SA
123 cur_samplerate_(0),
124 data_saved_(true)
2953961c 125{
2953961c
JH
126}
127
2b81ae46 128Session::~Session()
2953961c 129{
04463625 130 // Stop and join to the thread
5b7cf66c 131 stop_capture();
2953961c
JH
132}
133
2b81ae46 134DeviceManager& Session::device_manager()
4cb0b033 135{
8dbbc7f0 136 return device_manager_;
4cb0b033
JH
137}
138
2b81ae46 139const DeviceManager& Session::device_manager() const
4cb0b033 140{
8dbbc7f0 141 return device_manager_;
4cb0b033
JH
142}
143
da30ecb7 144shared_ptr<sigrok::Session> Session::session() const
1f4caa77 145{
da30ecb7
JH
146 if (!device_)
147 return shared_ptr<sigrok::Session>();
148 return device_->session();
1f4caa77
JH
149}
150
da30ecb7 151shared_ptr<devices::Device> Session::device() const
dc0867ff 152{
8dbbc7f0 153 return device_;
dc0867ff
JH
154}
155
101e7a9b
SA
156QString Session::name() const
157{
158 return name_;
159}
160
161void Session::set_name(QString name)
162{
163 if (default_name_.isEmpty())
164 default_name_ = name;
165
166 name_ = name;
167
168 name_changed();
169}
170
6f925ba9 171const list< shared_ptr<views::ViewBase> > Session::views() const
36a8185e
SA
172{
173 return views_;
174}
175
6f925ba9 176shared_ptr<views::ViewBase> Session::main_view() const
0f8f8c18
SA
177{
178 return main_view_;
179}
180
6f925ba9 181void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
0f8f8c18
SA
182{
183 main_bar_ = main_bar;
184}
185
186shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
187{
188 return main_bar_;
189}
190
5ccfc97e
SA
191bool Session::data_saved() const
192{
193 return data_saved_;
194}
195
323715c4
SA
196void Session::save_setup(QSettings &settings) const
197{
e887fe9e 198 int i = 0;
323715c4
SA
199
200 // Save channels and decoders
201 for (const shared_ptr<data::SignalBase>& base : signalbases_) {
202#ifdef ENABLE_DECODE
203 if (base->is_decode_signal()) {
e887fe9e 204 settings.beginGroup("decode_signal" + QString::number(i++));
323715c4
SA
205 base->save_settings(settings);
206 settings.endGroup();
207 } else
208#endif
209 {
210 settings.beginGroup(base->internal_name());
211 base->save_settings(settings);
212 settings.endGroup();
213 }
214 }
215
e887fe9e 216 settings.setValue("decode_signals", i);
323715c4
SA
217
218 // Save view states and their signal settings
219 // Note: main_view must be saved as view0
e887fe9e
SA
220 i = 0;
221 settings.beginGroup("view" + QString::number(i++));
323715c4
SA
222 main_view_->save_settings(settings);
223 settings.endGroup();
224
225 for (const shared_ptr<views::ViewBase>& view : views_) {
226 if (view != main_view_) {
e887fe9e 227 settings.beginGroup("view" + QString::number(i++));
db298158 228 settings.setValue("type", view->get_type());
323715c4
SA
229 view->save_settings(settings);
230 settings.endGroup();
231 }
232 }
233
e887fe9e
SA
234 settings.setValue("views", i);
235
236 i = 0;
237 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(main_view_);
238 for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
239
240 const shared_ptr<views::trace::Flag> flag =
241 dynamic_pointer_cast<views::trace::Flag>(time_item);
242 if (flag) {
243 if (!flag->enabled())
244 continue;
245
246 settings.beginGroup("meta_obj" + QString::number(i++));
247 settings.setValue("type", "time_marker");
248 GlobalSettings::store_timestamp(settings, "time", flag->time());
249 settings.setValue("text", flag->get_text());
250 settings.endGroup();
251 }
252 }
253
254 if (tv->cursors_shown()) {
255 settings.beginGroup("meta_obj" + QString::number(i++));
256 settings.setValue("type", "selection");
257 const shared_ptr<views::trace::CursorPair> cp = tv->cursors();
258 GlobalSettings::store_timestamp(settings, "start_time", cp->first()->time());
259 GlobalSettings::store_timestamp(settings, "end_time", cp->second()->time());
260 settings.endGroup();
261 }
262
263 settings.setValue("meta_objs", i);
323715c4
SA
264}
265
101e7a9b
SA
266void Session::save_settings(QSettings &settings) const
267{
268 map<string, string> dev_info;
269 list<string> key_list;
270
271 if (device_) {
43017494
SA
272 shared_ptr<devices::HardwareDevice> hw_device =
273 dynamic_pointer_cast< devices::HardwareDevice >(device_);
274
275 if (hw_device) {
276 settings.setValue("device_type", "hardware");
277 settings.beginGroup("device");
278
326cf6fe
UH
279 key_list.emplace_back("vendor");
280 key_list.emplace_back("model");
281 key_list.emplace_back("version");
282 key_list.emplace_back("serial_num");
283 key_list.emplace_back("connection_id");
43017494
SA
284
285 dev_info = device_manager_.get_device_info(device_);
286
f4ab4b5c 287 for (string& key : key_list) {
43017494
SA
288 if (dev_info.count(key))
289 settings.setValue(QString::fromUtf8(key.c_str()),
290 QString::fromUtf8(dev_info.at(key).c_str()));
291 else
292 settings.remove(QString::fromUtf8(key.c_str()));
293 }
101e7a9b 294
43017494
SA
295 settings.endGroup();
296 }
101e7a9b 297
43017494 298 shared_ptr<devices::SessionFile> sessionfile_device =
1325ce42 299 dynamic_pointer_cast<devices::SessionFile>(device_);
43017494
SA
300
301 if (sessionfile_device) {
302 settings.setValue("device_type", "sessionfile");
303 settings.beginGroup("device");
304 settings.setValue("filename", QString::fromStdString(
305 sessionfile_device->full_name()));
306 settings.endGroup();
101e7a9b
SA
307 }
308
1325ce42
SA
309 shared_ptr<devices::InputFile> inputfile_device =
310 dynamic_pointer_cast<devices::InputFile>(device_);
311
312 if (inputfile_device) {
313 settings.setValue("device_type", "inputfile");
314 settings.beginGroup("device");
315 inputfile_device->save_meta_to_settings(settings);
316 settings.endGroup();
317 }
318
323715c4
SA
319 save_setup(settings);
320 }
321}
322
323void Session::restore_setup(QSettings &settings)
324{
325 // Restore channels
326 for (shared_ptr<data::SignalBase> base : signalbases_) {
327 settings.beginGroup(base->internal_name());
328 base->restore_settings(settings);
329 settings.endGroup();
330 }
331
332 // Restore decoders
aecae05c 333#ifdef ENABLE_DECODE
323715c4
SA
334 int decode_signals = settings.value("decode_signals").toInt();
335
336 for (int i = 0; i < decode_signals; i++) {
337 settings.beginGroup("decode_signal" + QString::number(i));
338 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
339 signal->restore_settings(settings);
340 settings.endGroup();
341 }
aecae05c 342#endif
101e7a9b 343
323715c4
SA
344 // Restore views
345 int views = settings.value("views").toInt();
3a21afa6 346
323715c4
SA
347 for (int i = 0; i < views; i++) {
348 settings.beginGroup("view" + QString::number(i));
3a21afa6 349
323715c4
SA
350 if (i > 0) {
351 views::ViewType type = (views::ViewType)settings.value("type").toInt();
baf867ed 352 add_view(type, this);
323715c4
SA
353 views_.back()->restore_settings(settings);
354 } else
355 main_view_->restore_settings(settings);
3a21afa6 356
323715c4 357 settings.endGroup();
101e7a9b 358 }
e887fe9e
SA
359
360 // Restore meta objects like markers and cursors
361 int meta_objs = settings.value("meta_objs").toInt();
362
363 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(main_view_);
364 for (int i = 0; i < meta_objs; i++) {
365 settings.beginGroup("meta_obj" + QString::number(i));
366 const QString type = settings.value("type").toString();
367
368 if (type == "time_marker") {
369 Timestamp ts = GlobalSettings::restore_timestamp(settings, "time");
370 shared_ptr<views::trace::Flag> flag = tv->add_flag(ts);
371 flag->set_text(settings.value("text").toString());
372 }
373
374 if (type == "selection") {
375 Timestamp start = GlobalSettings::restore_timestamp(settings, "start_time");
376 Timestamp end = GlobalSettings::restore_timestamp(settings, "end_time");
377 tv->set_cursors(start, end);
378 tv->show_cursors();
379 }
380
381 settings.endGroup();
382 }
101e7a9b
SA
383}
384
385void Session::restore_settings(QSettings &settings)
386{
43017494
SA
387 shared_ptr<devices::Device> device;
388
e887fe9e 389 const QString device_type = settings.value("device_type").toString();
43017494
SA
390
391 if (device_type == "hardware") {
392 map<string, string> dev_info;
393 list<string> key_list;
394
395 // Re-select last used device if possible but only if it's not demo
396 settings.beginGroup("device");
326cf6fe
UH
397 key_list.emplace_back("vendor");
398 key_list.emplace_back("model");
399 key_list.emplace_back("version");
400 key_list.emplace_back("serial_num");
401 key_list.emplace_back("connection_id");
43017494
SA
402
403 for (string key : key_list) {
404 const QString k = QString::fromStdString(key);
405 if (!settings.contains(k))
406 continue;
407
408 const string value = settings.value(k).toString().toStdString();
409 if (!value.empty())
6f925ba9 410 dev_info.insert(make_pair(key, value));
43017494
SA
411 }
412
413 if (dev_info.count("model") > 0)
414 device = device_manager_.find_device_from_info(dev_info);
415
416 if (device)
417 set_device(device);
418
419 settings.endGroup();
101e7a9b
SA
420 }
421
1325ce42
SA
422 if ((device_type == "sessionfile") || (device_type == "inputfile")) {
423 if (device_type == "sessionfile") {
424 settings.beginGroup("device");
e887fe9e 425 const QString filename = settings.value("filename").toString();
1325ce42
SA
426 settings.endGroup();
427
428 if (QFileInfo(filename).isReadable()) {
429 device = make_shared<devices::SessionFile>(device_manager_.context(),
430 filename.toStdString());
431 }
432 }
433
434 if (device_type == "inputfile") {
435 settings.beginGroup("device");
436 device = make_shared<devices::InputFile>(device_manager_.context(),
437 settings);
438 settings.endGroup();
439 }
101e7a9b 440
1325ce42 441 if (device) {
43017494 442 set_device(device);
101e7a9b 443
403c3e87 444 start_capture([](QString infoMessage) {
fe060a48
SA
445 // TODO Emulate noquote()
446 qDebug() << "Session error:" << infoMessage; });
33e1afbe 447
1325ce42
SA
448 set_name(QString::fromStdString(
449 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
43017494
SA
450 }
451 }
452
323715c4
SA
453 if (device)
454 restore_setup(settings);
101e7a9b
SA
455}
456
fd22c71c
SA
457void Session::select_device(shared_ptr<devices::Device> device)
458{
459 try {
460 if (device)
461 set_device(device);
462 else
463 set_default_device();
464 } catch (const QString &e) {
5e685656 465 MainWindow::show_session_error(tr("Failed to select device"), e);
fd22c71c
SA
466 }
467}
468
da30ecb7 469void Session::set_device(shared_ptr<devices::Device> device)
d64d1596 470{
da30ecb7
JH
471 assert(device);
472
82596f46
JH
473 // Ensure we are not capturing before setting the device
474 stop_capture();
475
4d6c6ea3
SA
476 if (device_)
477 device_->close();
478
86123e2e
SA
479 device_.reset();
480
7b254679 481 // Revert name back to default name (e.g. "Session 1") as the data is gone
101e7a9b
SA
482 name_ = default_name_;
483 name_changed();
484
5a206446 485 // Remove all stored data and reset all views
6f925ba9 486 for (shared_ptr<views::ViewBase> view : views_) {
47e9e7bb 487 view->clear_signals();
bb7dd726 488#ifdef ENABLE_DECODE
f4e57597 489 view->clear_decode_signals();
bb7dd726 490#endif
5a206446 491 view->reset_view_state();
bb7dd726 492 }
f4ab4b5c 493 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
47e9e7bb 494 d->clear();
cc9a7898 495 all_signal_data_.clear();
47e9e7bb 496 signalbases_.clear();
4b0d7046
SA
497 cur_logic_segment_.reset();
498
f4ab4b5c 499 for (auto& entry : cur_analog_segments_) {
4b0d7046
SA
500 shared_ptr<sigrok::Channel>(entry.first).reset();
501 shared_ptr<data::AnalogSegment>(entry.second).reset();
502 }
503
504 logic_data_.reset();
4b0d7046 505
86123e2e
SA
506 signals_changed();
507
6f925ba9 508 device_ = move(device);
7e0c99bf
SA
509
510 try {
511 device_->open();
512 } catch (const QString &e) {
513 device_.reset();
5e685656 514 MainWindow::show_session_error(tr("Failed to open device"), e);
7e0c99bf
SA
515 }
516
bcd64b9b
SA
517 if (device_) {
518 device_->session()->add_datafeed_callback([=]
519 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
520 data_feed_in(device, packet);
521 });
522
523 update_signals();
524 }
ae2d1bc5 525
91f8fe8c 526 device_changed();
ae2d1bc5 527}
85843b14 528
2b81ae46 529void Session::set_default_device()
6fd0b639 530{
da30ecb7 531 const list< shared_ptr<devices::HardwareDevice> > &devices =
8dbbc7f0 532 device_manager_.devices();
6fd0b639 533
da30ecb7
JH
534 if (devices.empty())
535 return;
dc0867ff 536
da30ecb7 537 // Try and find the demo device and select that by default
6f925ba9 538 const auto iter = find_if(devices.begin(), devices.end(),
da30ecb7 539 [] (const shared_ptr<devices::HardwareDevice> &d) {
0fb98cf8 540 return d->hardware_device()->driver()->name() == "demo"; });
da30ecb7 541 set_device((iter == devices.end()) ? devices.front() : *iter);
dc0867ff
JH
542}
543
31d1aca6
SA
544bool Session::using_file_device() const
545{
546 shared_ptr<devices::SessionFile> sessionfile_device =
547 dynamic_pointer_cast<devices::SessionFile>(device_);
548
549 shared_ptr<devices::InputFile> inputfile_device =
550 dynamic_pointer_cast<devices::InputFile>(device_);
551
552 return (sessionfile_device || inputfile_device);
553}
554
724f29f3
GS
555/**
556 * Convert generic options to data types that are specific to InputFormat.
557 *
3083cda8
UH
558 * @param[in] user_spec Vector of tokenized words, string format.
559 * @param[in] fmt_opts Input format's options, result of InputFormat::options().
724f29f3 560 *
3083cda8 561 * @return Map of options suitable for InputFormat::create_input().
724f29f3
GS
562 */
563map<string, Glib::VariantBase>
564Session::input_format_options(vector<string> user_spec,
565 map<string, shared_ptr<Option>> fmt_opts)
566{
567 map<string, Glib::VariantBase> result;
568
f4ab4b5c 569 for (auto& entry : user_spec) {
724f29f3
GS
570 /*
571 * Split key=value specs. Accept entries without separator
572 * (for simplified boolean specifications).
573 */
574 string key, val;
575 size_t pos = entry.find("=");
576 if (pos == std::string::npos) {
577 key = entry;
578 val = "";
579 } else {
580 key = entry.substr(0, pos);
581 val = entry.substr(pos + 1);
582 }
583
584 /*
585 * Skip user specifications that are not a member of the
586 * format's set of supported options. Have the text input
587 * spec converted to the required input format specific
588 * data type.
589 */
590 auto found = fmt_opts.find(key);
591 if (found == fmt_opts.end())
592 continue;
593 shared_ptr<Option> opt = found->second;
594 result[key] = opt->parse_string(val);
595 }
596
597 return result;
598}
599
611c8625 600void Session::load_init_file(const string &file_name,
96dbf014 601 const string &format, const string &setup_file_name)
fd22c71c
SA
602{
603 shared_ptr<InputFormat> input_format;
724f29f3 604 map<string, Glib::VariantBase> input_opts;
fd22c71c
SA
605
606 if (!format.empty()) {
607 const map<string, shared_ptr<InputFormat> > formats =
608 device_manager_.context()->input_formats();
724f29f3
GS
609 auto user_opts = pv::util::split_string(format, ":");
610 string user_name = user_opts.front();
611 user_opts.erase(user_opts.begin());
fd22c71c
SA
612 const auto iter = find_if(formats.begin(), formats.end(),
613 [&](const pair<string, shared_ptr<InputFormat> > f) {
724f29f3 614 return f.first == user_name; });
fd22c71c 615 if (iter == formats.end()) {
5e685656 616 MainWindow::show_session_error(tr("Error"),
fd22c71c
SA
617 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
618 return;
619 }
fd22c71c 620 input_format = (*iter).second;
724f29f3
GS
621 input_opts = input_format_options(user_opts,
622 input_format->options());
fd22c71c
SA
623 }
624
96dbf014 625 load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
611c8625 626 input_format, input_opts);
fd22c71c
SA
627}
628
96dbf014
SA
629void Session::load_file(QString file_name, QString setup_file_name,
630 shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
fd22c71c
SA
631{
632 const QString errorMessage(
633 QString("Failed to load file %1").arg(file_name));
634
a9674d1c
GS
635 // In the absence of a caller's format spec, try to auto detect.
636 // Assume "sigrok session file" upon lookup miss.
637 if (!format)
638 format = device_manager_.context()->input_format_match(file_name.toStdString());
fd22c71c
SA
639 try {
640 if (format)
641 set_device(shared_ptr<devices::Device>(
642 new devices::InputFile(
643 device_manager_.context(),
644 file_name.toStdString(),
645 format, options)));
646 else
647 set_device(shared_ptr<devices::Device>(
648 new devices::SessionFile(
649 device_manager_.context(),
650 file_name.toStdString())));
30677c13 651 } catch (Error& e) {
0ea2cfc5 652 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
fd22c71c
SA
653 set_default_device();
654 main_bar_->update_device_list();
655 return;
656 }
657
96dbf014 658 // Use the input file with .pvs extension if no setup file was given
b4cc75e0 659 if (setup_file_name.isEmpty()) {
611c8625
DL
660 setup_file_name = file_name;
661 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
662 setup_file_name.append(".pvs");
663 }
96dbf014 664
8962d7b3
SA
665 if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
666 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
667 restore_setup(settings_storage);
668 }
669
fd22c71c
SA
670 main_bar_->update_device_list();
671
672 start_capture([&, errorMessage](QString infoMessage) {
5e685656 673 MainWindow::show_session_error(errorMessage, infoMessage); });
fd22c71c
SA
674
675 set_name(QFileInfo(file_name).fileName());
676}
677
2b81ae46 678Session::capture_state Session::get_capture_state() const
5b7cf66c 679{
8dbbc7f0
JH
680 lock_guard<mutex> lock(sampling_mutex_);
681 return capture_state_;
5b7cf66c
JH
682}
683
2b81ae46 684void Session::start_capture(function<void (const QString)> error_handler)
2e2946fe 685{
34c11fa7
SA
686 if (!device_) {
687 error_handler(tr("No active device set, can't start acquisition."));
688 return;
689 }
690
5b7cf66c
JH
691 stop_capture();
692
6ac6242b 693 // Check that at least one channel is enabled
e6c1382e
JH
694 const shared_ptr<sigrok::Device> sr_dev = device_->device();
695 if (sr_dev) {
696 const auto channels = sr_dev->channels();
6f925ba9 697 if (!any_of(channels.begin(), channels.end(),
e6c1382e
JH
698 [](shared_ptr<Channel> channel) {
699 return channel->enabled(); })) {
700 error_handler(tr("No channels enabled."));
701 return;
702 }
9c48fa57
JH
703 }
704
53ea4c6c 705 // Clear signal data
f4ab4b5c 706 for (const shared_ptr<data::SignalData>& d : all_signal_data_)
47e9e7bb 707 d->clear();
53ea4c6c 708
7ea2a4ff
SA
709 trigger_list_.clear();
710
53bb2e1d
SA
711 // Revert name back to default name (e.g. "Session 1") for real devices
712 // as the (possibly saved) data is gone. File devices keep their name.
713 shared_ptr<devices::HardwareDevice> hw_device =
714 dynamic_pointer_cast< devices::HardwareDevice >(device_);
715
716 if (hw_device) {
717 name_ = default_name_;
718 name_changed();
719 }
101e7a9b 720
9c48fa57 721 // Begin the session
8dbbc7f0 722 sampling_thread_ = std::thread(
2b05d311 723 &Session::sample_thread_proc, this, error_handler);
2e2946fe
JH
724}
725
2b81ae46 726void Session::stop_capture()
5b7cf66c 727{
04463625 728 if (get_capture_state() != Stopped)
da30ecb7 729 device_->stop();
5b7cf66c
JH
730
731 // Check that sampling stopped
8dbbc7f0
JH
732 if (sampling_thread_.joinable())
733 sampling_thread_.join();
5b7cf66c
JH
734}
735
6f925ba9 736void Session::register_view(shared_ptr<views::ViewBase> view)
47e9e7bb 737{
bdbc561f 738 if (views_.empty())
0f8f8c18 739 main_view_ = view;
0f8f8c18 740
3a21afa6 741 views_.push_back(view);
53e8927d 742
f5a5b019 743 // Add all device signals
53e8927d 744 update_signals();
f5a5b019
SA
745
746 // Add all other signals
bdbc561f
SA
747 unordered_set< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
748
749 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
750 const int sb_exists = count_if(
751 view_signalbases.cbegin(), view_signalbases.cend(),
752 [&](const shared_ptr<data::SignalBase> &sb) {
753 return sb == signalbase;
754 });
755
756 // Add the signal to the view if it doesn't have it yet
757 if (!sb_exists)
758 switch (signalbase->type()) {
759 case data::SignalBase::AnalogChannel:
760 case data::SignalBase::LogicChannel:
761 case data::SignalBase::MathChannel:
762 view->add_signalbase(signalbase);
763 break;
764 case data::SignalBase::DecodeChannel:
f5a5b019 765#ifdef ENABLE_DECODE
bdbc561f 766 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
f5a5b019 767#endif
bdbc561f
SA
768 break;
769 }
f5a5b019
SA
770 }
771
772 signals_changed();
47e9e7bb
SA
773}
774
6f925ba9 775void Session::deregister_view(shared_ptr<views::ViewBase> view)
47e9e7bb 776{
6f925ba9 777 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
0f8f8c18
SA
778
779 if (views_.empty()) {
780 main_view_.reset();
781
782 // Without a view there can be no main bar
783 main_bar_.reset();
784 }
47e9e7bb
SA
785}
786
6f925ba9 787bool Session::has_view(shared_ptr<views::ViewBase> view)
101e7a9b 788{
f4ab4b5c 789 for (shared_ptr<views::ViewBase>& v : views_)
3a21afa6
SA
790 if (v == view)
791 return true;
792
793 return false;
101e7a9b
SA
794}
795
2220e942
SA
796double Session::get_samplerate() const
797{
798 double samplerate = 0.0;
799
f4ab4b5c 800 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
47e9e7bb
SA
801 assert(d);
802 const vector< shared_ptr<pv::data::Segment> > segments =
803 d->segments();
f4ab4b5c 804 for (const shared_ptr<pv::data::Segment>& s : segments)
6f925ba9 805 samplerate = max(samplerate, s->samplerate());
2220e942 806 }
2220e942
SA
807 // If there is no sample rate given we use samples as unit
808 if (samplerate == 0.0)
809 samplerate = 1.0;
810
811 return samplerate;
812}
813
9009d9b5 814uint32_t Session::get_segment_count() const
7f965464 815{
9009d9b5 816 uint32_t value = 0;
7f965464 817
9009d9b5 818 // Find the highest number of segments
f4ab4b5c 819 for (const shared_ptr<data::SignalData>& data : all_signal_data_)
9009d9b5
SA
820 if (data->get_segment_count() > value)
821 value = data->get_segment_count();
7f965464 822
9009d9b5 823 return value;
7f965464
SA
824}
825
7ea2a4ff
SA
826vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
827{
828 vector<util::Timestamp> result;
829
f4ab4b5c 830 for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
7ea2a4ff
SA
831 if (entry.first == segment_id)
832 result.push_back(entry.second);
833
834 return result;
835}
836
6f925ba9 837const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
2e2946fe 838{
47e9e7bb 839 return signalbases_;
2e2946fe
JH
840}
841
89914a86
SA
842bool Session::all_segments_complete(uint32_t segment_id) const
843{
844 bool all_complete = true;
845
f4ab4b5c 846 for (const shared_ptr<data::SignalBase>& base : signalbases_)
89914a86
SA
847 if (!base->segment_is_complete(segment_id))
848 all_complete = false;
849
850 return all_complete;
851}
852
269528f5 853#ifdef ENABLE_DECODE
e771b42d 854shared_ptr<data::DecodeSignal> Session::add_decode_signal()
82c7f640 855{
e771b42d 856 shared_ptr<data::DecodeSignal> signal;
a7336fb2 857
2ad82c2e 858 try {
4e5a4405 859 // Create the decode signal
e771b42d 860 signal = make_shared<data::DecodeSignal>(*this);
bf0edd2b 861
ad908057 862 signalbases_.insert(signal);
bb7dd726 863
47747218 864 // Add the decode signal to all views
f4ab4b5c 865 for (shared_ptr<views::ViewBase>& view : views_)
ad908057 866 view->add_decode_signal(signal);
30677c13 867 } catch (runtime_error& e) {
e771b42d
SA
868 remove_decode_signal(signal);
869 return nullptr;
e92cd4e4
JH
870 }
871
82c7f640 872 signals_changed();
e92cd4e4 873
e771b42d 874 return signal;
82c7f640
JH
875}
876
ad908057 877void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
38eeddea 878{
ad908057 879 signalbases_.erase(signal);
2d25fc47 880
f4ab4b5c 881 for (shared_ptr<views::ViewBase>& view : views_)
ad908057 882 view->remove_decode_signal(signal);
2d25fc47
SA
883
884 signals_changed();
c51482b3 885}
269528f5 886#endif
c51482b3 887
2b81ae46 888void Session::set_capture_state(capture_state state)
6ac96c2e 889{
896936e5
TS
890 bool changed;
891
268fd2b8 892 if (state == Running)
6592e8fe 893 acq_time_.restart();
268fd2b8
SA
894 if (state == Stopped)
895 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
896
896936e5
TS
897 {
898 lock_guard<mutex> lock(sampling_mutex_);
899 changed = capture_state_ != state;
900 capture_state_ = state;
901 }
902
f3290553 903 if (changed)
2b49eeb0 904 capture_state_changed(state);
6ac96c2e
JH
905}
906
ffe00119 907void Session::update_signals()
b087ba7f 908{
076eefa4 909 if (!device_) {
47e9e7bb 910 signalbases_.clear();
076eefa4 911 logic_data_.reset();
f4ab4b5c 912 for (shared_ptr<views::ViewBase>& view : views_) {
47e9e7bb 913 view->clear_signals();
bb7dd726 914#ifdef ENABLE_DECODE
f4e57597 915 view->clear_decode_signals();
bb7dd726
SA
916#endif
917 }
076eefa4
SA
918 return;
919 }
e6c1382e
JH
920
921 lock_guard<recursive_mutex> lock(data_mutex_);
b087ba7f 922
ffe00119 923 const shared_ptr<sigrok::Device> sr_dev = device_->device();
c6412b47 924 if (!sr_dev) {
47e9e7bb 925 signalbases_.clear();
c6412b47 926 logic_data_.reset();
f4ab4b5c 927 for (shared_ptr<views::ViewBase>& view : views_) {
47e9e7bb 928 view->clear_signals();
bb7dd726 929#ifdef ENABLE_DECODE
f4e57597 930 view->clear_decode_signals();
bb7dd726
SA
931#endif
932 }
c6412b47
JH
933 return;
934 }
935
b087ba7f 936 // Detect what data types we will receive
c6412b47 937 auto channels = sr_dev->channels();
6f925ba9 938 unsigned int logic_channel_count = count_if(
e8d00928
ML
939 channels.begin(), channels.end(),
940 [] (shared_ptr<Channel> channel) {
472a80c5 941 return channel->type() == sigrok::ChannelType::LOGIC; });
b087ba7f 942
f3d66e52 943 // Create data containers for the logic data segments
b087ba7f 944 {
8524a597 945 lock_guard<recursive_mutex> data_lock(data_mutex_);
b087ba7f 946
3917ba77
JH
947 if (logic_channel_count == 0) {
948 logic_data_.reset();
949 } else if (!logic_data_ ||
950 logic_data_->num_channels() != logic_channel_count) {
8dbbc7f0 951 logic_data_.reset(new data::Logic(
6ac6242b 952 logic_channel_count));
8dbbc7f0 953 assert(logic_data_);
b087ba7f 954 }
b087ba7f
JH
955 }
956
47e9e7bb 957 // Make the signals list
f4ab4b5c 958 for (shared_ptr<views::ViewBase>& viewbase : views_) {
f23c4692
SA
959 views::trace::View *trace_view =
960 qobject_cast<views::trace::View*>(viewbase.get());
f4e57597
SA
961
962 if (trace_view) {
0a952555 963 unordered_set< shared_ptr<Signal> > prev_sigs(trace_view->signals());
f4e57597
SA
964 trace_view->clear_signals();
965
966 for (auto channel : sr_dev->channels()) {
967 shared_ptr<data::SignalBase> signalbase;
0a952555 968 shared_ptr<Signal> signal;
f4e57597
SA
969
970 // Find the channel in the old signals
6f925ba9 971 const auto iter = find_if(
f4e57597 972 prev_sigs.cbegin(), prev_sigs.cend(),
0a952555 973 [&](const shared_ptr<Signal> &s) {
f4e57597
SA
974 return s->base()->channel() == channel;
975 });
976 if (iter != prev_sigs.end()) {
977 // Copy the signal from the old set to the new
978 signal = *iter;
979 trace_view->add_signal(signal);
980 } else {
981 // Find the signalbase for this channel if possible
982 signalbase.reset();
f4ab4b5c 983 for (const shared_ptr<data::SignalBase>& b : signalbases_)
f4e57597
SA
984 if (b->channel() == channel)
985 signalbase = b;
986
0a952555
SA
987 shared_ptr<Signal> signal;
988
f4e57597
SA
989 switch(channel->type()->id()) {
990 case SR_CHANNEL_LOGIC:
991 if (!signalbase) {
472a80c5
SA
992 signalbase = make_shared<data::SignalBase>(channel,
993 data::SignalBase::LogicChannel);
f4e57597
SA
994 signalbases_.insert(signalbase);
995
996 all_signal_data_.insert(logic_data_);
997 signalbase->set_data(logic_data_);
12ea3616
SA
998
999 connect(this, SIGNAL(capture_state_changed(int)),
1000 signalbase.get(), SLOT(on_capture_state_changed(int)));
f4e57597
SA
1001 }
1002
0a952555 1003 signal = shared_ptr<Signal>(new LogicSignal(*this, device_, signalbase));
f4e57597
SA
1004 break;
1005
1006 case SR_CHANNEL_ANALOG:
1007 {
1008 if (!signalbase) {
472a80c5
SA
1009 signalbase = make_shared<data::SignalBase>(channel,
1010 data::SignalBase::AnalogChannel);
f4e57597
SA
1011 signalbases_.insert(signalbase);
1012
1013 shared_ptr<data::Analog> data(new data::Analog());
1014 all_signal_data_.insert(data);
1015 signalbase->set_data(data);
12ea3616
SA
1016
1017 connect(this, SIGNAL(capture_state_changed(int)),
1018 signalbase.get(), SLOT(on_capture_state_changed(int)));
f4e57597
SA
1019 }
1020
0a952555 1021 signal = shared_ptr<Signal>(new AnalogSignal(*this, signalbase));
f4e57597 1022 break;
47e9e7bb
SA
1023 }
1024
f4e57597 1025 default:
0402d7a3 1026 assert(false);
f4e57597 1027 break;
47e9e7bb 1028 }
0a952555
SA
1029
1030 // New views take their signal settings from the main view
1031 if (!viewbase->is_main_view()) {
1032 shared_ptr<pv::views::trace::View> main_tv =
1033 dynamic_pointer_cast<pv::views::trace::View>(main_view_);
1034 shared_ptr<Signal> main_signal =
1035 main_tv->get_signal_by_signalbase(signalbase);
1036 signal->restore_settings(main_signal->save_settings());
1037 }
1038
1039 trace_view->add_signal(signal);
3917ba77 1040 }
b087ba7f
JH
1041 }
1042 }
fbd3e234 1043 }
b087ba7f
JH
1044
1045 signals_changed();
1046}
1047
cbd2a2de 1048shared_ptr<data::SignalBase> Session::signalbase_from_channel(
bf0edd2b 1049 shared_ptr<sigrok::Channel> channel) const
3ddcc083 1050{
bf0edd2b 1051 for (shared_ptr<data::SignalBase> sig : signalbases_) {
3ddcc083 1052 assert(sig);
6ac6242b 1053 if (sig->channel() == channel)
3ddcc083
JH
1054 return sig;
1055 }
bf0edd2b 1056 return shared_ptr<data::SignalBase>();
3ddcc083
JH
1057}
1058
2b05d311 1059void Session::sample_thread_proc(function<void (const QString)> error_handler)
274d4f13 1060{
f2edb557 1061 assert(error_handler);
be73bdfa 1062
5f9a5209
SA
1063#ifdef ENABLE_FLOW
1064 pipeline_ = Pipeline::create();
1065
1066 source_ = ElementFactory::create_element("filesrc", "source");
1067 sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1068
1069 pipeline_->add(source_)->add(sink_);
1070 source_->link(sink_);
1071
1072 source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1073
1074 sink_->set_property("emit-signals", TRUE);
1075 sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1076
1077 // Get the bus from the pipeline and add a bus watch to the default main context
1078 RefPtr<Bus> bus = pipeline_->get_bus();
1079 bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1080
1081 // Start pipeline and Wait until it finished processing
1082 pipeline_done_interrupt_ = false;
1083 pipeline_->set_state(Gst::STATE_PLAYING);
1084
1085 unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1086 pipeline_done_cond_.wait(pipeline_done_lock_);
1087
1088 // Let the pipeline free all resources
1089 pipeline_->set_state(Gst::STATE_NULL);
1090
1091#else
34c11fa7
SA
1092 if (!device_)
1093 return;
45f0c7c9 1094
e170ab65
SA
1095 try {
1096 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1097 } catch (Error& e) {
1098 cur_samplerate_ = 0;
1099 }
274d4f13 1100
e7216ae0
SA
1101 out_of_memory_ = false;
1102
4e86ec70
SA
1103 {
1104 lock_guard<recursive_mutex> lock(data_mutex_);
1105 cur_logic_segment_.reset();
1106 cur_analog_segments_.clear();
1107 }
1108 highest_segment_id_ = -1;
7ea2a4ff 1109 frame_began_ = false;
4e86ec70 1110
ae2d1bc5 1111 try {
5237f0c5 1112 device_->start();
30677c13 1113 } catch (Error& e) {
e8d00928 1114 error_handler(e.what());
eec446e1
JH
1115 return;
1116 }
1117
da30ecb7 1118 set_capture_state(device_->session()->trigger() ?
07dcf561 1119 AwaitingTrigger : Running);
eec446e1 1120
dc4ada2b
SA
1121 try {
1122 device_->run();
30677c13 1123 } catch (Error& e) {
dc4ada2b
SA
1124 error_handler(e.what());
1125 set_capture_state(Stopped);
1126 return;
6f381ee7
SA
1127 } catch (QString& e) {
1128 error_handler(e);
1129 set_capture_state(Stopped);
1130 return;
dc4ada2b
SA
1131 }
1132
eec446e1 1133 set_capture_state(Stopped);
1a2fe44c
JH
1134
1135 // Confirm that SR_DF_END was received
403c3e87
SA
1136 if (cur_logic_segment_)
1137 qDebug() << "WARNING: SR_DF_END was not received.";
5f9a5209 1138#endif
e7216ae0 1139
5e6967cb
SA
1140 // Optimize memory usage
1141 free_unused_memory();
1142
5ccfc97e
SA
1143 // We now have unsaved data unless we just "captured" from a file
1144 shared_ptr<devices::File> file_device =
1145 dynamic_pointer_cast<devices::File>(device_);
1146
1147 if (!file_device)
1148 data_saved_ = false;
1149
e7216ae0
SA
1150 if (out_of_memory_)
1151 error_handler(tr("Out of memory, acquisition stopped."));
eec446e1
JH
1152}
1153
5e6967cb
SA
1154void Session::free_unused_memory()
1155{
f4ab4b5c 1156 for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
5e6967cb
SA
1157 const vector< shared_ptr<data::Segment> > segments = data->segments();
1158
f4ab4b5c 1159 for (const shared_ptr<data::Segment>& segment : segments)
5e6967cb 1160 segment->free_unused_memory();
5e6967cb
SA
1161 }
1162}
1163
4e86ec70
SA
1164void Session::signal_new_segment()
1165{
341d9a79 1166 int new_segment_id = 0;
4e86ec70
SA
1167
1168 if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1169
1170 // Determine new frame/segment number, assuming that all
1171 // signals have the same number of frames/segments
1172 if (cur_logic_segment_) {
341d9a79 1173 new_segment_id = logic_data_->get_segment_count() - 1;
4e86ec70
SA
1174 } else {
1175 shared_ptr<sigrok::Channel> any_channel =
1176 (*cur_analog_segments_.begin()).first;
1177
1178 shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1179 assert(base);
1180
1181 shared_ptr<data::Analog> data(base->analog_data());
1182 assert(data);
1183
341d9a79 1184 new_segment_id = data->get_segment_count() - 1;
4e86ec70
SA
1185 }
1186 }
1187
1188 if (new_segment_id > highest_segment_id_) {
1189 highest_segment_id_ = new_segment_id;
1190 new_segment(highest_segment_id_);
1191 }
1192}
1193
558ad6ce
SA
1194void Session::signal_segment_completed()
1195{
1196 int segment_id = 0;
1197
f4ab4b5c 1198 for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
558ad6ce
SA
1199 // We only care about analog and logic channels, not derived ones
1200 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1201 segment_id = signalbase->analog_data()->get_segment_count() - 1;
1202 break;
1203 }
1204
1205 if (signalbase->type() == data::SignalBase::LogicChannel) {
1206 segment_id = signalbase->logic_data()->get_segment_count() - 1;
1207 break;
1208 }
1209 }
1210
1211 if (segment_id >= 0)
1212 segment_completed(segment_id);
1213}
1214
5f9a5209
SA
1215#ifdef ENABLE_FLOW
1216bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1217{
1218 (void)bus;
1219
1220 if ((message->get_source() == pipeline_) && \
1221 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1222 pipeline_done_cond_.notify_one();
1223
1224 // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1225
1226 return true;
1227}
1228
1229Gst::FlowReturn Session::on_gst_new_sample()
1230{
1231 RefPtr<Gst::Sample> sample = sink_->pull_sample();
1232 RefPtr<Gst::Buffer> buf = sample->get_buffer();
1233
1234 for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1235 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1236 Gst::MapInfo mapinfo;
1237 buf_mem->map(mapinfo, Gst::MAP_READ);
1238
1239 shared_ptr<sigrok::Packet> logic_packet =
1240 sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1241
1242 try {
1243 feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1244 } catch (bad_alloc&) {
1245 out_of_memory_ = true;
1246 device_->stop();
1247 buf_mem->unmap(mapinfo);
1248 return Gst::FLOW_ERROR;
1249 }
1250
1251 buf_mem->unmap(mapinfo);
1252 }
1253
1254 return Gst::FLOW_OK;
1255}
1256#endif
1257
da30ecb7 1258void Session::feed_in_header()
eec446e1 1259{
b5940cf0 1260 // Nothing to do here for now
be73bdfa
JH
1261}
1262
da30ecb7 1263void Session::feed_in_meta(shared_ptr<Meta> meta)
be73bdfa 1264{
f4ab4b5c 1265 for (auto& entry : meta->config()) {
e8d00928 1266 switch (entry.first->id()) {
be73bdfa 1267 case SR_CONF_SAMPLERATE:
014293fc 1268 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
be73bdfa
JH
1269 break;
1270 default:
014293fc 1271 qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
be73bdfa
JH
1272 break;
1273 }
aba1dd16 1274 }
74043039
JH
1275
1276 signals_changed();
aba1dd16
JH
1277}
1278
48257a69
SA
1279void Session::feed_in_trigger()
1280{
1281 // The channel containing most samples should be most accurate
1282 uint64_t sample_count = 0;
1283
cc9a7898 1284 {
f4ab4b5c 1285 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
cc9a7898
SA
1286 assert(d);
1287 uint64_t temp_count = 0;
1288
1289 const vector< shared_ptr<pv::data::Segment> > segments =
1290 d->segments();
1291 for (const shared_ptr<pv::data::Segment> &s : segments)
1292 temp_count += s->get_sample_count();
1293
1294 if (temp_count > sample_count)
1295 sample_count = temp_count;
1296 }
48257a69
SA
1297 }
1298
a66e286e
SA
1299 uint32_t segment_id = 0; // Default segment when no frames are used
1300
1301 // If a frame began, we'd ideally be able to use the highest segment ID for
1302 // the trigger. However, as new segments are only created when logic or
1303 // analog data comes in, this doesn't work if the trigger appears right
1304 // after the beginning of the frame, before any sample data.
1305 // For this reason, we use highest segment ID + 1 if no sample data came in
1306 // yet and the highest segment ID otherwise.
1307 if (frame_began_) {
1308 segment_id = highest_segment_id_;
1309 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1310 segment_id++;
1311 }
7ea2a4ff 1312
a66e286e 1313 // TODO Create timestamp from segment start time + segment's current sample count
7ea2a4ff
SA
1314 util::Timestamp timestamp = sample_count / get_samplerate();
1315 trigger_list_.emplace_back(segment_id, timestamp);
1316 trigger_event(segment_id, timestamp);
48257a69
SA
1317}
1318
2b81ae46 1319void Session::feed_in_frame_begin()
82f50b10 1320{
837bb15a 1321 frame_began_ = true;
82f50b10
JH
1322}
1323
837bb15a
SA
1324void Session::feed_in_frame_end()
1325{
558ad6ce
SA
1326 if (!frame_began_)
1327 return;
1328
837bb15a
SA
1329 {
1330 lock_guard<recursive_mutex> lock(data_mutex_);
558ad6ce
SA
1331
1332 if (cur_logic_segment_)
1333 cur_logic_segment_->set_complete();
1334
f4ab4b5c 1335 for (auto& entry : cur_analog_segments_) {
558ad6ce
SA
1336 shared_ptr<data::AnalogSegment> segment = entry.second;
1337 segment->set_complete();
1338 }
1339
837bb15a
SA
1340 cur_logic_segment_.reset();
1341 cur_analog_segments_.clear();
1342 }
1343
7ea2a4ff 1344 frame_began_ = false;
558ad6ce
SA
1345
1346 signal_segment_completed();
837bb15a
SA
1347}
1348
2b81ae46 1349void Session::feed_in_logic(shared_ptr<Logic> logic)
9c112671 1350{
eaa02ef4
SA
1351 if (logic->data_length() == 0) {
1352 qDebug() << "WARNING: Received logic packet with 0 samples.";
1353 return;
1354 }
1355
6f381ee7
SA
1356 if (logic->unit_size() > 8)
1357 throw QString(tr("Can't handle more than 64 logic channels."));
1358
b5940cf0 1359 if (!cur_samplerate_)
e170ab65
SA
1360 try {
1361 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1362 } catch (Error& e) {
1363 // Do nothing
1364 }
b5940cf0 1365
8524a597 1366 lock_guard<recursive_mutex> lock(data_mutex_);
79efbc53 1367
2ad82c2e 1368 if (!logic_data_) {
e6c1382e
JH
1369 // The only reason logic_data_ would not have been created is
1370 // if it was not possible to determine the signals when the
1371 // device was created.
1372 update_signals();
79efbc53 1373 }
be73bdfa 1374
2ad82c2e 1375 if (!cur_logic_segment_) {
bb2cdfff 1376 // This could be the first packet after a trigger
2b49eeb0
JH
1377 set_capture_state(Running);
1378
f3d66e52 1379 // Create a new data segment
067bb624 1380 cur_logic_segment_ = make_shared<data::LogicSegment>(
85a70280
SA
1381 *logic_data_, logic_data_->get_segment_count(),
1382 logic->unit_size(), cur_samplerate_);
f3d66e52 1383 logic_data_->push_segment(cur_logic_segment_);
82f50b10 1384
4e86ec70 1385 signal_new_segment();
9c112671
JH
1386 }
1387
04e1acc2
SA
1388 cur_logic_segment_->append_payload(logic);
1389
1f374035 1390 data_received();
9c112671
JH
1391}
1392
2b81ae46 1393void Session::feed_in_analog(shared_ptr<Analog> analog)
aba1dd16 1394{
eaa02ef4
SA
1395 if (analog->num_samples() == 0) {
1396 qDebug() << "WARNING: Received analog packet with 0 samples.";
1397 return;
1398 }
1399
b5940cf0 1400 if (!cur_samplerate_)
e170ab65
SA
1401 try {
1402 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1403 } catch (Error& e) {
1404 // Do nothing
1405 }
b5940cf0 1406
8524a597 1407 lock_guard<recursive_mutex> lock(data_mutex_);
79efbc53 1408
e8d00928 1409 const vector<shared_ptr<Channel>> channels = analog->channels();
bb2cdfff 1410 bool sweep_beginning = false;
be73bdfa 1411
3e617752 1412 unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
303eec78
SA
1413 analog->get_data_as_float(data.get());
1414
47e9e7bb 1415 if (signalbases_.empty())
a3f678a7 1416 update_signals();
a3f678a7 1417
303eec78 1418 float *channel_data = data.get();
f4ab4b5c 1419 for (auto& channel : channels) {
f3d66e52 1420 shared_ptr<data::AnalogSegment> segment;
2b49eeb0 1421
f3d66e52
JH
1422 // Try to get the segment of the channel
1423 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1424 iterator iter = cur_analog_segments_.find(channel);
1425 if (iter != cur_analog_segments_.end())
1426 segment = (*iter).second;
2ad82c2e 1427 else {
39ccf9c3 1428 // If no segment was found, this means we haven't
bb2cdfff 1429 // created one yet. i.e. this is the first packet
f3d66e52 1430 // in the sweep containing this segment.
bb2cdfff
JH
1431 sweep_beginning = true;
1432
ff4bf6bd 1433 // Find the analog data associated with the channel
cbd2a2de
SA
1434 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1435 assert(base);
bb2cdfff 1436
cbd2a2de 1437 shared_ptr<data::Analog> data(base->analog_data());
bb2cdfff
JH
1438 assert(data);
1439
7db61e77 1440 // Create a segment, keep it in the maps of channels
067bb624 1441 segment = make_shared<data::AnalogSegment>(
85a70280 1442 *data, data->get_segment_count(), cur_samplerate_);
7db61e77
SA
1443 cur_analog_segments_[channel] = segment;
1444
f3d66e52
JH
1445 // Push the segment into the analog data.
1446 data->push_segment(segment);
4e86ec70
SA
1447
1448 signal_new_segment();
bb2cdfff
JH
1449 }
1450
f3d66e52 1451 assert(segment);
bb2cdfff 1452
f3d66e52 1453 // Append the samples in the segment
3e617752
SA
1454 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1455 channels.size());
aba1dd16 1456 }
bb2cdfff
JH
1457
1458 if (sweep_beginning) {
1459 // This could be the first packet after a trigger
1460 set_capture_state(Running);
aba1dd16
JH
1461 }
1462
1f374035 1463 data_received();
aba1dd16 1464}
9c112671 1465
da30ecb7
JH
1466void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1467 shared_ptr<Packet> packet)
b0e1d01d 1468{
da30ecb7
JH
1469 (void)device;
1470
e8d00928 1471 assert(device);
da30ecb7 1472 assert(device == device_->device());
b0e1d01d
JH
1473 assert(packet);
1474
e8d00928 1475 switch (packet->type()->id()) {
b0e1d01d 1476 case SR_DF_HEADER:
da30ecb7 1477 feed_in_header();
b0e1d01d
JH
1478 break;
1479
be73bdfa 1480 case SR_DF_META:
da30ecb7 1481 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
aba1dd16
JH
1482 break;
1483
48257a69
SA
1484 case SR_DF_TRIGGER:
1485 feed_in_trigger();
1486 break;
1487
2e2946fe 1488 case SR_DF_LOGIC:
e7216ae0
SA
1489 try {
1490 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
30677c13 1491 } catch (bad_alloc&) {
e7216ae0
SA
1492 out_of_memory_ = true;
1493 device_->stop();
1494 }
2953961c
JH
1495 break;
1496
aba1dd16 1497 case SR_DF_ANALOG:
e7216ae0
SA
1498 try {
1499 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
30677c13 1500 } catch (bad_alloc&) {
e7216ae0
SA
1501 out_of_memory_ = true;
1502 device_->stop();
1503 }
aba1dd16
JH
1504 break;
1505
837bb15a
SA
1506 case SR_DF_FRAME_BEGIN:
1507 feed_in_frame_begin();
1508 break;
1509
0a4162a4 1510 case SR_DF_FRAME_END:
837bb15a
SA
1511 feed_in_frame_end();
1512 break;
1513
2953961c 1514 case SR_DF_END:
837bb15a
SA
1515 // Strictly speaking, this is performed when a frame end marker was
1516 // received, so there's no point doing this again. However, not all
1517 // devices use frames, and for those devices, we need to do it here.
2e2946fe 1518 {
8524a597 1519 lock_guard<recursive_mutex> lock(data_mutex_);
7c611046
SA
1520
1521 if (cur_logic_segment_)
1522 cur_logic_segment_->set_complete();
1523
f4ab4b5c 1524 for (auto& entry : cur_analog_segments_) {
7c611046
SA
1525 shared_ptr<data::AnalogSegment> segment = entry.second;
1526 segment->set_complete();
1527 }
1528
f3d66e52
JH
1529 cur_logic_segment_.reset();
1530 cur_analog_segments_.clear();
2e2946fe 1531 }
2953961c 1532 break;
837bb15a 1533
adb0a983
ML
1534 default:
1535 break;
2e2946fe 1536 }
2953961c
JH
1537}
1538
5ccfc97e
SA
1539void Session::on_data_saved()
1540{
1541 data_saved_ = true;
1542}
1543
97378470
SA
1544#ifdef ENABLE_DECODE
1545void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1546{
1547 assert(decoders.size() > 0);
1548
1549 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1550
1551 if (signal)
ed75426f
SA
1552 for (unsigned int i = 0; i < decoders.size(); i++) {
1553 const srd_decoder* d = decoders[i];
1554 signal->stack_decoder(d, !(i < decoders.size() - 1));
1555 }
97378470
SA
1556}
1557#endif
1558
51e77110 1559} // namespace pv