]> sigrok.org Git - pulseview.git/blob - pv/data/signalbase.cpp
Implement MathSignal
[pulseview.git] / pv / data / signalbase.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5  * Copyright (C) 2016 Soeren Apel <soeren@apelpie.net>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "analog.hpp"
22 #include "analogsegment.hpp"
23 #include "decode/row.hpp"
24 #include "logic.hpp"
25 #include "logicsegment.hpp"
26 #include "signalbase.hpp"
27 #include "signaldata.hpp"
28
29 #include <QDebug>
30
31 #include <pv/binding/decoder.hpp>
32 #include <pv/session.hpp>
33
34 using std::dynamic_pointer_cast;
35 using std::make_shared;
36 using std::out_of_range;
37 using std::shared_ptr;
38 using std::tie;
39 using std::unique_lock;
40
41 namespace pv {
42 namespace data {
43
44 const int SignalBase::ColorBGAlpha = 8 * 256 / 100;
45 const uint64_t SignalBase::ConversionBlockSize = 4096;
46 const uint32_t SignalBase::ConversionDelay = 1000;  // 1 second
47
48
49 SignalGroup::SignalGroup(const QString& name)
50 {
51         name_ = name;
52 }
53
54 void SignalGroup::append_signal(shared_ptr<SignalBase> signal)
55 {
56         if (!signal)
57                 return;
58
59         signals_.push_back(signal);
60         signal->set_group(this);
61 }
62
63 void SignalGroup::remove_signal(shared_ptr<SignalBase> signal)
64 {
65         if (!signal)
66                 return;
67
68         signals_.erase(std::remove_if(signals_.begin(), signals_.end(),
69                 [&](shared_ptr<SignalBase> s) { return s == signal; }),
70                 signals_.end());
71 }
72
73 deque<shared_ptr<SignalBase>> SignalGroup::signals() const
74 {
75         return signals_;
76 }
77
78 void SignalGroup::clear()
79 {
80         for (shared_ptr<SignalBase> sb : signals_)
81                 sb->set_group(nullptr);
82
83         signals_.clear();
84 }
85
86 const QString SignalGroup::name() const
87 {
88         return name_;
89 }
90
91
92 SignalBase::SignalBase(shared_ptr<sigrok::Channel> channel, ChannelType channel_type) :
93         channel_(channel),
94         channel_type_(channel_type),
95         group_(nullptr),
96         conversion_type_(NoConversion),
97         min_value_(0),
98         max_value_(0)
99 {
100         if (channel_) {
101                 internal_name_ = QString::fromStdString(channel_->name());
102                 index_ = channel_->index();
103         }
104
105         connect(&delayed_conversion_starter_, SIGNAL(timeout()),
106                 this, SLOT(on_delayed_conversion_start()));
107         delayed_conversion_starter_.setSingleShot(true);
108         delayed_conversion_starter_.setInterval(ConversionDelay);
109 }
110
111 SignalBase::~SignalBase()
112 {
113         stop_conversion();
114 }
115
116 shared_ptr<sigrok::Channel> SignalBase::channel() const
117 {
118         return channel_;
119 }
120
121 bool SignalBase::is_generated() const
122 {
123         // Only signals associated with a device have a corresponding sigrok channel
124         return channel_ == nullptr;
125 }
126
127 bool SignalBase::enabled() const
128 {
129         return (channel_) ? channel_->enabled() : true;
130 }
131
132 void SignalBase::set_enabled(bool value)
133 {
134         if (channel_) {
135                 channel_->set_enabled(value);
136                 enabled_changed(value);
137         }
138 }
139
140 SignalBase::ChannelType SignalBase::type() const
141 {
142         return channel_type_;
143 }
144
145 unsigned int SignalBase::index() const
146 {
147         return index_;
148 }
149
150 void SignalBase::set_index(unsigned int index)
151 {
152         index_ = index;
153 }
154
155 unsigned int SignalBase::logic_bit_index() const
156 {
157         if (channel_type_ == LogicChannel)
158                 return index_;
159         else
160                 return 0;
161 }
162
163 void SignalBase::set_group(SignalGroup* group)
164 {
165         group_ = group;
166 }
167
168 SignalGroup* SignalBase::group() const
169 {
170         return group_;
171 }
172
173 QString SignalBase::name() const
174 {
175         return (channel_) ? QString::fromStdString(channel_->name()) : name_;
176 }
177
178 QString SignalBase::internal_name() const
179 {
180         return internal_name_;
181 }
182
183 void SignalBase::set_internal_name(QString internal_name)
184 {
185         internal_name_ = internal_name;
186 }
187
188 QString SignalBase::display_name() const
189 {
190         if ((name() != internal_name_) && (!internal_name_.isEmpty()))
191                 return name() + " (" + internal_name_ + ")";
192         else
193                 return name();
194 }
195
196 void SignalBase::set_name(QString name)
197 {
198         if (channel_)
199                 channel_->set_name(name.toUtf8().constData());
200
201         name_ = name;
202
203         name_changed(name);
204 }
205
206 QColor SignalBase::color() const
207 {
208         return color_;
209 }
210
211 void SignalBase::set_color(QColor color)
212 {
213         color_ = color;
214
215         bgcolor_ = color;
216         bgcolor_.setAlpha(ColorBGAlpha);
217
218         color_changed(color);
219 }
220
221 QColor SignalBase::bgcolor() const
222 {
223         return bgcolor_;
224 }
225
226 void SignalBase::set_data(shared_ptr<pv::data::SignalData> data)
227 {
228         if (data_) {
229                 disconnect(data.get(), SIGNAL(samples_cleared()),
230                         this, SLOT(on_samples_cleared()));
231                 disconnect(data.get(), SIGNAL(samples_added(shared_ptr<Segment>, uint64_t, uint64_t)),
232                         this, SLOT(on_samples_added(shared_ptr<Segment>, uint64_t, uint64_t)));
233
234                 shared_ptr<Analog> analog = analog_data();
235                 if (analog)
236                         disconnect(analog.get(), SIGNAL(min_max_changed(float, float)),
237                                 this, SLOT(on_min_max_changed(float, float)));
238         }
239
240         data_ = data;
241
242         if (data_) {
243                 connect(data.get(), SIGNAL(samples_cleared()),
244                         this, SLOT(on_samples_cleared()));
245                 connect(data.get(), SIGNAL(samples_added(SharedPtrToSegment, uint64_t, uint64_t)),
246                         this, SLOT(on_samples_added(SharedPtrToSegment, uint64_t, uint64_t)));
247
248                 shared_ptr<Analog> analog = analog_data();
249                 if (analog)
250                         connect(analog.get(), SIGNAL(min_max_changed(float, float)),
251                                 this, SLOT(on_min_max_changed(float, float)));
252         }
253 }
254
255 void SignalBase::clear_sample_data()
256 {
257         if (analog_data())
258                 analog_data()->clear();
259
260         if (logic_data())
261                 logic_data()->clear();
262 }
263
264 shared_ptr<data::Analog> SignalBase::analog_data() const
265 {
266         return dynamic_pointer_cast<Analog>(data_);
267 }
268
269 shared_ptr<data::Logic> SignalBase::logic_data() const
270 {
271         shared_ptr<Logic> result = dynamic_pointer_cast<Logic>(data_);
272
273         if (((conversion_type_ == A2LConversionByThreshold) ||
274                 (conversion_type_ == A2LConversionBySchmittTrigger)))
275                 result = dynamic_pointer_cast<Logic>(converted_data_);
276
277         return result;
278 }
279
280 bool SignalBase::segment_is_complete(uint32_t segment_id) const
281 {
282         bool result = true;
283
284         shared_ptr<Analog> adata = analog_data();
285         if (adata)
286         {
287                 auto segments = adata->analog_segments();
288                 try {
289                         result = segments.at(segment_id)->is_complete();
290                 } catch (out_of_range&) {
291                         // Do nothing
292                 }
293         } else {
294                 shared_ptr<Logic> ldata = logic_data();
295                 if (ldata) {
296                         shared_ptr<Logic> data = dynamic_pointer_cast<Logic>(data_);
297                         auto segments = data->logic_segments();
298                         try {
299                                 result = segments.at(segment_id)->is_complete();
300                         } catch (out_of_range&) {
301                                 // Do nothing
302                         }
303                 }
304         }
305
306         return result;
307 }
308
309 bool SignalBase::has_samples() const
310 {
311         bool result = false;
312
313         shared_ptr<Analog> adata = analog_data();
314         if (adata)
315         {
316                 auto segments = adata->analog_segments();
317                 if ((segments.size() > 0) && (segments.front()->get_sample_count() > 0))
318                         result = true;
319         } else {
320                 shared_ptr<Logic> ldata = logic_data();
321                 if (ldata) {
322                         auto segments = ldata->logic_segments();
323                         if ((segments.size() > 0) && (segments.front()->get_sample_count() > 0))
324                                 result = true;
325                 }
326         }
327
328         return result;
329 }
330
331 double SignalBase::get_samplerate() const
332 {
333         shared_ptr<Analog> adata = analog_data();
334         if (adata)
335                 return adata->get_samplerate();
336         else {
337                 shared_ptr<Logic> ldata = logic_data();
338                 if (ldata)
339                         return ldata->get_samplerate();
340         }
341
342         // Default samplerate is 1 Hz
343         return 1.0;
344 }
345
346 SignalBase::ConversionType SignalBase::get_conversion_type() const
347 {
348         return conversion_type_;
349 }
350
351 void SignalBase::set_conversion_type(ConversionType t)
352 {
353         if (conversion_type_ != NoConversion) {
354                 stop_conversion();
355
356                 // Discard converted data
357                 converted_data_.reset();
358                 samples_cleared();
359         }
360
361         conversion_type_ = t;
362
363         // Re-create an empty container
364         // so that the signal is recognized as providing logic data
365         // and thus can be assigned to a decoder
366         if (conversion_is_a2l())
367                 if (!converted_data_)
368                         converted_data_ = make_shared<Logic>(1);  // Contains only one channel
369
370         start_conversion();
371
372         conversion_type_changed(t);
373 }
374
375 map<QString, QVariant> SignalBase::get_conversion_options() const
376 {
377         return conversion_options_;
378 }
379
380 bool SignalBase::set_conversion_option(QString key, QVariant value)
381 {
382         QVariant old_value;
383
384         auto key_iter = conversion_options_.find(key);
385         if (key_iter != conversion_options_.end())
386                 old_value = key_iter->second;
387
388         conversion_options_[key] = value;
389
390         return (value != old_value);
391 }
392
393 vector<double> SignalBase::get_conversion_thresholds(const ConversionType t,
394         const bool always_custom) const
395 {
396         vector<double> result;
397         ConversionType conv_type = t;
398         ConversionPreset preset;
399
400         // Use currently active conversion if no conversion type was supplied
401         if (conv_type == NoConversion)
402                 conv_type = conversion_type_;
403
404         if (always_custom)
405                 preset = NoPreset;
406         else
407                 preset = get_current_conversion_preset();
408
409         if (conv_type == A2LConversionByThreshold) {
410                 double thr = 0;
411
412                 if (preset == NoPreset) {
413                         auto thr_iter = conversion_options_.find("threshold_value");
414                         if (thr_iter != conversion_options_.end())
415                                 thr = (thr_iter->second).toDouble();
416                 }
417
418                 if (preset == DynamicPreset)
419                         thr = (min_value_ + max_value_) * 0.5;  // middle between min and max
420
421                 if ((int)preset == 1) thr = 0.9;
422                 if ((int)preset == 2) thr = 1.8;
423                 if ((int)preset == 3) thr = 2.5;
424                 if ((int)preset == 4) thr = 1.5;
425
426                 result.push_back(thr);
427         }
428
429         if (conv_type == A2LConversionBySchmittTrigger) {
430                 double thr_lo = 0, thr_hi = 0;
431
432                 if (preset == NoPreset) {
433                         auto thr_lo_iter = conversion_options_.find("threshold_value_low");
434                         if (thr_lo_iter != conversion_options_.end())
435                                 thr_lo = (thr_lo_iter->second).toDouble();
436
437                         auto thr_hi_iter = conversion_options_.find("threshold_value_high");
438                         if (thr_hi_iter != conversion_options_.end())
439                                 thr_hi = (thr_hi_iter->second).toDouble();
440                 }
441
442                 if (preset == DynamicPreset) {
443                         const double amplitude = max_value_ - min_value_;
444                         const double center = min_value_ + (amplitude / 2);
445                         thr_lo = center - (amplitude * 0.15);  // 15% margin
446                         thr_hi = center + (amplitude * 0.15);  // 15% margin
447                 }
448
449                 if ((int)preset == 1) { thr_lo = 0.3; thr_hi = 1.2; }
450                 if ((int)preset == 2) { thr_lo = 0.7; thr_hi = 2.5; }
451                 if ((int)preset == 3) { thr_lo = 1.3; thr_hi = 3.7; }
452                 if ((int)preset == 4) { thr_lo = 0.8; thr_hi = 2.0; }
453
454                 result.push_back(thr_lo);
455                 result.push_back(thr_hi);
456         }
457
458         return result;
459 }
460
461 vector< pair<QString, int> > SignalBase::get_conversion_presets() const
462 {
463         vector< pair<QString, int> > presets;
464
465         if (conversion_type_ == A2LConversionByThreshold) {
466                 // Source: http://www.interfacebus.com/voltage_threshold.html
467                 presets.emplace_back(tr("Signal average"), 0);
468                 presets.emplace_back(tr("0.9V (for 1.8V CMOS)"), 1);
469                 presets.emplace_back(tr("1.8V (for 3.3V CMOS)"), 2);
470                 presets.emplace_back(tr("2.5V (for 5.0V CMOS)"), 3);
471                 presets.emplace_back(tr("1.5V (for TTL)"), 4);
472         }
473
474         if (conversion_type_ == A2LConversionBySchmittTrigger) {
475                 // Source: http://www.interfacebus.com/voltage_threshold.html
476                 presets.emplace_back(tr("Signal average +/- 15%"), 0);
477                 presets.emplace_back(tr("0.3V/1.2V (for 1.8V CMOS)"), 1);
478                 presets.emplace_back(tr("0.7V/2.5V (for 3.3V CMOS)"), 2);
479                 presets.emplace_back(tr("1.3V/3.7V (for 5.0V CMOS)"), 3);
480                 presets.emplace_back(tr("0.8V/2.0V (for TTL)"), 4);
481         }
482
483         return presets;
484 }
485
486 SignalBase::ConversionPreset SignalBase::get_current_conversion_preset() const
487 {
488         auto preset = conversion_options_.find("preset");
489         if (preset != conversion_options_.end())
490                 return (ConversionPreset)((preset->second).toInt());
491
492         return DynamicPreset;
493 }
494
495 void SignalBase::set_conversion_preset(ConversionPreset id)
496 {
497         conversion_options_["preset"] = (int)id;
498 }
499
500 #ifdef ENABLE_DECODE
501 bool SignalBase::is_decode_signal() const
502 {
503         return (channel_type_ == DecodeChannel);
504 }
505 #endif
506
507 void SignalBase::save_settings(QSettings &settings) const
508 {
509         settings.setValue("name", name());
510         settings.setValue("enabled", enabled());
511         settings.setValue("color", color().rgba());
512         settings.setValue("conversion_type", (int)conversion_type_);
513
514         settings.setValue("conv_options", (int)(conversion_options_.size()));
515         int i = 0;
516         for (auto& kvp : conversion_options_) {
517                 settings.setValue(QString("conv_option%1_key").arg(i), kvp.first);
518                 settings.setValue(QString("conv_option%1_value").arg(i), kvp.second);
519                 i++;
520         }
521 }
522
523 void SignalBase::restore_settings(QSettings &settings)
524 {
525         if (settings.contains("name"))
526                 set_name(settings.value("name").toString());
527
528         if (settings.contains("enabled"))
529                 set_enabled(settings.value("enabled").toBool());
530
531         if (settings.contains("color")) {
532                 QVariant value = settings.value("color");
533
534                 // Workaround for Qt QColor serialization bug on OSX
535                 if ((QMetaType::Type)(value.type()) == QMetaType::QColor)
536                         set_color(value.value<QColor>());
537                 else
538                         set_color(QColor::fromRgba(value.value<uint32_t>()));
539
540                 // A color with an alpha value of 0 makes the signal marker invisible
541                 if (color() == QColor(0, 0, 0, 0))
542                         set_color(Qt::gray);
543         }
544
545         if (settings.contains("conversion_type"))
546                 set_conversion_type((ConversionType)settings.value("conversion_type").toInt());
547
548         int conv_options = 0;
549         if (settings.contains("conv_options"))
550                 conv_options = settings.value("conv_options").toInt();
551
552         if (conv_options)
553                 for (int i = 0; i < conv_options; i++) {
554                         const QString key_id = QString("conv_option%1_key").arg(i);
555                         const QString value_id = QString("conv_option%1_value").arg(i);
556
557                         if (settings.contains(key_id) && settings.contains(value_id))
558                                 conversion_options_[settings.value(key_id).toString()] =
559                                         settings.value(value_id);
560                 }
561 }
562
563 bool SignalBase::conversion_is_a2l() const
564 {
565         return (((conversion_type_ == A2LConversionByThreshold) ||
566                 (conversion_type_ == A2LConversionBySchmittTrigger)));
567 }
568
569 void SignalBase::convert_single_segment_range(AnalogSegment *asegment,
570         LogicSegment *lsegment, uint64_t start_sample, uint64_t end_sample)
571 {
572         if (end_sample > start_sample) {
573                 tie(min_value_, max_value_) = asegment->get_min_max();
574
575                 // Create sigrok::Analog instance
576                 float *asamples = new float[ConversionBlockSize];
577                 uint8_t *lsamples = new uint8_t[ConversionBlockSize];
578
579                 vector<shared_ptr<sigrok::Channel> > channels;
580                 if (channel_)
581                         channels.push_back(channel_);
582
583                 vector<const sigrok::QuantityFlag*> mq_flags;
584                 const sigrok::Quantity * const mq = sigrok::Quantity::VOLTAGE;
585                 const sigrok::Unit * const unit = sigrok::Unit::VOLT;
586
587                 shared_ptr<sigrok::Packet> packet =
588                         Session::sr_context->create_analog_packet(channels,
589                         asamples, ConversionBlockSize, mq, unit, mq_flags);
590
591                 shared_ptr<sigrok::Analog> analog =
592                         dynamic_pointer_cast<sigrok::Analog>(packet->payload());
593
594                 // Convert
595                 uint64_t i = start_sample;
596
597                 if (conversion_type_ == A2LConversionByThreshold) {
598                         const double threshold = get_conversion_thresholds()[0];
599
600                         // Convert as many sample blocks as we can
601                         while ((end_sample - i) > ConversionBlockSize) {
602                                 asegment->get_samples(i, i + ConversionBlockSize, asamples);
603
604                                 shared_ptr<sigrok::Logic> logic =
605                                         analog->get_logic_via_threshold(threshold, lsamples);
606
607                                 lsegment->append_payload(logic->data_pointer(), logic->data_length());
608                                 samples_added(lsegment->segment_id(), i, i + ConversionBlockSize);
609                                 i += ConversionBlockSize;
610                         }
611
612                         // Re-create sigrok::Analog and convert remaining samples
613                         packet = Session::sr_context->create_analog_packet(channels,
614                                 asamples, end_sample - i, mq, unit, mq_flags);
615
616                         analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
617
618                         asegment->get_samples(i, end_sample, asamples);
619                         shared_ptr<sigrok::Logic> logic =
620                                 analog->get_logic_via_threshold(threshold, lsamples);
621                         lsegment->append_payload(logic->data_pointer(), logic->data_length());
622                         samples_added(lsegment->segment_id(), i, end_sample);
623                 }
624
625                 if (conversion_type_ == A2LConversionBySchmittTrigger) {
626                         const vector<double> thresholds = get_conversion_thresholds();
627                         const double lo_thr = thresholds[0];
628                         const double hi_thr = thresholds[1];
629
630                         uint8_t state = 0;  // TODO Use value of logic sample n-1 instead of 0
631
632                         // Convert as many sample blocks as we can
633                         while ((end_sample - i) > ConversionBlockSize) {
634                                 asegment->get_samples(i, i + ConversionBlockSize, asamples);
635
636                                 shared_ptr<sigrok::Logic> logic =
637                                         analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
638                                                 &state, lsamples);
639
640                                 lsegment->append_payload(logic->data_pointer(), logic->data_length());
641                                 samples_added(lsegment->segment_id(), i, i + ConversionBlockSize);
642                                 i += ConversionBlockSize;
643                         }
644
645                         // Re-create sigrok::Analog and convert remaining samples
646                         packet = Session::sr_context->create_analog_packet(channels,
647                                 asamples, end_sample - i, mq, unit, mq_flags);
648
649                         analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
650
651                         asegment->get_samples(i, end_sample, asamples);
652                         shared_ptr<sigrok::Logic> logic =
653                                 analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
654                                         &state, lsamples);
655                         lsegment->append_payload(logic->data_pointer(), logic->data_length());
656                         samples_added(lsegment->segment_id(), i, end_sample);
657                 }
658
659                 // If acquisition is ongoing, start-/endsample may have changed
660                 end_sample = asegment->get_sample_count();
661
662                 delete[] lsamples;
663                 delete[] asamples;
664         }
665 }
666
667 void SignalBase::convert_single_segment(AnalogSegment *asegment, LogicSegment *lsegment)
668 {
669         uint64_t start_sample, end_sample, old_end_sample;
670         start_sample = end_sample = 0;
671         bool complete_state, old_complete_state;
672
673         start_sample = lsegment->get_sample_count();
674         end_sample = asegment->get_sample_count();
675         complete_state = asegment->is_complete();
676
677         // Don't do anything if the segment is still being filled and the sample count is too small
678         if ((!complete_state) && (end_sample - start_sample < ConversionBlockSize))
679                 return;
680
681         do {
682                 convert_single_segment_range(asegment, lsegment, start_sample, end_sample);
683
684                 old_end_sample = end_sample;
685                 old_complete_state = complete_state;
686
687                 start_sample = lsegment->get_sample_count();
688                 end_sample = asegment->get_sample_count();
689                 complete_state = asegment->is_complete();
690
691                 // If the segment has been incomplete when we were called and has been
692                 // completed in the meanwhile, we convert the remaining samples as well.
693                 // Also, if a sufficient number of samples was added in the meanwhile,
694                 // we do another round of sample conversion.
695         } while ((complete_state != old_complete_state) ||
696                 (end_sample - old_end_sample >= ConversionBlockSize));
697 }
698
699 void SignalBase::conversion_thread_proc()
700 {
701         shared_ptr<Analog> analog_data;
702
703         if (conversion_is_a2l()) {
704                 analog_data = dynamic_pointer_cast<Analog>(data_);
705
706                 if (analog_data->analog_segments().size() == 0) {
707                         unique_lock<mutex> input_lock(conversion_input_mutex_);
708                         conversion_input_cond_.wait(input_lock);
709                 }
710
711         } else
712                 // Currently, we only handle A2L conversions
713                 return;
714
715         // If we had to wait for input data, we may have been notified to terminate
716         if (conversion_interrupt_)
717                 return;
718
719         uint32_t segment_id = 0;
720
721         AnalogSegment *asegment = analog_data->analog_segments().front().get();
722         assert(asegment);
723
724         const shared_ptr<Logic> logic_data = dynamic_pointer_cast<Logic>(converted_data_);
725         assert(logic_data);
726
727         // Create the initial logic data segment if needed
728         if (logic_data->logic_segments().size() == 0) {
729                 shared_ptr<LogicSegment> new_segment =
730                         make_shared<LogicSegment>(*logic_data.get(), 0, 1, asegment->samplerate());
731                 logic_data->push_segment(new_segment);
732         }
733
734         LogicSegment *lsegment = logic_data->logic_segments().front().get();
735         assert(lsegment);
736
737         do {
738                 convert_single_segment(asegment, lsegment);
739
740                 // Only advance to next segment if the current input segment is complete
741                 if (asegment->is_complete() &&
742                         analog_data->analog_segments().size() > logic_data->logic_segments().size()) {
743                         // There are more segments to process
744                         segment_id++;
745
746                         try {
747                                 asegment = analog_data->analog_segments().at(segment_id).get();
748                         } catch (out_of_range&) {
749                                 qDebug() << "Conversion error for" << name() << ": no analog segment" \
750                                         << segment_id << ", segments size is" << analog_data->analog_segments().size();
751                                 return;
752                         }
753
754                         shared_ptr<LogicSegment> new_segment = make_shared<LogicSegment>(
755                                 *logic_data.get(), segment_id, 1, asegment->samplerate());
756                         logic_data->push_segment(new_segment);
757
758                         lsegment = logic_data->logic_segments().back().get();
759                 } else {
760                         // No more samples/segments to process, wait for data or interrupt
761                         if (!conversion_interrupt_) {
762                                 unique_lock<mutex> input_lock(conversion_input_mutex_);
763                                 conversion_input_cond_.wait(input_lock);
764                         }
765                 }
766         } while (!conversion_interrupt_);
767 }
768
769 void SignalBase::start_conversion(bool delayed_start)
770 {
771         if (delayed_start) {
772                 delayed_conversion_starter_.start();
773                 return;
774         }
775
776         stop_conversion();
777
778         if (converted_data_)
779                 converted_data_->clear();
780         samples_cleared();
781
782         conversion_interrupt_ = false;
783         conversion_thread_ = std::thread(
784                 &SignalBase::conversion_thread_proc, this);
785 }
786
787 void SignalBase::stop_conversion()
788 {
789         // Stop conversion so we can restart it from the beginning
790         conversion_interrupt_ = true;
791         conversion_input_cond_.notify_one();
792         if (conversion_thread_.joinable())
793                 conversion_thread_.join();
794 }
795
796 void SignalBase::on_samples_cleared()
797 {
798         if (converted_data_)
799                 converted_data_->clear();
800
801         samples_cleared();
802 }
803
804 void SignalBase::on_samples_added(SharedPtrToSegment segment, uint64_t start_sample,
805         uint64_t end_sample)
806 {
807         if (conversion_type_ != NoConversion) {
808                 if (conversion_thread_.joinable()) {
809                         // Notify the conversion thread since it's running
810                         conversion_input_cond_.notify_one();
811                 } else {
812                         // Start the conversion thread unless the delay timer is running
813                         if (!delayed_conversion_starter_.isActive())
814                                 start_conversion();
815                 }
816         }
817
818         samples_added(segment->segment_id(), start_sample, end_sample);
819 }
820
821 void SignalBase::on_min_max_changed(float min, float max)
822 {
823         // Restart conversion if one is enabled and uses a calculated threshold
824         if ((conversion_type_ != NoConversion) &&
825                 (get_current_conversion_preset() == DynamicPreset))
826                 start_conversion(true);
827
828         min_max_changed(min, max);
829 }
830
831 void SignalBase::on_capture_state_changed(int state)
832 {
833         if (state == Session::Running) {
834                 // Restart conversion if one is enabled
835                 if (conversion_type_ != NoConversion)
836                         start_conversion();
837         }
838 }
839
840 void SignalBase::on_delayed_conversion_start()
841 {
842         start_conversion();
843 }
844
845 } // namespace data
846 } // namespace pv