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