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