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