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