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