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