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