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