]> sigrok.org Git - pulseview.git/blob - pv/session.cpp
Switch segment storage from single vector to vector of arrays
[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 #ifdef _WIN32
21 // Windows: Avoid boost/thread namespace pollution (which includes windows.h).
22 #define NOGDI
23 #define NORESOURCE
24 #endif
25 #include <boost/thread/locks.hpp>
26 #include <boost/thread/shared_mutex.hpp>
27
28 #include <QFileInfo>
29
30 #include <cassert>
31 #include <mutex>
32 #include <stdexcept>
33
34 #include <sys/stat.h>
35
36 #include "session.hpp"
37 #include "devicemanager.hpp"
38
39 #include "data/analog.hpp"
40 #include "data/analogsegment.hpp"
41 #include "data/decoderstack.hpp"
42 #include "data/logic.hpp"
43 #include "data/logicsegment.hpp"
44 #include "data/signalbase.hpp"
45 #include "data/decode/decoder.hpp"
46
47 #include "devices/hardwaredevice.hpp"
48 #include "devices/inputfile.hpp"
49 #include "devices/sessionfile.hpp"
50
51 #include "toolbars/mainbar.hpp"
52
53 #include "view/analogsignal.hpp"
54 #include "view/decodetrace.hpp"
55 #include "view/logicsignal.hpp"
56 #include "view/signal.hpp"
57 #include "view/view.hpp"
58
59 #include <libsigrokcxx/libsigrokcxx.hpp>
60
61 #ifdef ENABLE_DECODE
62 #include <libsigrokdecode/libsigrokdecode.h>
63 #endif
64
65 using boost::shared_lock;
66 using boost::shared_mutex;
67 using boost::unique_lock;
68
69 using std::dynamic_pointer_cast;
70 using std::function;
71 using std::lock_guard;
72 using std::list;
73 using std::map;
74 using std::mutex;
75 using std::pair;
76 using std::recursive_mutex;
77 using std::set;
78 using std::shared_ptr;
79 using std::string;
80 using std::unordered_set;
81 using std::vector;
82
83 using sigrok::Analog;
84 using sigrok::Channel;
85 using sigrok::ChannelType;
86 using sigrok::ConfigKey;
87 using sigrok::DatafeedCallbackFunction;
88 using sigrok::Error;
89 using sigrok::Header;
90 using sigrok::InputFormat;
91 using sigrok::Logic;
92 using sigrok::Meta;
93 using sigrok::OutputFormat;
94 using sigrok::Packet;
95 using sigrok::PacketPayload;
96 using sigrok::Session;
97 using sigrok::SessionDevice;
98
99 using Glib::VariantBase;
100 using Glib::Variant;
101
102 namespace pv {
103 Session::Session(DeviceManager &device_manager, QString name) :
104         device_manager_(device_manager),
105         default_name_(name),
106         name_(name),
107         capture_state_(Stopped),
108         cur_samplerate_(0),
109         data_saved_(true)
110 {
111 }
112
113 Session::~Session()
114 {
115         // Stop and join to the thread
116         stop_capture();
117 }
118
119 DeviceManager& Session::device_manager()
120 {
121         return device_manager_;
122 }
123
124 const DeviceManager& Session::device_manager() const
125 {
126         return device_manager_;
127 }
128
129 shared_ptr<sigrok::Session> Session::session() const
130 {
131         if (!device_)
132                 return shared_ptr<sigrok::Session>();
133         return device_->session();
134 }
135
136 shared_ptr<devices::Device> Session::device() const
137 {
138         return device_;
139 }
140
141 QString Session::name() const
142 {
143         return name_;
144 }
145
146 void Session::set_name(QString name)
147 {
148         if (default_name_.isEmpty())
149                 default_name_ = name;
150
151         name_ = name;
152
153         name_changed();
154 }
155
156 const std::list< std::shared_ptr<views::ViewBase> > Session::views() const
157 {
158         return views_;
159 }
160
161 std::shared_ptr<views::ViewBase> Session::main_view() const
162 {
163         return main_view_;
164 }
165
166 void Session::set_main_bar(std::shared_ptr<pv::toolbars::MainBar> main_bar)
167 {
168         main_bar_ = main_bar;
169 }
170
171 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
172 {
173         return main_bar_;
174 }
175
176 bool Session::data_saved() const
177 {
178         return data_saved_;
179 }
180
181 void Session::save_settings(QSettings &settings) const
182 {
183         map<string, string> dev_info;
184         list<string> key_list;
185         int stacks = 0, views = 0;
186
187         if (device_) {
188                 shared_ptr<devices::HardwareDevice> hw_device =
189                         dynamic_pointer_cast< devices::HardwareDevice >(device_);
190
191                 if (hw_device) {
192                         settings.setValue("device_type", "hardware");
193                         settings.beginGroup("device");
194
195                         key_list.push_back("vendor");
196                         key_list.push_back("model");
197                         key_list.push_back("version");
198                         key_list.push_back("serial_num");
199                         key_list.push_back("connection_id");
200
201                         dev_info = device_manager_.get_device_info(device_);
202
203                         for (string key : key_list) {
204                                 if (dev_info.count(key))
205                                         settings.setValue(QString::fromUtf8(key.c_str()),
206                                                         QString::fromUtf8(dev_info.at(key).c_str()));
207                                 else
208                                         settings.remove(QString::fromUtf8(key.c_str()));
209                         }
210
211                         settings.endGroup();
212                 }
213
214                 shared_ptr<devices::SessionFile> sessionfile_device =
215                         dynamic_pointer_cast< devices::SessionFile >(device_);
216
217                 if (sessionfile_device) {
218                         settings.setValue("device_type", "sessionfile");
219                         settings.beginGroup("device");
220                         settings.setValue("filename", QString::fromStdString(
221                                 sessionfile_device->full_name()));
222                         settings.endGroup();
223                 }
224
225                 // Save channels and decoders
226                 for (shared_ptr<data::SignalBase> base : signalbases_) {
227 #ifdef ENABLE_DECODE
228                         if (base->is_decode_signal()) {
229                                 shared_ptr<pv::data::DecoderStack> decoder_stack =
230                                                 base->decoder_stack();
231                                 std::shared_ptr<data::decode::Decoder> top_decoder =
232                                                 decoder_stack->stack().front();
233
234                                 settings.beginGroup("decoder_stack" + QString::number(stacks++));
235                                 settings.setValue("id", top_decoder->decoder()->id);
236                                 settings.setValue("name", top_decoder->decoder()->name);
237                                 settings.endGroup();
238                         } else
239 #endif
240                         {
241                                 settings.beginGroup(base->internal_name());
242                                 base->save_settings(settings);
243                                 settings.endGroup();
244                         }
245                 }
246
247                 settings.setValue("decoder_stacks", stacks);
248
249                 // Save view states and their signal settings
250                 // Note: main_view must be saved as view0
251                 settings.beginGroup("view" + QString::number(views++));
252                 main_view_->save_settings(settings);
253                 settings.endGroup();
254
255                 for (shared_ptr<views::ViewBase> view : views_) {
256                         if (view != main_view_) {
257                                 settings.beginGroup("view" + QString::number(views++));
258                                 view->save_settings(settings);
259                                 settings.endGroup();
260                         }
261                 }
262
263                 settings.setValue("views", views);
264         }
265 }
266
267 void Session::restore_settings(QSettings &settings)
268 {
269         shared_ptr<devices::Device> device;
270
271         QString device_type = settings.value("device_type").toString();
272
273         if (device_type == "hardware") {
274                 map<string, string> dev_info;
275                 list<string> key_list;
276
277                 // Re-select last used device if possible but only if it's not demo
278                 settings.beginGroup("device");
279                 key_list.push_back("vendor");
280                 key_list.push_back("model");
281                 key_list.push_back("version");
282                 key_list.push_back("serial_num");
283                 key_list.push_back("connection_id");
284
285                 for (string key : key_list) {
286                         const QString k = QString::fromStdString(key);
287                         if (!settings.contains(k))
288                                 continue;
289
290                         const string value = settings.value(k).toString().toStdString();
291                         if (!value.empty())
292                                 dev_info.insert(std::make_pair(key, value));
293                 }
294
295                 if (dev_info.count("model") > 0)
296                         device = device_manager_.find_device_from_info(dev_info);
297
298                 if (device)
299                         set_device(device);
300
301                 settings.endGroup();
302         }
303
304         if (device_type == "sessionfile") {
305                 settings.beginGroup("device");
306                 QString filename = settings.value("filename").toString();
307                 settings.endGroup();
308
309                 if (QFileInfo(filename).isReadable()) {
310                         device = std::make_shared<devices::SessionFile>(device_manager_.context(),
311                                 filename.toStdString());
312                         set_device(device);
313
314                         // TODO Perform error handling
315                         start_capture([](QString infoMessage) { (void)infoMessage; });
316
317                         set_name(QFileInfo(filename).fileName());
318                 }
319         }
320
321         if (device) {
322                 // Restore channels
323                 for (shared_ptr<data::SignalBase> base : signalbases_) {
324                         settings.beginGroup(base->internal_name());
325                         base->restore_settings(settings);
326                         settings.endGroup();
327                 }
328
329                 // Restore decoders
330 #ifdef ENABLE_DECODE
331                 int stacks = settings.value("decoder_stacks").toInt();
332
333                 for (int i = 0; i < stacks; i++) {
334                         settings.beginGroup("decoder_stack" + QString::number(i++));
335
336                         QString id = settings.value("id").toString();
337                         add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
338
339                         settings.endGroup();
340                 }
341 #endif
342
343                 // Restore views
344                 int views = settings.value("views").toInt();
345
346                 for (int i = 0; i < views; i++) {
347                         settings.beginGroup("view" + QString::number(i));
348
349                         if (i > 0) {
350                                 views::ViewType type = (views::ViewType)settings.value("type").toInt();
351                                 add_view(name_, type, this);
352                                 views_.back()->restore_settings(settings);
353                         } else
354                                 main_view_->restore_settings(settings);
355
356                         settings.endGroup();
357                 }
358         }
359 }
360
361 void Session::select_device(shared_ptr<devices::Device> device)
362 {
363         try {
364                 if (device)
365                         set_device(device);
366                 else
367                         set_default_device();
368         } catch (const QString &e) {
369                 main_bar_->session_error(tr("Failed to Select Device"),
370                         tr("Failed to Select Device"));
371         }
372 }
373
374 void Session::set_device(shared_ptr<devices::Device> device)
375 {
376         assert(device);
377
378         // Ensure we are not capturing before setting the device
379         stop_capture();
380
381         if (device_)
382                 device_->close();
383
384         device_.reset();
385
386         // Revert name back to default name (e.g. "Untitled-1") as the data is gone
387         name_ = default_name_;
388         name_changed();
389
390         // Remove all stored data
391         for (std::shared_ptr<views::ViewBase> view : views_) {
392                 view->clear_signals();
393 #ifdef ENABLE_DECODE
394                 view->clear_decode_signals();
395 #endif
396         }
397         for (const shared_ptr<data::SignalData> d : all_signal_data_)
398                 d->clear();
399         all_signal_data_.clear();
400         signalbases_.clear();
401         cur_logic_segment_.reset();
402
403         for (auto entry : cur_analog_segments_) {
404                 shared_ptr<sigrok::Channel>(entry.first).reset();
405                 shared_ptr<data::AnalogSegment>(entry.second).reset();
406         }
407
408         logic_data_.reset();
409
410         signals_changed();
411
412         device_ = std::move(device);
413
414         try {
415                 device_->open();
416         } catch (const QString &e) {
417                 device_.reset();
418                 device_changed();
419                 throw;
420         }
421
422         device_->session()->add_datafeed_callback([=]
423                 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
424                         data_feed_in(device, packet);
425                 });
426
427         update_signals();
428         device_changed();
429 }
430
431 void Session::set_default_device()
432 {
433         const list< shared_ptr<devices::HardwareDevice> > &devices =
434                 device_manager_.devices();
435
436         if (devices.empty())
437                 return;
438
439         // Try and find the demo device and select that by default
440         const auto iter = std::find_if(devices.begin(), devices.end(),
441                 [] (const shared_ptr<devices::HardwareDevice> &d) {
442                         return d->hardware_device()->driver()->name() ==
443                         "demo"; });
444         set_device((iter == devices.end()) ? devices.front() : *iter);
445 }
446
447 void Session::load_init_file(const std::string &file_name,
448         const std::string &format)
449 {
450         shared_ptr<InputFormat> input_format;
451
452         if (!format.empty()) {
453                 const map<string, shared_ptr<InputFormat> > formats =
454                         device_manager_.context()->input_formats();
455                 const auto iter = find_if(formats.begin(), formats.end(),
456                         [&](const pair<string, shared_ptr<InputFormat> > f) {
457                                 return f.first == format; });
458                 if (iter == formats.end()) {
459                         main_bar_->session_error(tr("Error"),
460                                 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
461                         return;
462                 }
463
464                 input_format = (*iter).second;
465         }
466
467         load_file(QString::fromStdString(file_name), input_format);
468 }
469
470 void Session::load_file(QString file_name,
471         std::shared_ptr<sigrok::InputFormat> format,
472         const std::map<std::string, Glib::VariantBase> &options)
473 {
474         const QString errorMessage(
475                 QString("Failed to load file %1").arg(file_name));
476
477         try {
478                 if (format)
479                         set_device(shared_ptr<devices::Device>(
480                                 new devices::InputFile(
481                                         device_manager_.context(),
482                                         file_name.toStdString(),
483                                         format, options)));
484                 else
485                         set_device(shared_ptr<devices::Device>(
486                                 new devices::SessionFile(
487                                         device_manager_.context(),
488                                         file_name.toStdString())));
489         } catch (Error e) {
490                 main_bar_->session_error(tr("Failed to load ") + file_name, e.what());
491                 set_default_device();
492                 main_bar_->update_device_list();
493                 return;
494         }
495
496         main_bar_->update_device_list();
497
498         start_capture([&, errorMessage](QString infoMessage) {
499                 main_bar_->session_error(errorMessage, infoMessage); });
500
501         set_name(QFileInfo(file_name).fileName());
502 }
503
504 Session::capture_state Session::get_capture_state() const
505 {
506         lock_guard<mutex> lock(sampling_mutex_);
507         return capture_state_;
508 }
509
510 void Session::start_capture(function<void (const QString)> error_handler)
511 {
512         if (!device_) {
513                 error_handler(tr("No active device set, can't start acquisition."));
514                 return;
515         }
516
517         stop_capture();
518
519         // Check that at least one channel is enabled
520         const shared_ptr<sigrok::Device> sr_dev = device_->device();
521         if (sr_dev) {
522                 const auto channels = sr_dev->channels();
523                 if (!std::any_of(channels.begin(), channels.end(),
524                         [](shared_ptr<Channel> channel) {
525                                 return channel->enabled(); })) {
526                         error_handler(tr("No channels enabled."));
527                         return;
528                 }
529         }
530
531         // Clear signal data
532         for (const shared_ptr<data::SignalData> d : all_signal_data_)
533                 d->clear();
534
535         // Revert name back to default name (e.g. "Untitled-1") as the data is gone
536         name_ = default_name_;
537         name_changed();
538
539         // Begin the session
540         sampling_thread_ = std::thread(
541                 &Session::sample_thread_proc, this, error_handler);
542 }
543
544 void Session::stop_capture()
545 {
546         if (get_capture_state() != Stopped)
547                 device_->stop();
548
549         // Check that sampling stopped
550         if (sampling_thread_.joinable())
551                 sampling_thread_.join();
552 }
553
554 void Session::register_view(std::shared_ptr<views::ViewBase> view)
555 {
556         if (views_.empty()) {
557                 main_view_ = view;
558         }
559
560         views_.push_back(view);
561
562         update_signals();
563 }
564
565 void Session::deregister_view(std::shared_ptr<views::ViewBase> view)
566 {
567         views_.remove_if([&](std::shared_ptr<views::ViewBase> v) {
568                 return v == view; });
569
570         if (views_.empty()) {
571                 main_view_.reset();
572
573                 // Without a view there can be no main bar
574                 main_bar_.reset();
575         }
576 }
577
578 bool Session::has_view(std::shared_ptr<views::ViewBase> view)
579 {
580         for (std::shared_ptr<views::ViewBase> v : views_)
581                 if (v == view)
582                         return true;
583
584         return false;
585 }
586
587 double Session::get_samplerate() const
588 {
589         double samplerate = 0.0;
590
591         for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
592                 assert(d);
593                 const vector< shared_ptr<pv::data::Segment> > segments =
594                         d->segments();
595                 for (const shared_ptr<pv::data::Segment> &s : segments)
596                         samplerate = std::max(samplerate, s->samplerate());
597         }
598         // If there is no sample rate given we use samples as unit
599         if (samplerate == 0.0)
600                 samplerate = 1.0;
601
602         return samplerate;
603 }
604
605 const std::unordered_set< std::shared_ptr<data::SignalBase> >
606         Session::signalbases() const
607 {
608         return signalbases_;
609 }
610
611 #ifdef ENABLE_DECODE
612 bool Session::add_decoder(srd_decoder *const dec)
613 {
614         map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
615         shared_ptr<data::DecoderStack> decoder_stack;
616
617         try {
618                 // Create the decoder
619                 decoder_stack = shared_ptr<data::DecoderStack>(
620                         new data::DecoderStack(*this, dec));
621
622                 // Make a list of all the channels
623                 std::vector<const srd_channel*> all_channels;
624                 for (const GSList *i = dec->channels; i; i = i->next)
625                         all_channels.push_back((const srd_channel*)i->data);
626                 for (const GSList *i = dec->opt_channels; i; i = i->next)
627                         all_channels.push_back((const srd_channel*)i->data);
628
629                 // Auto select the initial channels
630                 for (const srd_channel *pdch : all_channels)
631                         for (shared_ptr<data::SignalBase> b : signalbases_) {
632                                 if (b->type() == ChannelType::LOGIC) {
633                                         if (QString::fromUtf8(pdch->name).toLower().
634                                                 contains(b->name().toLower()))
635                                                 channels[pdch] = b;
636                                 }
637                         }
638
639                 assert(decoder_stack);
640                 assert(!decoder_stack->stack().empty());
641                 assert(decoder_stack->stack().front());
642                 decoder_stack->stack().front()->set_channels(channels);
643
644                 // Create the decode signal
645                 shared_ptr<data::SignalBase> signalbase =
646                         shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
647
648                 signalbase->set_decoder_stack(decoder_stack);
649                 signalbases_.insert(signalbase);
650
651                 for (std::shared_ptr<views::ViewBase> view : views_)
652                         view->add_decode_signal(signalbase);
653         } catch (std::runtime_error e) {
654                 return false;
655         }
656
657         signals_changed();
658
659         // Do an initial decode
660         decoder_stack->begin_decode();
661
662         return true;
663 }
664
665 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
666 {
667         signalbases_.erase(signalbase);
668
669         for (std::shared_ptr<views::ViewBase> view : views_)
670                 view->remove_decode_signal(signalbase);
671
672         signals_changed();
673 }
674 #endif
675
676 void Session::set_capture_state(capture_state state)
677 {
678         bool changed;
679
680         {
681                 lock_guard<mutex> lock(sampling_mutex_);
682                 changed = capture_state_ != state;
683                 capture_state_ = state;
684         }
685
686         if (changed)
687                 capture_state_changed(state);
688 }
689
690 void Session::update_signals()
691 {
692         if (!device_) {
693                 signalbases_.clear();
694                 logic_data_.reset();
695                 for (std::shared_ptr<views::ViewBase> view : views_) {
696                         view->clear_signals();
697 #ifdef ENABLE_DECODE
698                         view->clear_decode_signals();
699 #endif
700                 }
701                 return;
702         }
703
704         lock_guard<recursive_mutex> lock(data_mutex_);
705
706         const shared_ptr<sigrok::Device> sr_dev = device_->device();
707         if (!sr_dev) {
708                 signalbases_.clear();
709                 logic_data_.reset();
710                 for (std::shared_ptr<views::ViewBase> view : views_) {
711                         view->clear_signals();
712 #ifdef ENABLE_DECODE
713                         view->clear_decode_signals();
714 #endif
715                 }
716                 return;
717         }
718
719         // Detect what data types we will receive
720         auto channels = sr_dev->channels();
721         unsigned int logic_channel_count = std::count_if(
722                 channels.begin(), channels.end(),
723                 [] (shared_ptr<Channel> channel) {
724                         return channel->type() == ChannelType::LOGIC; });
725
726         // Create data containers for the logic data segments
727         {
728                 lock_guard<recursive_mutex> data_lock(data_mutex_);
729
730                 if (logic_channel_count == 0) {
731                         logic_data_.reset();
732                 } else if (!logic_data_ ||
733                         logic_data_->num_channels() != logic_channel_count) {
734                         logic_data_.reset(new data::Logic(
735                                 logic_channel_count));
736                         assert(logic_data_);
737                 }
738         }
739
740         // Make the signals list
741         for (std::shared_ptr<views::ViewBase> viewbase : views_) {
742                 views::TraceView::View *trace_view =
743                         qobject_cast<views::TraceView::View*>(viewbase.get());
744
745                 if (trace_view) {
746                         unordered_set< shared_ptr<views::TraceView::Signal> >
747                                 prev_sigs(trace_view->signals());
748                         trace_view->clear_signals();
749
750                         for (auto channel : sr_dev->channels()) {
751                                 shared_ptr<data::SignalBase> signalbase;
752                                 shared_ptr<views::TraceView::Signal> signal;
753
754                                 // Find the channel in the old signals
755                                 const auto iter = std::find_if(
756                                         prev_sigs.cbegin(), prev_sigs.cend(),
757                                         [&](const shared_ptr<views::TraceView::Signal> &s) {
758                                                 return s->base()->channel() == channel;
759                                         });
760                                 if (iter != prev_sigs.end()) {
761                                         // Copy the signal from the old set to the new
762                                         signal = *iter;
763                                         trace_view->add_signal(signal);
764                                 } else {
765                                         // Find the signalbase for this channel if possible
766                                         signalbase.reset();
767                                         for (const shared_ptr<data::SignalBase> b : signalbases_)
768                                                 if (b->channel() == channel)
769                                                         signalbase = b;
770
771                                         switch(channel->type()->id()) {
772                                         case SR_CHANNEL_LOGIC:
773                                                 if (!signalbase) {
774                                                         signalbase = shared_ptr<data::SignalBase>(
775                                                                 new data::SignalBase(channel));
776                                                         signalbases_.insert(signalbase);
777
778                                                         all_signal_data_.insert(logic_data_);
779                                                         signalbase->set_data(logic_data_);
780                                                 }
781
782                                                 signal = shared_ptr<views::TraceView::Signal>(
783                                                         new views::TraceView::LogicSignal(*this,
784                                                                 device_, signalbase));
785                                                 trace_view->add_signal(signal);
786                                                 break;
787
788                                         case SR_CHANNEL_ANALOG:
789                                         {
790                                                 if (!signalbase) {
791                                                         signalbase = shared_ptr<data::SignalBase>(
792                                                                 new data::SignalBase(channel));
793                                                         signalbases_.insert(signalbase);
794
795                                                         shared_ptr<data::Analog> data(new data::Analog());
796                                                         all_signal_data_.insert(data);
797                                                         signalbase->set_data(data);
798                                                 }
799
800                                                 signal = shared_ptr<views::TraceView::Signal>(
801                                                         new views::TraceView::AnalogSignal(
802                                                                 *this, signalbase));
803                                                 trace_view->add_signal(signal);
804                                                 break;
805                                         }
806
807                                         default:
808                                                 assert(0);
809                                                 break;
810                                         }
811                                 }
812                         }
813                 }
814         }
815
816         signals_changed();
817 }
818
819 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
820         shared_ptr<sigrok::Channel> channel) const
821 {
822         for (shared_ptr<data::SignalBase> sig : signalbases_) {
823                 assert(sig);
824                 if (sig->channel() == channel)
825                         return sig;
826         }
827         return shared_ptr<data::SignalBase>();
828 }
829
830 void Session::sample_thread_proc(function<void (const QString)> error_handler)
831 {
832         assert(error_handler);
833
834         if (!device_)
835                 return;
836
837         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
838
839         out_of_memory_ = false;
840
841         try {
842                 device_->start();
843         } catch (Error e) {
844                 error_handler(e.what());
845                 return;
846         }
847
848         set_capture_state(device_->session()->trigger() ?
849                 AwaitingTrigger : Running);
850
851         device_->run();
852         set_capture_state(Stopped);
853
854         // Confirm that SR_DF_END was received
855         if (cur_logic_segment_) {
856                 qDebug("SR_DF_END was not received.");
857                 assert(0);
858         }
859
860         // We now have unsaved data unless we just "captured" from a file
861         shared_ptr<devices::File> file_device =
862                 dynamic_pointer_cast<devices::File>(device_);
863
864         if (!file_device)
865                 data_saved_ = false;
866
867         if (out_of_memory_)
868                 error_handler(tr("Out of memory, acquisition stopped."));
869 }
870
871 void Session::feed_in_header()
872 {
873         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
874 }
875
876 void Session::feed_in_meta(shared_ptr<Meta> meta)
877 {
878         for (auto entry : meta->config()) {
879                 switch (entry.first->id()) {
880                 case SR_CONF_SAMPLERATE:
881                         // We can't rely on the header to always contain the sample rate,
882                         // so in case it's supplied via a meta packet, we use it.
883                         if (!cur_samplerate_)
884                                 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
885
886                         /// @todo handle samplerate changes
887                         break;
888                 default:
889                         // Unknown metadata is not an error.
890                         break;
891                 }
892         }
893
894         signals_changed();
895 }
896
897 void Session::feed_in_trigger()
898 {
899         // The channel containing most samples should be most accurate
900         uint64_t sample_count = 0;
901
902         {
903                 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
904                         assert(d);
905                         uint64_t temp_count = 0;
906
907                         const vector< shared_ptr<pv::data::Segment> > segments =
908                                 d->segments();
909                         for (const shared_ptr<pv::data::Segment> &s : segments)
910                                 temp_count += s->get_sample_count();
911
912                         if (temp_count > sample_count)
913                                 sample_count = temp_count;
914                 }
915         }
916
917         trigger_event(sample_count / get_samplerate());
918 }
919
920 void Session::feed_in_frame_begin()
921 {
922         if (cur_logic_segment_ || !cur_analog_segments_.empty())
923                 frame_began();
924 }
925
926 void Session::feed_in_logic(shared_ptr<Logic> logic)
927 {
928         lock_guard<recursive_mutex> lock(data_mutex_);
929
930         if (!logic_data_) {
931                 // The only reason logic_data_ would not have been created is
932                 // if it was not possible to determine the signals when the
933                 // device was created.
934                 update_signals();
935         }
936
937         if (!cur_logic_segment_) {
938                 // This could be the first packet after a trigger
939                 set_capture_state(Running);
940
941                 // Create a new data segment
942                 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
943                         new data::LogicSegment(logic, cur_samplerate_));
944                 logic_data_->push_segment(cur_logic_segment_);
945
946                 // @todo Putting this here means that only listeners querying
947                 // for logic will be notified. Currently the only user of
948                 // frame_began is DecoderStack, but in future we need to signal
949                 // this after both analog and logic sweeps have begun.
950                 frame_began();
951         } else {
952                 // Append to the existing data segment
953                 cur_logic_segment_->append_payload(logic);
954         }
955
956         data_received();
957 }
958
959 void Session::feed_in_analog(shared_ptr<Analog> analog)
960 {
961         lock_guard<recursive_mutex> lock(data_mutex_);
962
963         const vector<shared_ptr<Channel>> channels = analog->channels();
964         const unsigned int channel_count = channels.size();
965         const size_t sample_count = analog->num_samples() / channel_count;
966         const float *data = static_cast<const float *>(analog->data_pointer());
967         bool sweep_beginning = false;
968
969         if (signalbases_.empty())
970                 update_signals();
971
972         for (auto channel : channels) {
973                 shared_ptr<data::AnalogSegment> segment;
974
975                 // Try to get the segment of the channel
976                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
977                         iterator iter = cur_analog_segments_.find(channel);
978                 if (iter != cur_analog_segments_.end())
979                         segment = (*iter).second;
980                 else {
981                         // If no segment was found, this means we haven't
982                         // created one yet. i.e. this is the first packet
983                         // in the sweep containing this segment.
984                         sweep_beginning = true;
985
986                         // Create a segment, keep it in the maps of channels
987                         segment = shared_ptr<data::AnalogSegment>(
988                                 new data::AnalogSegment(cur_samplerate_));
989                         cur_analog_segments_[channel] = segment;
990
991                         // Find the analog data associated with the channel
992                         shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
993                         assert(base);
994
995                         shared_ptr<data::Analog> data(base->analog_data());
996                         assert(data);
997
998                         // Push the segment into the analog data.
999                         data->push_segment(segment);
1000                 }
1001
1002                 assert(segment);
1003
1004                 // Append the samples in the segment
1005                 segment->append_interleaved_samples(data++, sample_count,
1006                         channel_count);
1007         }
1008
1009         if (sweep_beginning) {
1010                 // This could be the first packet after a trigger
1011                 set_capture_state(Running);
1012         }
1013
1014         data_received();
1015 }
1016
1017 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1018         shared_ptr<Packet> packet)
1019 {
1020         (void)device;
1021
1022         assert(device);
1023         assert(device == device_->device());
1024         assert(packet);
1025
1026         switch (packet->type()->id()) {
1027         case SR_DF_HEADER:
1028                 feed_in_header();
1029                 break;
1030
1031         case SR_DF_META:
1032                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1033                 break;
1034
1035         case SR_DF_TRIGGER:
1036                 feed_in_trigger();
1037                 break;
1038
1039         case SR_DF_FRAME_BEGIN:
1040                 feed_in_frame_begin();
1041                 break;
1042
1043         case SR_DF_LOGIC:
1044                 try {
1045                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1046                 } catch (std::bad_alloc) {
1047                         out_of_memory_ = true;
1048                         device_->stop();
1049                 }
1050                 break;
1051
1052         case SR_DF_ANALOG:
1053                 try {
1054                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1055                 } catch (std::bad_alloc) {
1056                         out_of_memory_ = true;
1057                         device_->stop();
1058                 }
1059                 break;
1060
1061         case SR_DF_END:
1062         {
1063                 {
1064                         lock_guard<recursive_mutex> lock(data_mutex_);
1065                         cur_logic_segment_.reset();
1066                         cur_analog_segments_.clear();
1067                 }
1068                 frame_ended();
1069                 break;
1070         }
1071         default:
1072                 break;
1073         }
1074 }
1075
1076 void Session::on_data_saved()
1077 {
1078         data_saved_ = true;
1079 }
1080
1081 } // namespace pv