Ruler tick legends don't partly disappear when scrolled off the ends
[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::ColourBGAlpha = 8 * 256 / 100;
45 const uint64_t SignalBase::ConversionBlockSize = 4096;
46 const uint32_t SignalBase::ConversionDelay = 1000;  // 1 second
47
48 SignalBase::SignalBase(shared_ptr<sigrok::Channel> channel, ChannelType channel_type) :
49         channel_(channel),
50         channel_type_(channel_type),
51         conversion_type_(NoConversion),
52         min_value_(0),
53         max_value_(0)
54 {
55         if (channel_)
56                 internal_name_ = QString::fromStdString(channel_->name());
57
58         connect(&delayed_conversion_starter_, SIGNAL(timeout()),
59                 this, SLOT(on_delayed_conversion_start()));
60         delayed_conversion_starter_.setSingleShot(true);
61         delayed_conversion_starter_.setInterval(ConversionDelay);
62 }
63
64 SignalBase::~SignalBase()
65 {
66         stop_conversion();
67 }
68
69 shared_ptr<sigrok::Channel> SignalBase::channel() const
70 {
71         return channel_;
72 }
73
74 QString SignalBase::name() const
75 {
76         return (channel_) ? QString::fromStdString(channel_->name()) : name_;
77 }
78
79 QString SignalBase::internal_name() const
80 {
81         return internal_name_;
82 }
83
84 void SignalBase::set_name(QString name)
85 {
86         if (channel_)
87                 channel_->set_name(name.toUtf8().constData());
88
89         name_ = name;
90
91         name_changed(name);
92 }
93
94 bool SignalBase::enabled() const
95 {
96         return (channel_) ? channel_->enabled() : true;
97 }
98
99 void SignalBase::set_enabled(bool value)
100 {
101         if (channel_) {
102                 channel_->set_enabled(value);
103                 enabled_changed(value);
104         }
105 }
106
107 SignalBase::ChannelType SignalBase::type() const
108 {
109         return channel_type_;
110 }
111
112 unsigned int SignalBase::index() const
113 {
114         return (channel_) ? channel_->index() : 0;
115 }
116
117 unsigned int SignalBase::logic_bit_index() const
118 {
119         if (channel_type_ == LogicChannel)
120                 return channel_->index();
121         else
122                 return 0;
123 }
124
125 QColor SignalBase::colour() const
126 {
127         return colour_;
128 }
129
130 void SignalBase::set_colour(QColor colour)
131 {
132         colour_ = colour;
133
134         bgcolour_ = colour;
135         bgcolour_.setAlpha(ColourBGAlpha);
136
137         colour_changed(colour);
138 }
139
140 QColor SignalBase::bgcolour() const
141 {
142         return bgcolour_;
143 }
144
145 void SignalBase::set_data(shared_ptr<pv::data::SignalData> data)
146 {
147         if (data_) {
148                 disconnect(data.get(), SIGNAL(samples_cleared()),
149                         this, SLOT(on_samples_cleared()));
150                 disconnect(data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
151                         this, SLOT(on_samples_added(QObject*, uint64_t, uint64_t)));
152
153                 if (channel_type_ == AnalogChannel) {
154                         shared_ptr<Analog> analog = analog_data();
155                         assert(analog);
156
157                         disconnect(analog.get(), SIGNAL(min_max_changed(float, float)),
158                                 this, SLOT(on_min_max_changed(float, float)));
159                 }
160         }
161
162         data_ = data;
163
164         if (data_) {
165                 connect(data.get(), SIGNAL(samples_cleared()),
166                         this, SLOT(on_samples_cleared()));
167                 connect(data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
168                         this, SLOT(on_samples_added(QObject*, uint64_t, uint64_t)));
169
170                 if (channel_type_ == AnalogChannel) {
171                         shared_ptr<Analog> analog = analog_data();
172                         assert(analog);
173
174                         connect(analog.get(), SIGNAL(min_max_changed(float, float)),
175                                 this, SLOT(on_min_max_changed(float, float)));
176                 }
177         }
178 }
179
180 shared_ptr<data::Analog> SignalBase::analog_data() const
181 {
182         shared_ptr<Analog> result = nullptr;
183
184         if (channel_type_ == AnalogChannel)
185                 result = dynamic_pointer_cast<Analog>(data_);
186
187         return result;
188 }
189
190 shared_ptr<data::Logic> SignalBase::logic_data() const
191 {
192         shared_ptr<Logic> result = nullptr;
193
194         if (channel_type_ == LogicChannel)
195                 result = dynamic_pointer_cast<Logic>(data_);
196
197         if (((conversion_type_ == A2LConversionByThreshold) ||
198                 (conversion_type_ == A2LConversionBySchmittTrigger)))
199                 result = dynamic_pointer_cast<Logic>(converted_data_);
200
201         return result;
202 }
203
204 bool SignalBase::segment_is_complete(uint32_t segment_id) const
205 {
206         bool result = true;
207
208         if (channel_type_ == AnalogChannel)
209         {
210                 shared_ptr<Analog> data = dynamic_pointer_cast<Analog>(data_);
211                 auto segments = data->analog_segments();
212                 try {
213                         result = segments.at(segment_id)->is_complete();
214                 } catch (out_of_range) {
215                         // Do nothing
216                 }
217         }
218
219         if (channel_type_ == LogicChannel)
220         {
221                 shared_ptr<Logic> data = dynamic_pointer_cast<Logic>(data_);
222                 auto segments = data->logic_segments();
223                 try {
224                         result = segments.at(segment_id)->is_complete();
225                 } catch (out_of_range) {
226                         // Do nothing
227                 }
228         }
229
230         return result;
231 }
232
233 SignalBase::ConversionType SignalBase::get_conversion_type() const
234 {
235         return conversion_type_;
236 }
237
238 void SignalBase::set_conversion_type(ConversionType t)
239 {
240         if (conversion_type_ != NoConversion) {
241                 stop_conversion();
242
243                 // Discard converted data
244                 converted_data_.reset();
245                 samples_cleared();
246         }
247
248         conversion_type_ = t;
249
250         // Re-create an empty container
251         // so that the signal is recognized as providing logic data
252         // and thus can be assigned to a decoder
253         if (conversion_is_a2l())
254                 if (!converted_data_)
255                         converted_data_ = make_shared<Logic>(1);  // Contains only one channel
256
257         start_conversion();
258
259         conversion_type_changed(t);
260 }
261
262 map<QString, QVariant> SignalBase::get_conversion_options() const
263 {
264         return conversion_options_;
265 }
266
267 bool SignalBase::set_conversion_option(QString key, QVariant value)
268 {
269         QVariant old_value;
270
271         auto key_iter = conversion_options_.find(key);
272         if (key_iter != conversion_options_.end())
273                 old_value = key_iter->second;
274
275         conversion_options_[key] = value;
276
277         return (value != old_value);
278 }
279
280 vector<double> SignalBase::get_conversion_thresholds(const ConversionType t,
281         const bool always_custom) const
282 {
283         vector<double> result;
284         ConversionType conv_type = t;
285         ConversionPreset preset;
286
287         // Use currently active conversion if no conversion type was supplied
288         if (conv_type == NoConversion)
289                 conv_type = conversion_type_;
290
291         if (always_custom)
292                 preset = NoPreset;
293         else
294                 preset = get_current_conversion_preset();
295
296         if (conv_type == A2LConversionByThreshold) {
297                 double thr = 0;
298
299                 if (preset == NoPreset) {
300                         auto thr_iter = conversion_options_.find("threshold_value");
301                         if (thr_iter != conversion_options_.end())
302                                 thr = (thr_iter->second).toDouble();
303                 }
304
305                 if (preset == DynamicPreset)
306                         thr = (min_value_ + max_value_) * 0.5;  // middle between min and max
307
308                 if ((int)preset == 1) thr = 0.9;
309                 if ((int)preset == 2) thr = 1.8;
310                 if ((int)preset == 3) thr = 2.5;
311                 if ((int)preset == 4) thr = 1.5;
312
313                 result.push_back(thr);
314         }
315
316         if (conv_type == A2LConversionBySchmittTrigger) {
317                 double thr_lo = 0, thr_hi = 0;
318
319                 if (preset == NoPreset) {
320                         auto thr_lo_iter = conversion_options_.find("threshold_value_low");
321                         if (thr_lo_iter != conversion_options_.end())
322                                 thr_lo = (thr_lo_iter->second).toDouble();
323
324                         auto thr_hi_iter = conversion_options_.find("threshold_value_high");
325                         if (thr_hi_iter != conversion_options_.end())
326                                 thr_hi = (thr_hi_iter->second).toDouble();
327                 }
328
329                 if (preset == DynamicPreset) {
330                         const double amplitude = max_value_ - min_value_;
331                         const double center = min_value_ + (amplitude / 2);
332                         thr_lo = center - (amplitude * 0.15);  // 15% margin
333                         thr_hi = center + (amplitude * 0.15);  // 15% margin
334                 }
335
336                 if ((int)preset == 1) { thr_lo = 0.3; thr_hi = 1.2; }
337                 if ((int)preset == 2) { thr_lo = 0.7; thr_hi = 2.5; }
338                 if ((int)preset == 3) { thr_lo = 1.3; thr_hi = 3.7; }
339                 if ((int)preset == 4) { thr_lo = 0.8; thr_hi = 2.0; }
340
341                 result.push_back(thr_lo);
342                 result.push_back(thr_hi);
343         }
344
345         return result;
346 }
347
348 vector< pair<QString, int> > SignalBase::get_conversion_presets() const
349 {
350         vector< pair<QString, int> > presets;
351
352         if (conversion_type_ == A2LConversionByThreshold) {
353                 // Source: http://www.interfacebus.com/voltage_threshold.html
354                 presets.emplace_back(tr("Signal average"), 0);
355                 presets.emplace_back(tr("0.9V (for 1.8V CMOS)"), 1);
356                 presets.emplace_back(tr("1.8V (for 3.3V CMOS)"), 2);
357                 presets.emplace_back(tr("2.5V (for 5.0V CMOS)"), 3);
358                 presets.emplace_back(tr("1.5V (for TTL)"), 4);
359         }
360
361         if (conversion_type_ == A2LConversionBySchmittTrigger) {
362                 // Source: http://www.interfacebus.com/voltage_threshold.html
363                 presets.emplace_back(tr("Signal average +/- 15%"), 0);
364                 presets.emplace_back(tr("0.3V/1.2V (for 1.8V CMOS)"), 1);
365                 presets.emplace_back(tr("0.7V/2.5V (for 3.3V CMOS)"), 2);
366                 presets.emplace_back(tr("1.3V/3.7V (for 5.0V CMOS)"), 3);
367                 presets.emplace_back(tr("0.8V/2.0V (for TTL)"), 4);
368         }
369
370         return presets;
371 }
372
373 SignalBase::ConversionPreset SignalBase::get_current_conversion_preset() const
374 {
375         auto preset = conversion_options_.find("preset");
376         if (preset != conversion_options_.end())
377                 return (ConversionPreset)((preset->second).toInt());
378
379         return DynamicPreset;
380 }
381
382 void SignalBase::set_conversion_preset(ConversionPreset id)
383 {
384         conversion_options_["preset"] = (int)id;
385 }
386
387 #ifdef ENABLE_DECODE
388 bool SignalBase::is_decode_signal() const
389 {
390         return (channel_type_ == DecodeChannel);
391 }
392 #endif
393
394 void SignalBase::save_settings(QSettings &settings) const
395 {
396         settings.setValue("name", name());
397         settings.setValue("enabled", enabled());
398         settings.setValue("colour", colour());
399         settings.setValue("conversion_type", (int)conversion_type_);
400
401         settings.setValue("conv_options", (int)(conversion_options_.size()));
402         int i = 0;
403         for (auto kvp : conversion_options_) {
404                 settings.setValue(QString("conv_option%1_key").arg(i), kvp.first);
405                 settings.setValue(QString("conv_option%1_value").arg(i), kvp.second);
406                 i++;
407         }
408 }
409
410 void SignalBase::restore_settings(QSettings &settings)
411 {
412         set_name(settings.value("name").toString());
413         set_enabled(settings.value("enabled").toBool());
414         set_colour(settings.value("colour").value<QColor>());
415         set_conversion_type((ConversionType)settings.value("conversion_type").toInt());
416
417         int conv_options = settings.value("conv_options").toInt();
418
419         if (conv_options)
420                 for (int i = 0; i < conv_options; i++) {
421                         QString key = settings.value(QString("conv_option%1_key").arg(i)).toString();
422                         QVariant value = settings.value(QString("conv_option%1_value").arg(i));
423                         conversion_options_[key] = value;
424                 }
425 }
426
427 bool SignalBase::conversion_is_a2l() const
428 {
429         return ((channel_type_ == AnalogChannel) &&
430                 ((conversion_type_ == A2LConversionByThreshold) ||
431                 (conversion_type_ == A2LConversionBySchmittTrigger)));
432 }
433
434 void SignalBase::convert_single_segment(AnalogSegment *asegment, LogicSegment *lsegment)
435 {
436         uint64_t start_sample, end_sample;
437         start_sample = end_sample = 0;
438
439         start_sample = lsegment->get_sample_count();
440         end_sample = asegment->get_sample_count();
441
442         if (end_sample > start_sample) {
443                 tie(min_value_, max_value_) = asegment->get_min_max();
444
445                 // Create sigrok::Analog instance
446                 float *asamples = new float[ConversionBlockSize];
447                 uint8_t *lsamples = new uint8_t[ConversionBlockSize];
448
449                 vector<shared_ptr<sigrok::Channel> > channels;
450                 channels.push_back(channel_);
451
452                 vector<const sigrok::QuantityFlag*> mq_flags;
453                 const sigrok::Quantity * const mq = sigrok::Quantity::VOLTAGE;
454                 const sigrok::Unit * const unit = sigrok::Unit::VOLT;
455
456                 shared_ptr<sigrok::Packet> packet =
457                         Session::sr_context->create_analog_packet(channels,
458                         asamples, ConversionBlockSize, mq, unit, mq_flags);
459
460                 shared_ptr<sigrok::Analog> analog =
461                         dynamic_pointer_cast<sigrok::Analog>(packet->payload());
462
463                 // Convert
464                 uint64_t i = start_sample;
465
466                 if (conversion_type_ == A2LConversionByThreshold) {
467                         const double threshold = get_conversion_thresholds()[0];
468
469                         // Convert as many sample blocks as we can
470                         while ((end_sample - i) > ConversionBlockSize) {
471                                 asegment->get_samples(i, i + ConversionBlockSize, asamples);
472
473                                 shared_ptr<sigrok::Logic> logic =
474                                         analog->get_logic_via_threshold(threshold, lsamples);
475
476                                 lsegment->append_payload(logic->data_pointer(), logic->data_length());
477
478                                 samples_added(lsegment, i, i + ConversionBlockSize);
479                                 i += ConversionBlockSize;
480                         }
481
482                         // Re-create sigrok::Analog and convert remaining samples
483                         packet = Session::sr_context->create_analog_packet(channels,
484                                 asamples, end_sample - i, mq, unit, mq_flags);
485
486                         analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
487
488                         asegment->get_samples(i, end_sample, asamples);
489                         shared_ptr<sigrok::Logic> logic =
490                                 analog->get_logic_via_threshold(threshold, lsamples);
491                         lsegment->append_payload(logic->data_pointer(), logic->data_length());
492                         samples_added(lsegment, i, end_sample);
493                 }
494
495                 if (conversion_type_ == A2LConversionBySchmittTrigger) {
496                         const vector<double> thresholds = get_conversion_thresholds();
497                         const double lo_thr = thresholds[0];
498                         const double hi_thr = thresholds[1];
499
500                         uint8_t state = 0;  // TODO Use value of logic sample n-1 instead of 0
501
502                         // Convert as many sample blocks as we can
503                         while ((end_sample - i) > ConversionBlockSize) {
504                                 asegment->get_samples(i, i + ConversionBlockSize, asamples);
505
506                                 shared_ptr<sigrok::Logic> logic =
507                                         analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
508                                                 &state, lsamples);
509
510                                 lsegment->append_payload(logic->data_pointer(), logic->data_length());
511
512                                 samples_added(lsegment, i, i + ConversionBlockSize);
513                                 i += ConversionBlockSize;
514                         }
515
516                         // Re-create sigrok::Analog and convert remaining samples
517                         packet = Session::sr_context->create_analog_packet(channels,
518                                 asamples, end_sample - i, mq, unit, mq_flags);
519
520                         analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
521
522                         asegment->get_samples(i, end_sample, asamples);
523                         shared_ptr<sigrok::Logic> logic =
524                                 analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
525                                         &state, lsamples);
526                         lsegment->append_payload(logic->data_pointer(), logic->data_length());
527                         samples_added(lsegment, i, end_sample);
528                 }
529
530                 // If acquisition is ongoing, start-/endsample may have changed
531                 end_sample = asegment->get_sample_count();
532
533                 delete[] lsamples;
534                 delete[] asamples;
535         }
536 }
537
538 void SignalBase::conversion_thread_proc()
539 {
540         shared_ptr<Analog> analog_data;
541
542         if (conversion_is_a2l()) {
543                 analog_data = dynamic_pointer_cast<Analog>(data_);
544
545                 if (analog_data->analog_segments().size() == 0) {
546                         unique_lock<mutex> input_lock(conversion_input_mutex_);
547                         conversion_input_cond_.wait(input_lock);
548                 }
549
550         } else
551                 // Currently, we only handle A2L conversions
552                 return;
553
554         // If we had to wait for input data, we may have been notified to terminate
555         if (conversion_interrupt_)
556                 return;
557
558         uint32_t segment_id = 0;
559
560         AnalogSegment *asegment = analog_data->analog_segments().front().get();
561         assert(asegment);
562
563         const shared_ptr<Logic> logic_data = dynamic_pointer_cast<Logic>(converted_data_);
564         assert(logic_data);
565
566         // Create the initial logic data segment if needed
567         if (logic_data->logic_segments().size() == 0) {
568                 shared_ptr<LogicSegment> new_segment =
569                         make_shared<LogicSegment>(*logic_data.get(), 0, 1, asegment->samplerate());
570                 logic_data->push_segment(new_segment);
571         }
572
573         LogicSegment *lsegment = logic_data->logic_segments().front().get();
574         assert(lsegment);
575
576         do {
577                 convert_single_segment(asegment, lsegment);
578
579                 if (analog_data->analog_segments().size() > logic_data->logic_segments().size()) {
580                         // There are more segments to process
581                         segment_id++;
582
583                         try {
584                                 asegment = analog_data->analog_segments().at(segment_id).get();
585                         } catch (out_of_range) {
586                                 qDebug() << "Conversion error for" << name() << ": no analog segment" \
587                                         << segment_id << ", segments size is" << analog_data->analog_segments().size();
588                                 return;
589                         }
590
591                         shared_ptr<LogicSegment> new_segment = make_shared<LogicSegment>(
592                                 *logic_data.get(), segment_id, 1, asegment->samplerate());
593                         logic_data->push_segment(new_segment);
594
595                         lsegment = logic_data->logic_segments().back().get();
596                 } else {
597                         // No more segments to process, wait for data or interrupt
598                         if (!conversion_interrupt_) {
599                                 unique_lock<mutex> input_lock(conversion_input_mutex_);
600                                 conversion_input_cond_.wait(input_lock);
601                         }
602                 }
603         } while (!conversion_interrupt_);
604 }
605
606 void SignalBase::start_conversion(bool delayed_start)
607 {
608         if (delayed_start) {
609                 delayed_conversion_starter_.start();
610                 return;
611         }
612
613         stop_conversion();
614
615         if (converted_data_)
616                 converted_data_->clear();
617         samples_cleared();
618
619         conversion_interrupt_ = false;
620         conversion_thread_ = std::thread(
621                 &SignalBase::conversion_thread_proc, this);
622 }
623
624 void SignalBase::stop_conversion()
625 {
626         // Stop conversion so we can restart it from the beginning
627         conversion_interrupt_ = true;
628         conversion_input_cond_.notify_one();
629         if (conversion_thread_.joinable())
630                 conversion_thread_.join();
631 }
632
633 void SignalBase::on_samples_cleared()
634 {
635         if (converted_data_)
636                 converted_data_->clear();
637
638         samples_cleared();
639 }
640
641 void SignalBase::on_samples_added(QObject* segment, uint64_t start_sample,
642         uint64_t end_sample)
643 {
644         if (conversion_type_ != NoConversion) {
645                 if (conversion_thread_.joinable()) {
646                         // Notify the conversion thread since it's running
647                         conversion_input_cond_.notify_one();
648                 } else {
649                         // Start the conversion thread unless the delay timer is running
650                         if (!delayed_conversion_starter_.isActive())
651                                 start_conversion();
652                 }
653         }
654
655         samples_added(segment, start_sample, end_sample);
656 }
657
658 void SignalBase::on_min_max_changed(float min, float max)
659 {
660         // Restart conversion if one is enabled and uses a calculated threshold
661         if ((conversion_type_ != NoConversion) &&
662                 (get_current_conversion_preset() == DynamicPreset))
663                 start_conversion(true);
664
665         min_max_changed(min, max);
666 }
667
668 void SignalBase::on_capture_state_changed(int state)
669 {
670         if (state == Session::Running) {
671                 // Restart conversion if one is enabled
672                 if (conversion_type_ != NoConversion)
673                         start_conversion();
674         }
675 }
676
677 void SignalBase::on_delayed_conversion_start()
678 {
679         start_conversion();
680 }
681
682 } // namespace data
683 } // namespace pv