a71ad1c56d2b2001bf0e65cdb2e706613ba09f1a
[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
783         // Revert name back to default name (e.g. "Session 1") for real devices
784         // as the (possibly saved) data is gone. File devices keep their name.
785         shared_ptr<devices::HardwareDevice> hw_device =
786                 dynamic_pointer_cast< devices::HardwareDevice >(device_);
787
788         if (hw_device) {
789                 name_ = default_name_;
790                 name_changed();
791         }
792
793         // Begin the session
794         sampling_thread_ = std::thread(
795                 &Session::sample_thread_proc, this, error_handler);
796 }
797
798 void Session::stop_capture()
799 {
800         if (get_capture_state() != Stopped)
801                 device_->stop();
802
803         // Check that sampling stopped
804         if (sampling_thread_.joinable())
805                 sampling_thread_.join();
806 }
807
808 void Session::register_view(shared_ptr<views::ViewBase> view)
809 {
810         if (views_.empty())
811                 main_view_ = view;
812
813         views_.push_back(view);
814
815         // Add all device signals
816         update_signals();
817
818         // Add all other signals
819         vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
820
821         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
822                 const int sb_exists = count_if(
823                         view_signalbases.cbegin(), view_signalbases.cend(),
824                         [&](const shared_ptr<data::SignalBase> &sb) {
825                                 return sb == signalbase;
826                         });
827
828                 // Add the signal to the view if it doesn't have it yet
829                 if (!sb_exists)
830                         switch (signalbase->type()) {
831                         case data::SignalBase::AnalogChannel:
832                         case data::SignalBase::LogicChannel:
833                         case data::SignalBase::MathChannel:
834                                 view->add_signalbase(signalbase);
835                                 break;
836                         case data::SignalBase::DecodeChannel:
837 #ifdef ENABLE_DECODE
838                                 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
839 #endif
840                                 break;
841                         }
842         }
843
844         signals_changed();
845 }
846
847 void Session::deregister_view(shared_ptr<views::ViewBase> view)
848 {
849         views_.erase(std::remove_if(views_.begin(), views_.end(),
850                 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
851                 views_.end());
852
853         if (views_.empty()) {
854                 main_view_.reset();
855
856                 // Without a view there can be no main bar
857                 main_bar_.reset();
858         }
859 }
860
861 bool Session::has_view(shared_ptr<views::ViewBase> view)
862 {
863         for (shared_ptr<views::ViewBase>& v : views_)
864                 if (v == view)
865                         return true;
866
867         return false;
868 }
869
870 double Session::get_samplerate() const
871 {
872         double samplerate = 0.0;
873
874         for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
875                 assert(d);
876                 const vector< shared_ptr<pv::data::Segment> > segments =
877                         d->segments();
878                 for (const shared_ptr<pv::data::Segment>& s : segments)
879                         samplerate = max(samplerate, s->samplerate());
880         }
881         // If there is no sample rate given we use samples as unit
882         if (samplerate == 0.0)
883                 samplerate = 1.0;
884
885         return samplerate;
886 }
887
888 uint32_t Session::get_segment_count() const
889 {
890         uint32_t value = 0;
891
892         // Find the highest number of segments
893         for (const shared_ptr<data::SignalData>& data : all_signal_data_)
894                 if (data->get_segment_count() > value)
895                         value = data->get_segment_count();
896
897         return value;
898 }
899
900 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
901 {
902         vector<util::Timestamp> result;
903
904         for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
905                 if (entry.first == segment_id)
906                         result.push_back(entry.second);
907
908         return result;
909 }
910
911 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
912 {
913         return signalbases_;
914 }
915
916 void Session::add_generated_signal(shared_ptr<data::SignalBase> signal)
917 {
918         signalbases_.push_back(signal);
919
920         for (shared_ptr<views::ViewBase>& view : views_)
921                 view->add_signalbase(signal);
922
923         update_signals();
924 }
925
926 void Session::remove_generated_signal(shared_ptr<data::SignalBase> signal)
927 {
928         if (shutting_down_)
929                 return;
930
931         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
932                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
933                 signalbases_.end());
934
935         for (shared_ptr<views::ViewBase>& view : views_)
936                 view->remove_signalbase(signal);
937
938         update_signals();
939 }
940
941 #ifdef ENABLE_DECODE
942 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
943 {
944         shared_ptr<data::DecodeSignal> signal;
945
946         try {
947                 // Create the decode signal
948                 signal = make_shared<data::DecodeSignal>(*this);
949
950                 signalbases_.push_back(signal);
951
952                 // Add the decode signal to all views
953                 for (shared_ptr<views::ViewBase>& view : views_)
954                         view->add_decode_signal(signal);
955         } catch (runtime_error& e) {
956                 remove_decode_signal(signal);
957                 return nullptr;
958         }
959
960         signals_changed();
961
962         return signal;
963 }
964
965 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
966 {
967         if (shutting_down_)
968                 return;
969
970         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
971                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
972                 signalbases_.end());
973
974         for (shared_ptr<views::ViewBase>& view : views_)
975                 view->remove_decode_signal(signal);
976
977         signals_changed();
978 }
979 #endif
980
981 bool Session::all_segments_complete(uint32_t segment_id) const
982 {
983         bool all_complete = true;
984
985         for (const shared_ptr<data::SignalBase>& base : signalbases_)
986                 if (!base->segment_is_complete(segment_id))
987                         all_complete = false;
988
989         return all_complete;
990 }
991
992 MetadataObjManager* Session::metadata_obj_manager()
993 {
994         return &metadata_obj_manager_;
995 }
996
997 void Session::set_capture_state(capture_state state)
998 {
999         bool changed;
1000
1001         if (state == Running)
1002                 acq_time_.restart();
1003         if (state == Stopped)
1004                 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
1005
1006         {
1007                 lock_guard<mutex> lock(sampling_mutex_);
1008                 changed = capture_state_ != state;
1009                 capture_state_ = state;
1010         }
1011
1012         if (changed)
1013                 capture_state_changed(state);
1014 }
1015
1016 void Session::update_signals()
1017 {
1018         if (!device_) {
1019                 signalbases_.clear();
1020                 logic_data_.reset();
1021                 for (shared_ptr<views::ViewBase>& view : views_) {
1022                         view->clear_signalbases();
1023 #ifdef ENABLE_DECODE
1024                         view->clear_decode_signals();
1025 #endif
1026                 }
1027                 return;
1028         }
1029
1030         lock_guard<recursive_mutex> lock(data_mutex_);
1031
1032         const shared_ptr<sigrok::Device> sr_dev = device_->device();
1033         if (!sr_dev) {
1034                 signalbases_.clear();
1035                 logic_data_.reset();
1036                 for (shared_ptr<views::ViewBase>& view : views_) {
1037                         view->clear_signalbases();
1038 #ifdef ENABLE_DECODE
1039                         view->clear_decode_signals();
1040 #endif
1041                 }
1042                 return;
1043         }
1044
1045         // Detect what data types we will receive
1046         auto channels = sr_dev->channels();
1047         unsigned int logic_channel_count = count_if(
1048                 channels.begin(), channels.end(),
1049                 [] (shared_ptr<Channel> channel) {
1050                         return channel->type() == sigrok::ChannelType::LOGIC; });
1051
1052         // Create a common data container for the logic signalbases
1053         {
1054                 lock_guard<recursive_mutex> data_lock(data_mutex_);
1055
1056                 if (logic_channel_count == 0) {
1057                         logic_data_.reset();
1058                 } else if (!logic_data_ ||
1059                         logic_data_->num_channels() != logic_channel_count) {
1060                         logic_data_.reset(new data::Logic(logic_channel_count));
1061                         assert(logic_data_);
1062                 }
1063         }
1064
1065         // Create signalbases if necessary
1066         for (auto channel : sr_dev->channels()) {
1067
1068                 // Try to find the channel in the list of existing signalbases
1069                 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1070                         [&](const shared_ptr<SignalBase> &sb) { return sb->channel() == channel; });
1071
1072                 // Not found, let's make a signalbase for it
1073                 if (iter == signalbases_.cend()) {
1074                         shared_ptr<SignalBase> signalbase;
1075                         switch(channel->type()->id()) {
1076                         case SR_CHANNEL_LOGIC:
1077                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::LogicChannel);
1078                                 signalbases_.push_back(signalbase);
1079
1080                                 all_signal_data_.insert(logic_data_);
1081                                 signalbase->set_data(logic_data_);
1082
1083                                 connect(this, SIGNAL(capture_state_changed(int)),
1084                                         signalbase.get(), SLOT(on_capture_state_changed(int)));
1085                                 break;
1086
1087                         case SR_CHANNEL_ANALOG:
1088                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::AnalogChannel);
1089                                 signalbases_.push_back(signalbase);
1090
1091                                 shared_ptr<data::Analog> data(new data::Analog());
1092                                 all_signal_data_.insert(data);
1093                                 signalbase->set_data(data);
1094
1095                                 connect(this, SIGNAL(capture_state_changed(int)),
1096                                         signalbase.get(), SLOT(on_capture_state_changed(int)));
1097                                 break;
1098                         }
1099                 }
1100         }
1101
1102         // Create and assign default signal groups if needed
1103         if (signal_groups_.empty()) {
1104                 for (auto& entry : sr_dev->channel_groups()) {
1105                         const shared_ptr<sigrok::ChannelGroup>& group = entry.second;
1106
1107                         if (group->channels().size() <= 1)
1108                                 continue;
1109
1110                         SignalGroup* sg = new SignalGroup(QString::fromStdString(entry.first));
1111                         for (const shared_ptr<sigrok::Channel>& channel : group->channels()) {
1112                                 for (shared_ptr<data::SignalBase> s : signalbases_) {
1113                                         if (s->channel() == channel) {
1114                                                 sg->append_signal(s);
1115                                                 break;
1116                                         }
1117                                 }
1118                         }
1119                         signal_groups_.emplace_back(sg);
1120                 }
1121         }
1122
1123         // Update all views
1124         for (shared_ptr<views::ViewBase>& viewbase : views_) {
1125                 vector< shared_ptr<SignalBase> > view_signalbases =
1126                                 viewbase->signalbases();
1127
1128                 // Add all non-decode signalbases that don't yet exist in the view
1129                 for (shared_ptr<SignalBase>& session_sb : signalbases_) {
1130                         if (session_sb->type() == SignalBase::DecodeChannel)
1131                                 continue;
1132
1133                         const auto iter = find_if(view_signalbases.cbegin(), view_signalbases.cend(),
1134                                 [&](const shared_ptr<SignalBase> &sb) { return sb == session_sb; });
1135
1136                         if (iter == view_signalbases.cend())
1137                                 viewbase->add_signalbase(session_sb);
1138                 }
1139
1140                 // Remove all non-decode signalbases that no longer exist
1141                 for (shared_ptr<SignalBase>& view_sb : view_signalbases) {
1142                         if (view_sb->type() == SignalBase::DecodeChannel)
1143                                 continue;
1144
1145                         const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1146                                 [&](const shared_ptr<SignalBase> &sb) { return sb == view_sb; });
1147
1148                         if (iter == signalbases_.cend())
1149                                 viewbase->remove_signalbase(view_sb);
1150                 }
1151         }
1152
1153         signals_changed();
1154 }
1155
1156 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1157         shared_ptr<sigrok::Channel> channel) const
1158 {
1159         for (shared_ptr<data::SignalBase> sig : signalbases_) {
1160                 assert(sig);
1161                 if (sig->channel() == channel)
1162                         return sig;
1163         }
1164         return shared_ptr<data::SignalBase>();
1165 }
1166
1167 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1168 {
1169         assert(error_handler);
1170
1171 #ifdef ENABLE_FLOW
1172         pipeline_ = Pipeline::create();
1173
1174         source_ = ElementFactory::create_element("filesrc", "source");
1175         sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1176
1177         pipeline_->add(source_)->add(sink_);
1178         source_->link(sink_);
1179
1180         source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1181
1182         sink_->set_property("emit-signals", TRUE);
1183         sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1184
1185         // Get the bus from the pipeline and add a bus watch to the default main context
1186         RefPtr<Bus> bus = pipeline_->get_bus();
1187         bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1188
1189         // Start pipeline and Wait until it finished processing
1190         pipeline_done_interrupt_ = false;
1191         pipeline_->set_state(Gst::STATE_PLAYING);
1192
1193         unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1194         pipeline_done_cond_.wait(pipeline_done_lock_);
1195
1196         // Let the pipeline free all resources
1197         pipeline_->set_state(Gst::STATE_NULL);
1198
1199 #else
1200         if (!device_)
1201                 return;
1202
1203         try {
1204                 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1205         } catch (Error& e) {
1206                 cur_samplerate_ = 0;
1207         }
1208
1209         out_of_memory_ = false;
1210
1211         {
1212                 lock_guard<recursive_mutex> lock(data_mutex_);
1213                 cur_logic_segment_.reset();
1214                 cur_analog_segments_.clear();
1215                 for (shared_ptr<data::SignalBase> sb : signalbases_)
1216                         sb->clear_sample_data();
1217         }
1218         highest_segment_id_ = -1;
1219         frame_began_ = false;
1220
1221         try {
1222                 device_->start();
1223         } catch (Error& e) {
1224                 error_handler(e.what());
1225                 return;
1226         }
1227
1228         set_capture_state(device_->session()->trigger() ?
1229                 AwaitingTrigger : Running);
1230
1231         try {
1232                 device_->run();
1233         } catch (Error& e) {
1234                 error_handler(e.what());
1235                 set_capture_state(Stopped);
1236                 return;
1237         } catch (QString& e) {
1238                 error_handler(e);
1239                 set_capture_state(Stopped);
1240                 return;
1241         }
1242
1243         set_capture_state(Stopped);
1244
1245         // Confirm that SR_DF_END was received
1246         if (cur_logic_segment_)
1247                 qDebug() << "WARNING: SR_DF_END was not received.";
1248 #endif
1249
1250         // Optimize memory usage
1251         free_unused_memory();
1252
1253         // We now have unsaved data unless we just "captured" from a file
1254         shared_ptr<devices::File> file_device =
1255                 dynamic_pointer_cast<devices::File>(device_);
1256
1257         if (!file_device)
1258                 data_saved_ = false;
1259
1260         if (out_of_memory_)
1261                 error_handler(tr("Out of memory, acquisition stopped."));
1262 }
1263
1264 void Session::free_unused_memory()
1265 {
1266         for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1267                 const vector< shared_ptr<data::Segment> > segments = data->segments();
1268
1269                 for (const shared_ptr<data::Segment>& segment : segments)
1270                         segment->free_unused_memory();
1271         }
1272 }
1273
1274 void Session::signal_new_segment()
1275 {
1276         int new_segment_id = 0;
1277
1278         if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1279
1280                 // Determine new frame/segment number, assuming that all
1281                 // signals have the same number of frames/segments
1282                 if (cur_logic_segment_) {
1283                         new_segment_id = logic_data_->get_segment_count() - 1;
1284                 } else {
1285                         shared_ptr<sigrok::Channel> any_channel =
1286                                 (*cur_analog_segments_.begin()).first;
1287
1288                         shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1289                         assert(base);
1290
1291                         shared_ptr<data::Analog> data(base->analog_data());
1292                         assert(data);
1293
1294                         new_segment_id = data->get_segment_count() - 1;
1295                 }
1296         }
1297
1298         if (new_segment_id > highest_segment_id_) {
1299                 highest_segment_id_ = new_segment_id;
1300                 new_segment(highest_segment_id_);
1301         }
1302 }
1303
1304 void Session::signal_segment_completed()
1305 {
1306         int segment_id = 0;
1307
1308         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1309                 // We only care about analog and logic channels, not derived ones
1310                 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1311                         segment_id = signalbase->analog_data()->get_segment_count() - 1;
1312                         break;
1313                 }
1314
1315                 if (signalbase->type() == data::SignalBase::LogicChannel) {
1316                         segment_id = signalbase->logic_data()->get_segment_count() - 1;
1317                         break;
1318                 }
1319         }
1320
1321         if (segment_id >= 0)
1322                 segment_completed(segment_id);
1323 }
1324
1325 #ifdef ENABLE_FLOW
1326 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1327 {
1328         (void)bus;
1329
1330         if ((message->get_source() == pipeline_) && \
1331                 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1332                 pipeline_done_cond_.notify_one();
1333
1334         // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1335
1336         return true;
1337 }
1338
1339 Gst::FlowReturn Session::on_gst_new_sample()
1340 {
1341         RefPtr<Gst::Sample> sample = sink_->pull_sample();
1342         RefPtr<Gst::Buffer> buf = sample->get_buffer();
1343
1344         for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1345                 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1346                 Gst::MapInfo mapinfo;
1347                 buf_mem->map(mapinfo, Gst::MAP_READ);
1348
1349                 shared_ptr<sigrok::Packet> logic_packet =
1350                         sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1351
1352                 try {
1353                         feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1354                 } catch (bad_alloc&) {
1355                         out_of_memory_ = true;
1356                         device_->stop();
1357                         buf_mem->unmap(mapinfo);
1358                         return Gst::FLOW_ERROR;
1359                 }
1360
1361                 buf_mem->unmap(mapinfo);
1362         }
1363
1364         return Gst::FLOW_OK;
1365 }
1366 #endif
1367
1368 void Session::feed_in_header()
1369 {
1370         // Nothing to do here for now
1371 }
1372
1373 void Session::feed_in_meta(shared_ptr<Meta> meta)
1374 {
1375         for (auto& entry : meta->config()) {
1376                 switch (entry.first->id()) {
1377                 case SR_CONF_SAMPLERATE:
1378                         cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1379                         break;
1380                 default:
1381                         qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1382                         break;
1383                 }
1384         }
1385
1386         signals_changed();
1387 }
1388
1389 void Session::feed_in_trigger()
1390 {
1391         // The channel containing most samples should be most accurate
1392         uint64_t sample_count = 0;
1393
1394         {
1395                 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1396                         assert(d);
1397                         uint64_t temp_count = 0;
1398
1399                         const vector< shared_ptr<pv::data::Segment> > segments =
1400                                 d->segments();
1401                         for (const shared_ptr<pv::data::Segment> &s : segments)
1402                                 temp_count += s->get_sample_count();
1403
1404                         if (temp_count > sample_count)
1405                                 sample_count = temp_count;
1406                 }
1407         }
1408
1409         uint32_t segment_id = 0;  // Default segment when no frames are used
1410
1411         // If a frame began, we'd ideally be able to use the highest segment ID for
1412         // the trigger. However, as new segments are only created when logic or
1413         // analog data comes in, this doesn't work if the trigger appears right
1414         // after the beginning of the frame, before any sample data.
1415         // For this reason, we use highest segment ID + 1 if no sample data came in
1416         // yet and the highest segment ID otherwise.
1417         if (frame_began_) {
1418                 segment_id = highest_segment_id_;
1419                 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1420                         segment_id++;
1421         }
1422
1423         // TODO Create timestamp from segment start time + segment's current sample count
1424         util::Timestamp timestamp = sample_count / get_samplerate();
1425         trigger_list_.emplace_back(segment_id, timestamp);
1426         trigger_event(segment_id, timestamp);
1427 }
1428
1429 void Session::feed_in_frame_begin()
1430 {
1431         frame_began_ = true;
1432 }
1433
1434 void Session::feed_in_frame_end()
1435 {
1436         if (!frame_began_)
1437                 return;
1438
1439         {
1440                 lock_guard<recursive_mutex> lock(data_mutex_);
1441
1442                 if (cur_logic_segment_)
1443                         cur_logic_segment_->set_complete();
1444
1445                 for (auto& entry : cur_analog_segments_) {
1446                         shared_ptr<data::AnalogSegment> segment = entry.second;
1447                         segment->set_complete();
1448                 }
1449
1450                 cur_logic_segment_.reset();
1451                 cur_analog_segments_.clear();
1452         }
1453
1454         frame_began_ = false;
1455
1456         signal_segment_completed();
1457 }
1458
1459 void Session::feed_in_logic(shared_ptr<sigrok::Logic> logic)
1460 {
1461         if (logic->data_length() == 0) {
1462                 qDebug() << "WARNING: Received logic packet with 0 samples.";
1463                 return;
1464         }
1465
1466         if (logic->unit_size() > 8)
1467                 throw QString(tr("Can't handle more than 64 logic channels."));
1468
1469         if (!cur_samplerate_)
1470                 try {
1471                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1472                 } catch (Error& e) {
1473                         // Do nothing
1474                 }
1475
1476         lock_guard<recursive_mutex> lock(data_mutex_);
1477
1478         if (!logic_data_) {
1479                 // The only reason logic_data_ would not have been created is
1480                 // if it was not possible to determine the signals when the
1481                 // device was created.
1482                 update_signals();
1483         }
1484
1485         if (!cur_logic_segment_) {
1486                 // This could be the first packet after a trigger
1487                 set_capture_state(Running);
1488
1489                 // Create a new data segment
1490                 cur_logic_segment_ = make_shared<data::LogicSegment>(
1491                         *logic_data_, logic_data_->get_segment_count(),
1492                         logic->unit_size(), cur_samplerate_);
1493                 logic_data_->push_segment(cur_logic_segment_);
1494
1495                 signal_new_segment();
1496         }
1497
1498         cur_logic_segment_->append_payload(logic);
1499
1500         data_received();
1501 }
1502
1503 void Session::feed_in_analog(shared_ptr<sigrok::Analog> analog)
1504 {
1505         if (analog->num_samples() == 0) {
1506                 qDebug() << "WARNING: Received analog packet with 0 samples.";
1507                 return;
1508         }
1509
1510         if (!cur_samplerate_)
1511                 try {
1512                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1513                 } catch (Error& e) {
1514                         // Do nothing
1515                 }
1516
1517         lock_guard<recursive_mutex> lock(data_mutex_);
1518
1519         const vector<shared_ptr<Channel>> channels = analog->channels();
1520         bool sweep_beginning = false;
1521
1522         unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1523         analog->get_data_as_float(data.get());
1524
1525         if (signalbases_.empty())
1526                 update_signals();
1527
1528         float *channel_data = data.get();
1529         for (auto& channel : channels) {
1530                 shared_ptr<data::AnalogSegment> segment;
1531
1532                 // Try to get the segment of the channel
1533                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1534                         iterator iter = cur_analog_segments_.find(channel);
1535                 if (iter != cur_analog_segments_.end())
1536                         segment = (*iter).second;
1537                 else {
1538                         // If no segment was found, this means we haven't
1539                         // created one yet. i.e. this is the first packet
1540                         // in the sweep containing this segment.
1541                         sweep_beginning = true;
1542
1543                         // Find the analog data associated with the channel
1544                         shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1545                         assert(base);
1546
1547                         shared_ptr<data::Analog> data(base->analog_data());
1548                         assert(data);
1549
1550                         // Create a segment, keep it in the maps of channels
1551                         segment = make_shared<data::AnalogSegment>(
1552                                 *data, data->get_segment_count(), cur_samplerate_);
1553                         cur_analog_segments_[channel] = segment;
1554
1555                         // Push the segment into the analog data.
1556                         data->push_segment(segment);
1557
1558                         signal_new_segment();
1559                 }
1560
1561                 assert(segment);
1562
1563                 // Append the samples in the segment
1564                 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1565                         channels.size());
1566         }
1567
1568         if (sweep_beginning) {
1569                 // This could be the first packet after a trigger
1570                 set_capture_state(Running);
1571         }
1572
1573         data_received();
1574 }
1575
1576 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1577         shared_ptr<Packet> packet)
1578 {
1579         (void)device;
1580
1581         assert(device);
1582         assert(device == device_->device());
1583         assert(packet);
1584
1585         switch (packet->type()->id()) {
1586         case SR_DF_HEADER:
1587                 feed_in_header();
1588                 break;
1589
1590         case SR_DF_META:
1591                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1592                 break;
1593
1594         case SR_DF_TRIGGER:
1595                 feed_in_trigger();
1596                 break;
1597
1598         case SR_DF_LOGIC:
1599                 try {
1600                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1601                 } catch (bad_alloc&) {
1602                         out_of_memory_ = true;
1603                         device_->stop();
1604                 }
1605                 break;
1606
1607         case SR_DF_ANALOG:
1608                 try {
1609                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1610                 } catch (bad_alloc&) {
1611                         out_of_memory_ = true;
1612                         device_->stop();
1613                 }
1614                 break;
1615
1616         case SR_DF_FRAME_BEGIN:
1617                 feed_in_frame_begin();
1618                 break;
1619
1620         case SR_DF_FRAME_END:
1621                 feed_in_frame_end();
1622                 break;
1623
1624         case SR_DF_END:
1625                 // Strictly speaking, this is performed when a frame end marker was
1626                 // received, so there's no point doing this again. However, not all
1627                 // devices use frames, and for those devices, we need to do it here.
1628                 {
1629                         lock_guard<recursive_mutex> lock(data_mutex_);
1630
1631                         if (cur_logic_segment_)
1632                                 cur_logic_segment_->set_complete();
1633
1634                         for (auto& entry : cur_analog_segments_) {
1635                                 shared_ptr<data::AnalogSegment> segment = entry.second;
1636                                 segment->set_complete();
1637                         }
1638
1639                         cur_logic_segment_.reset();
1640                         cur_analog_segments_.clear();
1641                 }
1642                 break;
1643
1644         default:
1645                 break;
1646         }
1647 }
1648
1649 void Session::on_data_saved()
1650 {
1651         data_saved_ = true;
1652 }
1653
1654 #ifdef ENABLE_DECODE
1655 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1656 {
1657         assert(decoders.size() > 0);
1658
1659         shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1660
1661         if (signal)
1662                 for (unsigned int i = 0; i < decoders.size(); i++) {
1663                         const srd_decoder* d = decoders[i];
1664                         signal->stack_decoder(d, !(i < decoders.size() - 1));
1665                 }
1666 }
1667 #endif
1668
1669 } // namespace pv