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