]> sigrok.org Git - pulseview.git/blame - pv/data/decodesignal.cpp
Annotation: Use special type for the class, not plain int
[pulseview.git] / pv / data / decodesignal.cpp
CommitLineData
ad908057
SA
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2017 Soeren Apel <soeren@apelpie.net>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
0c5fe73e
SA
20#include <limits>
21
47747218
SA
22#include <QDebug>
23
ad908057
SA
24#include "logic.hpp"
25#include "logicsegment.hpp"
26#include "decodesignal.hpp"
27#include "signaldata.hpp"
28
29#include <pv/binding/decoder.hpp>
30#include <pv/data/decode/decoder.hpp>
ecd07c20 31#include <pv/data/decode/row.hpp>
d3feec23 32#include <pv/globalsettings.hpp>
ad908057
SA
33#include <pv/session.hpp>
34
47747218
SA
35using std::lock_guard;
36using std::make_pair;
ad908057 37using std::make_shared;
0c5fe73e 38using std::min;
5ecf957f 39using std::out_of_range;
ad908057 40using std::shared_ptr;
47747218
SA
41using std::unique_lock;
42using pv::data::decode::Annotation;
ad908057 43using pv::data::decode::Decoder;
ecd07c20 44using pv::data::decode::Row;
ad908057
SA
45
46namespace pv {
47namespace data {
48
47747218
SA
49const double DecodeSignal::DecodeMargin = 1.0;
50const double DecodeSignal::DecodeThreshold = 0.2;
3fbddf7f 51const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
ad908057 52
ad908057 53
47747218
SA
54DecodeSignal::DecodeSignal(pv::Session &session) :
55 SignalBase(nullptr, SignalBase::DecodeChannel),
56 session_(session),
e91883bb 57 srd_session_(nullptr),
47747218 58 logic_mux_data_invalid_(false),
e3202557 59 stack_config_changed_(true),
8a603e13 60 current_segment_id_(0)
ad908057 61{
47747218
SA
62 connect(&session_, SIGNAL(capture_state_changed(int)),
63 this, SLOT(on_capture_state_changed(int)));
ad908057
SA
64}
65
47747218 66DecodeSignal::~DecodeSignal()
ad908057 67{
8ce0e732 68 reset_decode(true);
ad908057
SA
69}
70
47747218 71const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
ecd07c20 72{
47747218 73 return stack_;
ecd07c20
SA
74}
75
c8e60bdf 76void DecodeSignal::stack_decoder(const srd_decoder *decoder)
ad908057
SA
77{
78 assert(decoder);
762ab7a4
SA
79 const shared_ptr<Decoder> dec = make_shared<decode::Decoder>(decoder);
80
81 stack_.push_back(dec);
47747218
SA
82
83 // Set name if this decoder is the first in the list
84 if (stack_.size() == 1)
85 set_name(QString::fromUtf8(decoder->name));
132a5c6d 86
27a3f09b 87 // Include the newly created decode channels in the channel lists
9f97b357 88 update_channel_list();
132a5c6d 89
e3202557 90 stack_config_changed_ = true;
762ab7a4 91 auto_assign_signals(dec);
27a3f09b 92 commit_decoder_channels();
47747218 93 begin_decode();
ad908057
SA
94}
95
96void DecodeSignal::remove_decoder(int index)
97{
47747218
SA
98 assert(index >= 0);
99 assert(index < (int)stack_.size());
100
101 // Find the decoder in the stack
102 auto iter = stack_.begin();
103 for (int i = 0; i < index; i++, iter++)
104 assert(iter != stack_.end());
105
106 // Delete the element
107 stack_.erase(iter);
108
109 // Update channels and decoded data
e3202557 110 stack_config_changed_ = true;
9f97b357 111 update_channel_list();
47747218 112 begin_decode();
ad908057
SA
113}
114
115bool DecodeSignal::toggle_decoder_visibility(int index)
116{
47747218 117 auto iter = stack_.cbegin();
ad908057 118 for (int i = 0; i < index; i++, iter++)
47747218 119 assert(iter != stack_.end());
ad908057
SA
120
121 shared_ptr<Decoder> dec = *iter;
122
123 // Toggle decoder visibility
124 bool state = false;
125 if (dec) {
126 state = !dec->shown();
127 dec->show(state);
128 }
129
130 return state;
131}
132
8ce0e732 133void DecodeSignal::reset_decode(bool shutting_down)
47747218 134{
8ce0e732 135 if (stack_config_changed_ || shutting_down)
e3202557
SA
136 stop_srd_session();
137 else
138 terminate_srd_session();
ce0b6a40 139
1b56c646
SA
140 if (decode_thread_.joinable()) {
141 decode_interrupt_ = true;
142 decode_input_cond_.notify_one();
143 decode_thread_.join();
144 }
145
146 if (logic_mux_thread_.joinable()) {
147 logic_mux_interrupt_ = true;
148 logic_mux_cond_.notify_one();
149 logic_mux_thread_.join();
150 }
151
47747218 152 class_rows_.clear();
8a603e13 153 current_segment_id_ = 0;
72435789 154 segments_.clear();
1b56c646
SA
155
156 logic_mux_data_.reset();
157 logic_mux_data_invalid_ = true;
eee3eab9 158
403c3e87
SA
159 if (!error_message_.isEmpty()) {
160 error_message_ = QString();
161 qDebug().noquote().nospace() << name() << ": Error cleared";
162 }
72435789 163
eee3eab9 164 decode_reset();
47747218
SA
165}
166
946b52e1
SA
167void DecodeSignal::begin_decode()
168{
47747218
SA
169 if (decode_thread_.joinable()) {
170 decode_interrupt_ = true;
171 decode_input_cond_.notify_one();
172 decode_thread_.join();
173 }
174
175 if (logic_mux_thread_.joinable()) {
176 logic_mux_interrupt_ = true;
177 logic_mux_cond_.notify_one();
178 logic_mux_thread_.join();
179 }
180
181 reset_decode();
182
27a3f09b 183 if (stack_.size() == 0) {
403c3e87 184 set_error_message(tr("No decoders"));
27a3f09b
SA
185 return;
186 }
187
188 assert(channels_.size() > 0);
189
190 if (get_assigned_signal_count() == 0) {
403c3e87 191 set_error_message(tr("There are no channels assigned to this decoder"));
27a3f09b
SA
192 return;
193 }
194
04627946
SA
195 // Make sure that all assigned channels still provide logic data
196 // (can happen when a converted signal was assigned but the
197 // conversion removed in the meanwhile)
198 for (data::DecodeChannel &ch : channels_)
199 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
200 ch.assigned_signal = nullptr;
201
47747218
SA
202 // Check that all decoders have the required channels
203 for (const shared_ptr<decode::Decoder> &dec : stack_)
204 if (!dec->have_required_channels()) {
403c3e87
SA
205 set_error_message(tr("One or more required channels "
206 "have not been specified"));
47747218
SA
207 return;
208 }
209
4913560f 210 // Map out all the annotation classes
47747218
SA
211 for (const shared_ptr<decode::Decoder> &dec : stack_) {
212 assert(dec);
213 const srd_decoder *const decc = dec->decoder();
214 assert(dec->decoder());
215
47747218
SA
216 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
217 const srd_decoder_annotation_row *const ann_row =
218 (srd_decoder_annotation_row *)l->data;
219 assert(ann_row);
220
221 const Row row(decc, ann_row);
222
47747218
SA
223 for (const GSList *ll = ann_row->ann_classes;
224 ll; ll = ll->next)
225 class_rows_[make_pair(decc,
226 GPOINTER_TO_INT(ll->data))] = row;
227 }
228 }
229
27a3f09b
SA
230 // Free the logic data and its segment(s) if it needs to be updated
231 if (logic_mux_data_invalid_)
232 logic_mux_data_.reset();
233
234 if (!logic_mux_data_) {
72435789 235 const uint32_t ch_count = get_assigned_signal_count();
ed535cd7 236 logic_mux_unit_size_ = (ch_count + 7) / 8;
27a3f09b 237 logic_mux_data_ = make_shared<Logic>(ch_count);
27a3f09b 238 }
47747218 239
ed535cd7
SA
240 // Receive notifications when new sample data is available
241 connect_input_notifiers();
242
8a603e13 243 if (get_input_segment_count() == 0) {
403c3e87 244 set_error_message(tr("No input data"));
ed535cd7
SA
245 return;
246 }
247
27a3f09b
SA
248 // Make sure the logic output data is complete and up-to-date
249 logic_mux_interrupt_ = false;
250 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
251
252 // Decode the muxed logic data
47747218
SA
253 decode_interrupt_ = false;
254 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
946b52e1
SA
255}
256
ecd07c20
SA
257QString DecodeSignal::error_message() const
258{
47747218
SA
259 lock_guard<mutex> lock(output_mutex_);
260 return error_message_;
ecd07c20
SA
261}
262
47747218 263const vector<data::DecodeChannel> DecodeSignal::get_channels() const
9f97b357
SA
264{
265 return channels_;
266}
267
762ab7a4 268void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
132a5c6d 269{
47747218
SA
270 bool new_assignment = false;
271
132a5c6d
SA
272 // Try to auto-select channels that don't have signals assigned yet
273 for (data::DecodeChannel &ch : channels_) {
762ab7a4
SA
274 // If a decoder is given, auto-assign only its channels
275 if (dec && (ch.decoder_ != dec))
276 continue;
277
132a5c6d
SA
278 if (ch.assigned_signal)
279 continue;
280
692f6093
SA
281 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
282 const QString ch_name = ch.name.toLower();
283 const QString s_name = s->name().toLower();
284
285 if (s->logic_data() &&
286 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
132a5c6d 287 ch.assigned_signal = s.get();
47747218
SA
288 new_assignment = true;
289 }
692f6093 290 }
47747218
SA
291 }
292
293 if (new_assignment) {
294 logic_mux_data_invalid_ = true;
e3202557 295 stack_config_changed_ = true;
27a3f09b 296 commit_decoder_channels();
47747218 297 channels_updated();
132a5c6d
SA
298 }
299}
300
9f97b357
SA
301void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
302{
303 for (data::DecodeChannel &ch : channels_)
47747218 304 if (ch.id == channel_id) {
9f97b357 305 ch.assigned_signal = signal;
47747218
SA
306 logic_mux_data_invalid_ = true;
307 }
9f97b357 308
e3202557 309 stack_config_changed_ = true;
27a3f09b 310 commit_decoder_channels();
9f97b357 311 channels_updated();
47747218 312 begin_decode();
9f97b357
SA
313}
314
27a3f09b
SA
315int DecodeSignal::get_assigned_signal_count() const
316{
317 // Count all channels that have a signal assigned to them
318 return count_if(channels_.begin(), channels_.end(),
319 [](data::DecodeChannel ch) { return ch.assigned_signal; });
320}
321
9f97b357
SA
322void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
323{
324 for (data::DecodeChannel &ch : channels_)
325 if (ch.id == channel_id)
326 ch.initial_pin_state = init_state;
327
e3202557 328 stack_config_changed_ = true;
9f97b357 329 channels_updated();
47747218 330 begin_decode();
9f97b357
SA
331}
332
ff83d980
SA
333double DecodeSignal::samplerate() const
334{
72435789
SA
335 double result = 0;
336
337 // TODO For now, we simply return the first samplerate that we have
8a603e13
SA
338 if (segments_.size() > 0)
339 result = segments_.front().samplerate;
72435789
SA
340
341 return result;
ff83d980
SA
342}
343
72435789 344const pv::util::Timestamp DecodeSignal::start_time() const
ff83d980 345{
72435789
SA
346 pv::util::Timestamp result;
347
348 // TODO For now, we simply return the first start time that we have
8a603e13
SA
349 if (segments_.size() > 0)
350 result = segments_.front().start_time;
72435789
SA
351
352 return result;
ff83d980
SA
353}
354
5ecf957f 355int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
0c5fe73e
SA
356{
357 // The working sample count is the highest sample number for
ed535cd7
SA
358 // which all used signals have data available, so go through all
359 // channels and use the lowest overall sample count of the segment
0c5fe73e 360
0c5fe73e
SA
361 int64_t count = std::numeric_limits<int64_t>::max();
362 bool no_signals_assigned = true;
363
364 for (const data::DecodeChannel &ch : channels_)
365 if (ch.assigned_signal) {
366 no_signals_assigned = false;
367
368 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
369 if (!logic_data || logic_data->logic_segments().empty())
370 return 0;
371
5ecf957f
SA
372 try {
373 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
374 count = min(count, (int64_t)segment->get_sample_count());
30677c13 375 } catch (out_of_range&) {
5ecf957f
SA
376 return 0;
377 }
0c5fe73e
SA
378 }
379
380 return (no_signals_assigned ? 0 : count);
381}
382
5ecf957f 383int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id) const
ff83d980 384{
47747218 385 lock_guard<mutex> decode_lock(output_mutex_);
5ecf957f
SA
386
387 int64_t result = 0;
388
72435789
SA
389 try {
390 const DecodeSegment *segment = &(segments_.at(segment_id));
391 result = segment->samples_decoded;
30677c13 392 } catch (out_of_range&) {
72435789
SA
393 // Do nothing
394 }
5ecf957f
SA
395
396 return result;
ff83d980
SA
397}
398
ecd07c20
SA
399vector<Row> DecodeSignal::visible_rows() const
400{
47747218
SA
401 lock_guard<mutex> lock(output_mutex_);
402
403 vector<Row> rows;
404
405 for (const shared_ptr<decode::Decoder> &dec : stack_) {
406 assert(dec);
407 if (!dec->shown())
408 continue;
409
410 const srd_decoder *const decc = dec->decoder();
411 assert(dec->decoder());
412
413 // Add a row for the decoder if it doesn't have a row list
414 if (!decc->annotation_rows)
415 rows.emplace_back(decc);
416
417 // Add the decoder rows
418 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
419 const srd_decoder_annotation_row *const ann_row =
420 (srd_decoder_annotation_row *)l->data;
421 assert(ann_row);
422 rows.emplace_back(decc, ann_row);
423 }
424 }
425
426 return rows;
ecd07c20
SA
427}
428
429void DecodeSignal::get_annotation_subset(
430 vector<pv::data::decode::Annotation> &dest,
72435789 431 const decode::Row &row, uint32_t segment_id, uint64_t start_sample,
ecd07c20
SA
432 uint64_t end_sample) const
433{
47747218
SA
434 lock_guard<mutex> lock(output_mutex_);
435
72435789
SA
436 try {
437 const DecodeSegment *segment = &(segments_.at(segment_id));
438 const map<const decode::Row, decode::RowData> *rows =
439 &(segment->annotation_rows);
440
441 const auto iter = rows->find(row);
442 if (iter != rows->end())
443 (*iter).second.get_annotation_subset(dest,
444 start_sample, end_sample);
30677c13 445 } catch (out_of_range&) {
72435789
SA
446 // Do nothing
447 }
47747218
SA
448}
449
450void DecodeSignal::save_settings(QSettings &settings) const
451{
452 SignalBase::save_settings(settings);
453
c8e60bdf
SA
454 settings.setValue("decoders", (int)(stack_.size()));
455
8b5ea5a1 456 // Save decoder stack
c8e60bdf
SA
457 int decoder_idx = 0;
458 for (shared_ptr<decode::Decoder> decoder : stack_) {
459 settings.beginGroup("decoder" + QString::number(decoder_idx++));
460
461 settings.setValue("id", decoder->decoder()->id);
462
d3feec23
SA
463 // Save decoder options
464 const map<string, GVariant*>& options = decoder->options();
465
466 settings.setValue("options", (int)options.size());
467
468 // Note: decode::Decoder::options() returns only the options
469 // that differ from the default. See binding::Decoder::getter()
470 int i = 0;
471 for (auto option : options) {
472 settings.beginGroup("option" + QString::number(i));
473 settings.setValue("name", QString::fromStdString(option.first));
474 GlobalSettings::store_gvariant(settings, option.second);
475 settings.endGroup();
476 i++;
477 }
478
c8e60bdf
SA
479 settings.endGroup();
480 }
481
8b5ea5a1
SA
482 // Save channel mapping
483 settings.setValue("channels", (int)channels_.size());
484
485 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
486 auto channel = find_if(channels_.begin(), channels_.end(),
487 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
488
489 if (channel == channels_.end()) {
490 qDebug() << "ERROR: Gap in channel index:" << channel_id;
491 continue;
492 }
493
494 settings.beginGroup("channel" + QString::number(channel_id));
495
496 settings.setValue("name", channel->name); // Useful for debugging
497 settings.setValue("initial_pin_state", channel->initial_pin_state);
498
499 if (channel->assigned_signal)
500 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
501
502 settings.endGroup();
503 }
47747218
SA
504}
505
506void DecodeSignal::restore_settings(QSettings &settings)
507{
508 SignalBase::restore_settings(settings);
509
8b5ea5a1 510 // Restore decoder stack
c8e60bdf
SA
511 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
512
513 int decoders = settings.value("decoders").toInt();
514
515 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
516 settings.beginGroup("decoder" + QString::number(decoder_idx));
517
518 QString id = settings.value("id").toString();
519
520 for (GSList *entry = dec_list; entry; entry = entry->next) {
521 const srd_decoder *dec = (srd_decoder*)entry->data;
522 if (!dec)
523 continue;
524
525 if (QString::fromUtf8(dec->id) == id) {
d3feec23
SA
526 shared_ptr<decode::Decoder> decoder =
527 make_shared<decode::Decoder>(dec);
528
529 stack_.push_back(decoder);
530
531 // Restore decoder options that differ from their default
532 int options = settings.value("options").toInt();
533
534 for (int i = 0; i < options; i++) {
535 settings.beginGroup("option" + QString::number(i));
536 QString name = settings.value("name").toString();
537 GVariant *value = GlobalSettings::restore_gvariant(settings);
538 decoder->set_option(name.toUtf8(), value);
539 settings.endGroup();
540 }
c8e60bdf
SA
541
542 // Include the newly created decode channels in the channel lists
543 update_channel_list();
544 break;
545 }
546 }
547
548 settings.endGroup();
4ca06ec3 549 channels_updated();
c8e60bdf
SA
550 }
551
8b5ea5a1
SA
552 // Restore channel mapping
553 unsigned int channels = settings.value("channels").toInt();
554
555 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
556 session_.signalbases();
557
558 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
559 auto channel = find_if(channels_.begin(), channels_.end(),
560 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
561
562 if (channel == channels_.end()) {
563 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
564 continue;
565 }
566
567 settings.beginGroup("channel" + QString::number(channel_id));
568
569 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
570
571 for (shared_ptr<data::SignalBase> signal : signalbases)
572 if (signal->name() == assigned_signal_name)
573 channel->assigned_signal = signal.get();
574
575 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
576
577 settings.endGroup();
578 }
579
aa71890d 580 // Update the internal structures
e3202557 581 stack_config_changed_ = true;
aa71890d
SA
582 update_channel_list();
583 commit_decoder_channels();
584
8b5ea5a1 585 begin_decode();
47747218
SA
586}
587
403c3e87
SA
588void DecodeSignal::set_error_message(QString msg)
589{
590 error_message_ = msg;
591 qDebug().noquote().nospace() << name() << ": " << msg;
592}
593
8a603e13
SA
594uint32_t DecodeSignal::get_input_segment_count() const
595{
596 uint64_t count = std::numeric_limits<uint64_t>::max();
597 bool no_signals_assigned = true;
598
599 for (const data::DecodeChannel &ch : channels_)
600 if (ch.assigned_signal) {
601 no_signals_assigned = false;
602
603 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
604 if (!logic_data || logic_data->logic_segments().empty())
605 return 0;
606
607 // Find the min value of all segment counts
608 if ((uint64_t)(logic_data->logic_segments().size()) < count)
609 count = logic_data->logic_segments().size();
610 }
611
612 return (no_signals_assigned ? 0 : count);
613}
614
615uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
616{
617 double samplerate = 0;
618
619 for (const data::DecodeChannel &ch : channels_)
620 if (ch.assigned_signal) {
621 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
622 if (!logic_data || logic_data->logic_segments().empty())
623 continue;
624
625 try {
626 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
627 samplerate = segment->samplerate();
30677c13 628 } catch (out_of_range&) {
8a603e13
SA
629 // Do nothing
630 }
631 break;
632 }
633
634 return samplerate;
635}
636
9f97b357
SA
637void DecodeSignal::update_channel_list()
638{
47747218 639 vector<data::DecodeChannel> prev_channels = channels_;
9f97b357
SA
640 channels_.clear();
641
642 uint16_t id = 0;
643
644 // Copy existing entries, create new as needed
47747218 645 for (shared_ptr<Decoder> decoder : stack_) {
9f97b357
SA
646 const srd_decoder* srd_d = decoder->decoder();
647 const GSList *l;
648
649 // Mandatory channels
650 for (l = srd_d->channels; l; l = l->next) {
651 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
652 bool ch_added = false;
653
654 // Copy but update ID if this channel was in the list before
47747218 655 for (data::DecodeChannel &ch : prev_channels)
9f97b357
SA
656 if (ch.pdch_ == pdch) {
657 ch.id = id++;
658 channels_.push_back(ch);
659 ch_added = true;
660 break;
661 }
662
663 if (!ch_added) {
664 // Create new entry without a mapped signal
6e7a4a00 665 data::DecodeChannel ch = {id++, 0, false, nullptr,
9f97b357
SA
666 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
667 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
668 channels_.push_back(ch);
669 }
670 }
671
672 // Optional channels
673 for (l = srd_d->opt_channels; l; l = l->next) {
674 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
675 bool ch_added = false;
676
677 // Copy but update ID if this channel was in the list before
47747218 678 for (data::DecodeChannel &ch : prev_channels)
9f97b357
SA
679 if (ch.pdch_ == pdch) {
680 ch.id = id++;
681 channels_.push_back(ch);
682 ch_added = true;
683 break;
684 }
685
686 if (!ch_added) {
687 // Create new entry without a mapped signal
6e7a4a00 688 data::DecodeChannel ch = {id++, 0, true, nullptr,
9f97b357
SA
689 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
690 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
691 channels_.push_back(ch);
692 }
693 }
694 }
695
47747218
SA
696 // Invalidate the logic output data if the channel assignment changed
697 if (prev_channels.size() != channels_.size()) {
698 // The number of channels changed, there's definitely a difference
699 logic_mux_data_invalid_ = true;
700 } else {
701 // Same number but assignment may still differ, so compare all channels
702 for (size_t i = 0; i < channels_.size(); i++) {
703 const data::DecodeChannel &p_ch = prev_channels[i];
704 const data::DecodeChannel &ch = channels_[i];
705
706 if ((p_ch.pdch_ != ch.pdch_) ||
707 (p_ch.assigned_signal != ch.assigned_signal)) {
708 logic_mux_data_invalid_ = true;
709 break;
710 }
711 }
712
713 }
714
9f97b357
SA
715 channels_updated();
716}
717
27a3f09b 718void DecodeSignal::commit_decoder_channels()
ad908057 719{
27a3f09b
SA
720 // Submit channel list to every decoder, containing only the relevant channels
721 for (shared_ptr<decode::Decoder> dec : stack_) {
722 vector<data::DecodeChannel*> channel_list;
723
724 for (data::DecodeChannel &ch : channels_)
725 if (ch.decoder_ == dec)
726 channel_list.push_back(&ch);
47747218 727
27a3f09b
SA
728 dec->set_channels(channel_list);
729 }
aa71890d
SA
730
731 // Channel bit IDs must be in sync with the channel's apperance in channels_
732 int id = 0;
733 for (data::DecodeChannel &ch : channels_)
734 if (ch.assigned_signal)
735 ch.bit_id = id++;
47747218
SA
736}
737
ed535cd7 738void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
47747218 739{
27a3f09b
SA
740 // Enforce end to be greater than start
741 if (end <= start)
742 return;
743
ed535cd7 744 // Fetch the channel segments and their data
27a3f09b
SA
745 vector<shared_ptr<LogicSegment> > segments;
746 vector<const uint8_t*> signal_data;
747 vector<uint8_t> signal_in_bytepos;
748 vector<uint8_t> signal_in_bitpos;
749
750 for (data::DecodeChannel &ch : channels_)
751 if (ch.assigned_signal) {
752 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
ed535cd7
SA
753
754 shared_ptr<LogicSegment> segment;
755 try {
756 segment = logic_data->logic_segments().at(segment_id);
30677c13 757 } catch (out_of_range&) {
ed535cd7
SA
758 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
759 << "has no logic segment" << segment_id;
760 return;
761 }
27a3f09b 762 segments.push_back(segment);
b82243f7
SA
763
764 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
765 segment->get_samples(start, end, data);
766 signal_data.push_back(data);
27a3f09b
SA
767
768 const int bitpos = ch.assigned_signal->logic_bit_index();
769 signal_in_bytepos.push_back(bitpos / 8);
770 signal_in_bitpos.push_back(bitpos % 8);
771 }
772
ed535cd7
SA
773
774 shared_ptr<LogicSegment> output_segment;
775 try {
776 output_segment = logic_mux_data_->logic_segments().at(segment_id);
30677c13 777 } catch (out_of_range&) {
ed535cd7
SA
778 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
779 << segment_id << "in mux_logic_samples(), mux segments size is" \
780 << logic_mux_data_->logic_segments().size();
781 return;
782 }
783
27a3f09b 784 // Perform the muxing of signal data into the output data
8a603e13 785 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
27a3f09b
SA
786 unsigned int signal_count = signal_data.size();
787
788 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
789 int bitpos = 0;
790 uint8_t bytepos = 0;
791
8a603e13
SA
792 const int out_sample_pos = sample_cnt * output_segment->unit_size();
793 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
27a3f09b 794 output[out_sample_pos + i] = 0;
47747218 795
27a3f09b
SA
796 for (unsigned int i = 0; i < signal_count; i++) {
797 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
798 const uint8_t in_sample = 1 &
799 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
47747218 800
27a3f09b
SA
801 const uint8_t out_sample = output[out_sample_pos + bytepos];
802
803 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
804
805 bitpos++;
806 if (bitpos > 7) {
807 bitpos = 0;
808 bytepos++;
809 }
810 }
47747218
SA
811 }
812
8a603e13 813 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
27a3f09b
SA
814 delete[] output;
815
816 for (const uint8_t* data : signal_data)
817 delete[] data;
818}
819
820void DecodeSignal::logic_mux_proc()
821{
ed535cd7
SA
822 uint32_t segment_id = 0;
823
8a603e13
SA
824 assert(logic_mux_data_);
825
65efd025
SA
826 // Create initial logic mux segment
827 shared_ptr<LogicSegment> output_segment =
85a70280
SA
828 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
829 logic_mux_unit_size_, 0);
65efd025 830 logic_mux_data_->push_segment(output_segment);
8a603e13
SA
831
832 output_segment->set_samplerate(get_input_samplerate(0));
ed535cd7 833
27a3f09b 834 do {
ed535cd7 835 const uint64_t input_sample_count = get_working_sample_count(segment_id);
8a603e13 836 const uint64_t output_sample_count = output_segment->get_sample_count();
27a3f09b
SA
837
838 const uint64_t samples_to_process =
839 (input_sample_count > output_sample_count) ?
840 (input_sample_count - output_sample_count) : 0;
841
842 // Process the samples if necessary...
843 if (samples_to_process > 0) {
8a603e13 844 const uint64_t unit_size = output_segment->unit_size();
27a3f09b
SA
845 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
846
847 uint64_t processed_samples = 0;
848 do {
849 const uint64_t start_sample = output_sample_count + processed_samples;
850 const uint64_t sample_count =
851 min(samples_to_process - processed_samples, chunk_sample_count);
852
ed535cd7 853 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
27a3f09b
SA
854 processed_samples += sample_count;
855
856 // ...and process the newly muxed logic data
857 decode_input_cond_.notify_one();
858 } while (processed_samples < samples_to_process);
859 }
860
1ec191ed 861 if (samples_to_process == 0) {
ed535cd7
SA
862 // TODO Optimize this by caching the input segment count and only
863 // querying it when the cached value was reached
864 if (segment_id < get_input_segment_count() - 1) {
865 // Process next segment
866 segment_id++;
867
65efd025 868 output_segment =
85a70280
SA
869 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
870 logic_mux_unit_size_, 0);
65efd025 871 logic_mux_data_->push_segment(output_segment);
ba5f2186 872
8a603e13
SA
873 output_segment->set_samplerate(get_input_samplerate(segment_id));
874
ed535cd7
SA
875 } else {
876 // All segments have been processed
877 logic_mux_data_invalid_ = false;
878
879 // Wait for more input
880 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
881 logic_mux_cond_.wait(logic_mux_lock);
882 }
27a3f09b 883 }
1ec191ed 884 } while (!logic_mux_interrupt_);
47747218
SA
885}
886
887void DecodeSignal::decode_data(
8a603e13
SA
888 const int64_t abs_start_samplenum, const int64_t sample_count,
889 const shared_ptr<LogicSegment> input_segment)
47747218 890{
8a603e13 891 const int64_t unit_size = input_segment->unit_size();
27a3f09b 892 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
47747218
SA
893
894 for (int64_t i = abs_start_samplenum;
895 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
896 i += chunk_sample_count) {
897
898 const int64_t chunk_end = min(i + chunk_sample_count,
899 abs_start_samplenum + sample_count);
900
b82243f7
SA
901 int64_t data_size = (chunk_end - i) * unit_size;
902 uint8_t* chunk = new uint8_t[data_size];
8a603e13 903 input_segment->get_samples(i, chunk_end, chunk);
47747218 904
e91883bb 905 if (srd_session_send(srd_session_, i, chunk_end, chunk,
b82243f7 906 data_size, unit_size) != SRD_OK) {
403c3e87 907 set_error_message(tr("Decoder reported an error"));
47747218
SA
908 delete[] chunk;
909 break;
910 }
a3ebd556 911
47747218
SA
912 delete[] chunk;
913
914 {
915 lock_guard<mutex> lock(output_mutex_);
8a603e13 916 segments_.at(current_segment_id_).samples_decoded = chunk_end;
47747218 917 }
1b56c646
SA
918
919 // Notify the frontend that we processed some data and
920 // possibly have new annotations as well
921 new_annotations();
47747218
SA
922 }
923}
924
925void DecodeSignal::decode_proc()
926{
65efd025
SA
927 current_segment_id_ = 0;
928
929 // If there is no input data available yet, wait until it is or we're interrupted
930 if (logic_mux_data_->logic_segments().size() == 0) {
931 unique_lock<mutex> input_wait_lock(input_mutex_);
932 decode_input_cond_.wait(input_wait_lock);
933 }
a3ebd556
SA
934
935 if (decode_interrupt_)
936 return;
937
8a603e13 938 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
8a603e13 939 assert(input_segment);
65efd025
SA
940
941 // Create the initial segment and set its sample rate so that we can pass it to SRD
942 create_decode_segment();
8a603e13 943 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 944 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 945
65efd025
SA
946 start_srd_session();
947
948 uint64_t sample_count = 0;
27a3f09b 949 uint64_t abs_start_samplenum = 0;
47747218 950 do {
27a3f09b
SA
951 // Keep processing new samples until we exhaust the input data
952 do {
767bf4e7 953 lock_guard<mutex> input_lock(input_mutex_);
8a603e13 954 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
27a3f09b
SA
955
956 if (sample_count > 0) {
8a603e13 957 decode_data(abs_start_samplenum, sample_count, input_segment);
27a3f09b
SA
958 abs_start_samplenum += sample_count;
959 }
1b56c646
SA
960 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
961
8a603e13
SA
962 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
963 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
964 // Process next segment
965 current_segment_id_++;
966
967 try {
968 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
30677c13 969 } catch (out_of_range&) {
8a603e13
SA
970 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
971 << current_segment_id_ << "in decode_proc(), mux segments size is" \
972 << logic_mux_data_->logic_segments().size();
973 return;
974 }
975 abs_start_samplenum = 0;
976
65efd025
SA
977 // Create the next segment and set its metadata
978 create_decode_segment();
8a603e13 979 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 980 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 981
90ca4cc8
SA
982 // Reset decoder state but keep the decoder stack intact
983 terminate_srd_session();
8a603e13
SA
984 } else {
985 // All segments have been processed
1b56c646 986 decode_finished();
27a3f09b 987
8a603e13
SA
988 // Wait for new input data or an interrupt was requested
989 unique_lock<mutex> input_wait_lock(input_mutex_);
990 decode_input_cond_.wait(input_wait_lock);
991 }
27a3f09b
SA
992 }
993 } while (error_message_.isEmpty() && !decode_interrupt_);
ce0b6a40
GS
994
995 // Potentially reap decoders when the application no longer is
996 // interested in their (pending) results.
997 if (decode_interrupt_)
998 terminate_srd_session();
e91883bb
SA
999}
1000
1001void DecodeSignal::start_srd_session()
1002{
4349dc21
GS
1003 uint64_t samplerate;
1004
8ce0e732
SA
1005 // If there were stack changes, the session has been destroyed by now, so if
1006 // it hasn't been destroyed, we can just reset and re-use it
ce0b6a40
GS
1007 if (srd_session_) {
1008 // When a decoder stack was created before, re-use it
1009 // for the next stream of input data, after terminating
1010 // potentially still executing operations, and resetting
1011 // internal state. Skip the rather expensive (teardown
1012 // and) construction of another decoder stack.
1013
1014 // TODO Reduce redundancy, use a common code path for
1015 // the meta/cb/start sequence?
1016 terminate_srd_session();
1017 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1018 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1019 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1020 DecodeSignal::annotation_callback, this);
1021 srd_session_start(srd_session_);
1022 return;
1023 }
e91883bb 1024
a3ebd556
SA
1025 // Create the session
1026 srd_session_new(&srd_session_);
1027 assert(srd_session_);
47747218 1028
a3ebd556
SA
1029 // Create the decoders
1030 srd_decoder_inst *prev_di = nullptr;
1031 for (const shared_ptr<decode::Decoder> &dec : stack_) {
1032 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
e91883bb 1033
a3ebd556 1034 if (!di) {
403c3e87 1035 set_error_message(tr("Failed to create decoder instance"));
a3ebd556 1036 srd_session_destroy(srd_session_);
c5f9553c 1037 srd_session_ = nullptr;
a3ebd556
SA
1038 return;
1039 }
e91883bb 1040
a3ebd556
SA
1041 if (prev_di)
1042 srd_inst_stack(srd_session_, prev_di, di);
e91883bb 1043
a3ebd556 1044 prev_di = di;
e91883bb 1045 }
a3ebd556
SA
1046
1047 // Start the session
4349dc21
GS
1048 samplerate = segments_.at(current_segment_id_).samplerate;
1049 if (samplerate)
1050 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1051 g_variant_new_uint64(samplerate));
a3ebd556
SA
1052
1053 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1054 DecodeSignal::annotation_callback, this);
1055
1056 srd_session_start(srd_session_);
e3202557
SA
1057
1058 // We just recreated the srd session, so all stack changes are applied now
1059 stack_config_changed_ = false;
e91883bb 1060}
47747218 1061
ce0b6a40
GS
1062void DecodeSignal::terminate_srd_session()
1063{
1064 // Call the "terminate and reset" routine for the decoder stack
1065 // (if available). This does not harm those stacks which already
1066 // have completed their operation, and reduces response time for
1067 // those stacks which still are processing data while the
1068 // application no longer wants them to.
1069 if (srd_session_)
1070 srd_session_terminate_reset(srd_session_);
1071}
1072
e91883bb
SA
1073void DecodeSignal::stop_srd_session()
1074{
1075 if (srd_session_) {
1076 // Destroy the session
1077 srd_session_destroy(srd_session_);
1078 srd_session_ = nullptr;
8ce0e732
SA
1079
1080 // Mark the decoder instances as non-existant since they were deleted
1081 for (const shared_ptr<decode::Decoder> &dec : stack_)
1082 dec->invalidate_decoder_inst();
e91883bb 1083 }
47747218
SA
1084}
1085
a8a9222d
SA
1086void DecodeSignal::connect_input_notifiers()
1087{
1088 // Disconnect the notification slot from the previous set of signals
1b56c646 1089 disconnect(this, SLOT(on_data_cleared()));
a8a9222d
SA
1090 disconnect(this, SLOT(on_data_received()));
1091
1092 // Connect the currently used signals to our slot
1093 for (data::DecodeChannel &ch : channels_) {
1094 if (!ch.assigned_signal)
1095 continue;
1096
1b56c646
SA
1097 const data::SignalBase *signal = ch.assigned_signal;
1098 connect(signal, SIGNAL(samples_cleared()),
1099 this, SLOT(on_data_cleared()));
b10b58f4 1100 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
a8a9222d
SA
1101 this, SLOT(on_data_received()));
1102 }
1103}
1104
65efd025 1105void DecodeSignal::create_decode_segment()
4913560f 1106{
65efd025
SA
1107 // Create annotation segment
1108 segments_.emplace_back(DecodeSegment());
72435789 1109
65efd025
SA
1110 // Add annotation classes
1111 for (const shared_ptr<decode::Decoder> &dec : stack_) {
1112 assert(dec);
1113 const srd_decoder *const decc = dec->decoder();
1114 assert(dec->decoder());
4913560f 1115
65efd025
SA
1116 // Add a row for the decoder if it doesn't have a row list
1117 if (!decc->annotation_rows)
1118 (segments_.back().annotation_rows)[Row(decc)] =
1119 decode::RowData();
4913560f 1120
65efd025
SA
1121 // Add the decoder rows
1122 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
1123 const srd_decoder_annotation_row *const ann_row =
1124 (srd_decoder_annotation_row *)l->data;
1125 assert(ann_row);
4913560f 1126
65efd025 1127 const Row row(decc, ann_row);
4913560f 1128
65efd025
SA
1129 // Add a new empty row data object
1130 (segments_.back().annotation_rows)[row] =
1131 decode::RowData();
4913560f
SA
1132 }
1133 }
1134}
1135
47747218
SA
1136void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1137{
1138 assert(pdata);
b21501d6 1139 assert(decode_signal);
47747218
SA
1140
1141 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1142 assert(ds);
1143
1144 lock_guard<mutex> lock(ds->output_mutex_);
1145
47747218
SA
1146 // Find the row
1147 assert(pdata->pdo);
1148 assert(pdata->pdo->di);
1149 const srd_decoder *const decc = pdata->pdo->di->decoder;
1150 assert(decc);
1151
1becee23
UH
1152 const srd_proto_data_annotation *const pda =
1153 (const srd_proto_data_annotation*)pdata->data;
1154 assert(pda);
1155
8a603e13 1156 auto row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.end();
47747218
SA
1157
1158 // Try looking up the sub-row of this class
1becee23
UH
1159 const auto format = pda->ann_class;
1160 const auto r = ds->class_rows_.find(make_pair(decc, format));
47747218 1161 if (r != ds->class_rows_.end())
8a603e13 1162 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find((*r).second);
47747218
SA
1163 else {
1164 // Failing that, use the decoder as a key
8a603e13 1165 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find(Row(decc));
47747218
SA
1166 }
1167
8a603e13 1168 if (row_iter == ds->segments_.at(ds->current_segment_id_).annotation_rows.end()) {
47747218 1169 qDebug() << "Unexpected annotation: decoder = " << decc <<
1becee23 1170 ", format = " << format;
47747218
SA
1171 assert(false);
1172 return;
1173 }
1174
1175 // Add the annotation
1becee23 1176 (*row_iter).second.emplace_annotation(pdata);
47747218
SA
1177}
1178
1179void DecodeSignal::on_capture_state_changed(int state)
1180{
1181 // If a new acquisition was started, we need to start decoding from scratch
ba5f2186
SA
1182 if (state == Session::Running) {
1183 logic_mux_data_invalid_ = true;
47747218 1184 begin_decode();
ba5f2186 1185 }
47747218
SA
1186}
1187
1b56c646
SA
1188void DecodeSignal::on_data_cleared()
1189{
1190 reset_decode();
1191}
1192
47747218
SA
1193void DecodeSignal::on_data_received()
1194{
1b56c646
SA
1195 if (!logic_mux_thread_.joinable())
1196 begin_decode();
1197 else
1198 logic_mux_cond_.notify_one();
47747218
SA
1199}
1200
ad908057
SA
1201} // namespace data
1202} // namespace pv