]> sigrok.org Git - pulseview.git/blame - pv/data/decodesignal.cpp
DecodeSignal: Fix flawed PD stack restoration
[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;
ad908057 39using std::shared_ptr;
47747218
SA
40using std::unique_lock;
41using pv::data::decode::Annotation;
ad908057 42using pv::data::decode::Decoder;
ecd07c20 43using pv::data::decode::Row;
ad908057
SA
44
45namespace pv {
46namespace data {
47
47747218
SA
48const double DecodeSignal::DecodeMargin = 1.0;
49const double DecodeSignal::DecodeThreshold = 0.2;
3fbddf7f 50const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
ad908057 51
ad908057 52
47747218
SA
53DecodeSignal::DecodeSignal(pv::Session &session) :
54 SignalBase(nullptr, SignalBase::DecodeChannel),
55 session_(session),
e91883bb 56 srd_session_(nullptr),
47747218
SA
57 logic_mux_data_invalid_(false),
58 start_time_(0),
59 samplerate_(0),
47747218
SA
60 samples_decoded_(0),
61 frame_complete_(false)
ad908057 62{
47747218
SA
63 connect(&session_, SIGNAL(capture_state_changed(int)),
64 this, SLOT(on_capture_state_changed(int)));
47747218
SA
65
66 set_name(tr("Empty decoder signal"));
ad908057
SA
67}
68
47747218 69DecodeSignal::~DecodeSignal()
ad908057 70{
1b56c646 71 reset_decode();
ad908057
SA
72}
73
47747218 74const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
ecd07c20 75{
47747218 76 return stack_;
ecd07c20
SA
77}
78
c8e60bdf 79void DecodeSignal::stack_decoder(const srd_decoder *decoder)
ad908057
SA
80{
81 assert(decoder);
762ab7a4
SA
82 const shared_ptr<Decoder> dec = make_shared<decode::Decoder>(decoder);
83
84 stack_.push_back(dec);
47747218
SA
85
86 // Set name if this decoder is the first in the list
87 if (stack_.size() == 1)
88 set_name(QString::fromUtf8(decoder->name));
132a5c6d 89
27a3f09b 90 // Include the newly created decode channels in the channel lists
9f97b357 91 update_channel_list();
132a5c6d 92
762ab7a4 93 auto_assign_signals(dec);
27a3f09b 94 commit_decoder_channels();
47747218 95 begin_decode();
ad908057
SA
96}
97
98void DecodeSignal::remove_decoder(int index)
99{
47747218
SA
100 assert(index >= 0);
101 assert(index < (int)stack_.size());
102
103 // Find the decoder in the stack
104 auto iter = stack_.begin();
105 for (int i = 0; i < index; i++, iter++)
106 assert(iter != stack_.end());
107
108 // Delete the element
109 stack_.erase(iter);
110
111 // Update channels and decoded data
9f97b357 112 update_channel_list();
47747218 113 begin_decode();
ad908057
SA
114}
115
116bool DecodeSignal::toggle_decoder_visibility(int index)
117{
47747218 118 auto iter = stack_.cbegin();
ad908057 119 for (int i = 0; i < index; i++, iter++)
47747218 120 assert(iter != stack_.end());
ad908057
SA
121
122 shared_ptr<Decoder> dec = *iter;
123
124 // Toggle decoder visibility
125 bool state = false;
126 if (dec) {
127 state = !dec->shown();
128 dec->show(state);
129 }
130
131 return state;
132}
133
47747218
SA
134void DecodeSignal::reset_decode()
135{
1b56c646
SA
136 if (decode_thread_.joinable()) {
137 decode_interrupt_ = true;
138 decode_input_cond_.notify_one();
139 decode_thread_.join();
140 }
141
142 if (logic_mux_thread_.joinable()) {
143 logic_mux_interrupt_ = true;
144 logic_mux_cond_.notify_one();
145 logic_mux_thread_.join();
146 }
147
e91883bb
SA
148 stop_srd_session();
149
47747218
SA
150 frame_complete_ = false;
151 samples_decoded_ = 0;
152 error_message_ = QString();
1b56c646 153
47747218
SA
154 rows_.clear();
155 class_rows_.clear();
1b56c646
SA
156
157 logic_mux_data_.reset();
158 logic_mux_data_invalid_ = true;
47747218
SA
159}
160
946b52e1
SA
161void DecodeSignal::begin_decode()
162{
47747218
SA
163 if (decode_thread_.joinable()) {
164 decode_interrupt_ = true;
165 decode_input_cond_.notify_one();
166 decode_thread_.join();
167 }
168
169 if (logic_mux_thread_.joinable()) {
170 logic_mux_interrupt_ = true;
171 logic_mux_cond_.notify_one();
172 logic_mux_thread_.join();
173 }
174
175 reset_decode();
176
27a3f09b
SA
177 if (stack_.size() == 0) {
178 error_message_ = tr("No decoders");
179 return;
180 }
181
182 assert(channels_.size() > 0);
183
184 if (get_assigned_signal_count() == 0) {
185 error_message_ = tr("There are no channels assigned to this decoder");
186 return;
187 }
188
04627946
SA
189 // Make sure that all assigned channels still provide logic data
190 // (can happen when a converted signal was assigned but the
191 // conversion removed in the meanwhile)
192 for (data::DecodeChannel &ch : channels_)
193 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
194 ch.assigned_signal = nullptr;
195
47747218
SA
196 // Check that all decoders have the required channels
197 for (const shared_ptr<decode::Decoder> &dec : stack_)
198 if (!dec->have_required_channels()) {
199 error_message_ = tr("One or more required channels "
200 "have not been specified");
201 return;
202 }
203
204 // Add annotation classes
205 for (const shared_ptr<decode::Decoder> &dec : stack_) {
206 assert(dec);
207 const srd_decoder *const decc = dec->decoder();
208 assert(dec->decoder());
209
210 // Add a row for the decoder if it doesn't have a row list
211 if (!decc->annotation_rows)
212 rows_[Row(decc)] = decode::RowData();
213
214 // Add the decoder rows
215 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
216 const srd_decoder_annotation_row *const ann_row =
217 (srd_decoder_annotation_row *)l->data;
218 assert(ann_row);
219
220 const Row row(decc, ann_row);
221
222 // Add a new empty row data object
223 rows_[row] = decode::RowData();
224
225 // Map out all the classes
226 for (const GSList *ll = ann_row->ann_classes;
227 ll; ll = ll->next)
228 class_rows_[make_pair(decc,
229 GPOINTER_TO_INT(ll->data))] = row;
230 }
231 }
232
27a3f09b
SA
233 // Free the logic data and its segment(s) if it needs to be updated
234 if (logic_mux_data_invalid_)
235 logic_mux_data_.reset();
236
237 if (!logic_mux_data_) {
238 const int64_t ch_count = get_assigned_signal_count();
239 const int64_t unit_size = (ch_count + 7) / 8;
240 logic_mux_data_ = make_shared<Logic>(ch_count);
241 segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
242 logic_mux_data_->push_segment(segment_);
243 }
47747218 244
27a3f09b
SA
245 // Make sure the logic output data is complete and up-to-date
246 logic_mux_interrupt_ = false;
247 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
248
249 // Decode the muxed logic data
47747218
SA
250 decode_interrupt_ = false;
251 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
a8a9222d
SA
252
253 // Receive notifications when new sample data is available
254 connect_input_notifiers();
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;
27a3f09b 295 commit_decoder_channels();
47747218 296 channels_updated();
132a5c6d
SA
297 }
298}
299
9f97b357
SA
300void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
301{
302 for (data::DecodeChannel &ch : channels_)
47747218 303 if (ch.id == channel_id) {
9f97b357 304 ch.assigned_signal = signal;
47747218
SA
305 logic_mux_data_invalid_ = true;
306 }
9f97b357 307
27a3f09b 308 commit_decoder_channels();
9f97b357 309 channels_updated();
47747218 310 begin_decode();
9f97b357
SA
311}
312
27a3f09b
SA
313int DecodeSignal::get_assigned_signal_count() const
314{
315 // Count all channels that have a signal assigned to them
316 return count_if(channels_.begin(), channels_.end(),
317 [](data::DecodeChannel ch) { return ch.assigned_signal; });
318}
319
9f97b357
SA
320void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
321{
322 for (data::DecodeChannel &ch : channels_)
323 if (ch.id == channel_id)
324 ch.initial_pin_state = init_state;
325
326 channels_updated();
327
47747218 328 begin_decode();
9f97b357
SA
329}
330
ff83d980
SA
331double DecodeSignal::samplerate() const
332{
47747218 333 return samplerate_;
ff83d980
SA
334}
335
336const pv::util::Timestamp& DecodeSignal::start_time() const
337{
47747218 338 return start_time_;
ff83d980
SA
339}
340
0c5fe73e
SA
341int64_t DecodeSignal::get_working_sample_count() const
342{
343 // The working sample count is the highest sample number for
344 // which all used signals have data available, so go through
345 // all channels and use the lowest overall sample count of the
346 // current segment
347
348 // TODO Currently, we assume only a single segment exists
349
350 int64_t count = std::numeric_limits<int64_t>::max();
351 bool no_signals_assigned = true;
352
353 for (const data::DecodeChannel &ch : channels_)
354 if (ch.assigned_signal) {
355 no_signals_assigned = false;
356
357 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
358 if (!logic_data || logic_data->logic_segments().empty())
359 return 0;
360
361 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
362 count = min(count, (int64_t)segment->get_sample_count());
363 }
364
365 return (no_signals_assigned ? 0 : count);
366}
367
368int64_t DecodeSignal::get_decoded_sample_count() const
ff83d980 369{
47747218
SA
370 lock_guard<mutex> decode_lock(output_mutex_);
371 return samples_decoded_;
ff83d980
SA
372}
373
ecd07c20
SA
374vector<Row> DecodeSignal::visible_rows() const
375{
47747218
SA
376 lock_guard<mutex> lock(output_mutex_);
377
378 vector<Row> rows;
379
380 for (const shared_ptr<decode::Decoder> &dec : stack_) {
381 assert(dec);
382 if (!dec->shown())
383 continue;
384
385 const srd_decoder *const decc = dec->decoder();
386 assert(dec->decoder());
387
388 // Add a row for the decoder if it doesn't have a row list
389 if (!decc->annotation_rows)
390 rows.emplace_back(decc);
391
392 // Add the decoder rows
393 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
394 const srd_decoder_annotation_row *const ann_row =
395 (srd_decoder_annotation_row *)l->data;
396 assert(ann_row);
397 rows.emplace_back(decc, ann_row);
398 }
399 }
400
401 return rows;
ecd07c20
SA
402}
403
404void DecodeSignal::get_annotation_subset(
405 vector<pv::data::decode::Annotation> &dest,
406 const decode::Row &row, uint64_t start_sample,
407 uint64_t end_sample) const
408{
47747218
SA
409 lock_guard<mutex> lock(output_mutex_);
410
411 const auto iter = rows_.find(row);
412 if (iter != rows_.end())
413 (*iter).second.get_annotation_subset(dest,
414 start_sample, end_sample);
415}
416
417void DecodeSignal::save_settings(QSettings &settings) const
418{
419 SignalBase::save_settings(settings);
420
c8e60bdf
SA
421 settings.setValue("decoders", (int)(stack_.size()));
422
8b5ea5a1 423 // Save decoder stack
c8e60bdf
SA
424 int decoder_idx = 0;
425 for (shared_ptr<decode::Decoder> decoder : stack_) {
426 settings.beginGroup("decoder" + QString::number(decoder_idx++));
427
428 settings.setValue("id", decoder->decoder()->id);
429
d3feec23
SA
430 // Save decoder options
431 const map<string, GVariant*>& options = decoder->options();
432
433 settings.setValue("options", (int)options.size());
434
435 // Note: decode::Decoder::options() returns only the options
436 // that differ from the default. See binding::Decoder::getter()
437 int i = 0;
438 for (auto option : options) {
439 settings.beginGroup("option" + QString::number(i));
440 settings.setValue("name", QString::fromStdString(option.first));
441 GlobalSettings::store_gvariant(settings, option.second);
442 settings.endGroup();
443 i++;
444 }
445
c8e60bdf
SA
446 settings.endGroup();
447 }
448
8b5ea5a1
SA
449 // Save channel mapping
450 settings.setValue("channels", (int)channels_.size());
451
452 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
453 auto channel = find_if(channels_.begin(), channels_.end(),
454 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
455
456 if (channel == channels_.end()) {
457 qDebug() << "ERROR: Gap in channel index:" << channel_id;
458 continue;
459 }
460
461 settings.beginGroup("channel" + QString::number(channel_id));
462
463 settings.setValue("name", channel->name); // Useful for debugging
464 settings.setValue("initial_pin_state", channel->initial_pin_state);
465
466 if (channel->assigned_signal)
467 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
468
469 settings.endGroup();
470 }
47747218
SA
471}
472
473void DecodeSignal::restore_settings(QSettings &settings)
474{
475 SignalBase::restore_settings(settings);
476
8b5ea5a1 477 // Restore decoder stack
c8e60bdf
SA
478 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
479
480 int decoders = settings.value("decoders").toInt();
481
482 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
483 settings.beginGroup("decoder" + QString::number(decoder_idx));
484
485 QString id = settings.value("id").toString();
486
487 for (GSList *entry = dec_list; entry; entry = entry->next) {
488 const srd_decoder *dec = (srd_decoder*)entry->data;
489 if (!dec)
490 continue;
491
492 if (QString::fromUtf8(dec->id) == id) {
d3feec23
SA
493 shared_ptr<decode::Decoder> decoder =
494 make_shared<decode::Decoder>(dec);
495
496 stack_.push_back(decoder);
497
498 // Restore decoder options that differ from their default
499 int options = settings.value("options").toInt();
500
501 for (int i = 0; i < options; i++) {
502 settings.beginGroup("option" + QString::number(i));
503 QString name = settings.value("name").toString();
504 GVariant *value = GlobalSettings::restore_gvariant(settings);
505 decoder->set_option(name.toUtf8(), value);
506 settings.endGroup();
507 }
c8e60bdf
SA
508
509 // Include the newly created decode channels in the channel lists
510 update_channel_list();
4ca06ec3 511 commit_decoder_channels();
c8e60bdf
SA
512 break;
513 }
514 }
515
516 settings.endGroup();
4ca06ec3 517 channels_updated();
c8e60bdf
SA
518 }
519
8b5ea5a1
SA
520 // Restore channel mapping
521 unsigned int channels = settings.value("channels").toInt();
522
523 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
524 session_.signalbases();
525
526 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
527 auto channel = find_if(channels_.begin(), channels_.end(),
528 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
529
530 if (channel == channels_.end()) {
531 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
532 continue;
533 }
534
535 settings.beginGroup("channel" + QString::number(channel_id));
536
537 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
538
539 for (shared_ptr<data::SignalBase> signal : signalbases)
540 if (signal->name() == assigned_signal_name)
541 channel->assigned_signal = signal.get();
542
543 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
544
545 settings.endGroup();
546 }
547
548 begin_decode();
47747218
SA
549}
550
9f97b357
SA
551void DecodeSignal::update_channel_list()
552{
47747218 553 vector<data::DecodeChannel> prev_channels = channels_;
9f97b357
SA
554 channels_.clear();
555
556 uint16_t id = 0;
557
558 // Copy existing entries, create new as needed
47747218 559 for (shared_ptr<Decoder> decoder : stack_) {
9f97b357
SA
560 const srd_decoder* srd_d = decoder->decoder();
561 const GSList *l;
562
563 // Mandatory channels
564 for (l = srd_d->channels; l; l = l->next) {
565 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
566 bool ch_added = false;
567
568 // Copy but update ID if this channel was in the list before
47747218 569 for (data::DecodeChannel &ch : prev_channels)
9f97b357
SA
570 if (ch.pdch_ == pdch) {
571 ch.id = id++;
572 channels_.push_back(ch);
573 ch_added = true;
574 break;
575 }
576
577 if (!ch_added) {
578 // Create new entry without a mapped signal
579 data::DecodeChannel ch = {id++, false, nullptr,
580 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
581 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
582 channels_.push_back(ch);
583 }
584 }
585
586 // Optional channels
587 for (l = srd_d->opt_channels; l; l = l->next) {
588 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
589 bool ch_added = false;
590
591 // Copy but update ID if this channel was in the list before
47747218 592 for (data::DecodeChannel &ch : prev_channels)
9f97b357
SA
593 if (ch.pdch_ == pdch) {
594 ch.id = id++;
595 channels_.push_back(ch);
596 ch_added = true;
597 break;
598 }
599
600 if (!ch_added) {
601 // Create new entry without a mapped signal
602 data::DecodeChannel ch = {id++, true, nullptr,
603 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
604 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
605 channels_.push_back(ch);
606 }
607 }
608 }
609
47747218
SA
610 // Invalidate the logic output data if the channel assignment changed
611 if (prev_channels.size() != channels_.size()) {
612 // The number of channels changed, there's definitely a difference
613 logic_mux_data_invalid_ = true;
614 } else {
615 // Same number but assignment may still differ, so compare all channels
616 for (size_t i = 0; i < channels_.size(); i++) {
617 const data::DecodeChannel &p_ch = prev_channels[i];
618 const data::DecodeChannel &ch = channels_[i];
619
620 if ((p_ch.pdch_ != ch.pdch_) ||
621 (p_ch.assigned_signal != ch.assigned_signal)) {
622 logic_mux_data_invalid_ = true;
623 break;
624 }
625 }
626
627 }
628
9f97b357
SA
629 channels_updated();
630}
631
27a3f09b 632void DecodeSignal::commit_decoder_channels()
ad908057 633{
27a3f09b
SA
634 // Submit channel list to every decoder, containing only the relevant channels
635 for (shared_ptr<decode::Decoder> dec : stack_) {
636 vector<data::DecodeChannel*> channel_list;
637
638 for (data::DecodeChannel &ch : channels_)
639 if (ch.decoder_ == dec)
640 channel_list.push_back(&ch);
47747218 641
27a3f09b
SA
642 dec->set_channels(channel_list);
643 }
47747218
SA
644}
645
27a3f09b 646void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
47747218 647{
27a3f09b
SA
648 // Enforce end to be greater than start
649 if (end <= start)
650 return;
651
652 // Fetch all segments and their data
653 // TODO Currently, we assume only a single segment exists
654 vector<shared_ptr<LogicSegment> > segments;
655 vector<const uint8_t*> signal_data;
656 vector<uint8_t> signal_in_bytepos;
657 vector<uint8_t> signal_in_bitpos;
658
659 for (data::DecodeChannel &ch : channels_)
660 if (ch.assigned_signal) {
661 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
662 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
663 segments.push_back(segment);
b82243f7
SA
664
665 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
666 segment->get_samples(start, end, data);
667 signal_data.push_back(data);
27a3f09b
SA
668
669 const int bitpos = ch.assigned_signal->logic_bit_index();
670 signal_in_bytepos.push_back(bitpos / 8);
671 signal_in_bitpos.push_back(bitpos % 8);
672 }
673
674 // Perform the muxing of signal data into the output data
675 uint8_t* output = new uint8_t[(end - start) * segment_->unit_size()];
676 unsigned int signal_count = signal_data.size();
677
678 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
679 int bitpos = 0;
680 uint8_t bytepos = 0;
681
682 const int out_sample_pos = sample_cnt * segment_->unit_size();
683 for (unsigned int i = 0; i < segment_->unit_size(); i++)
684 output[out_sample_pos + i] = 0;
47747218 685
27a3f09b
SA
686 for (unsigned int i = 0; i < signal_count; i++) {
687 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
688 const uint8_t in_sample = 1 &
689 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
47747218 690
27a3f09b
SA
691 const uint8_t out_sample = output[out_sample_pos + bytepos];
692
693 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
694
695 bitpos++;
696 if (bitpos > 7) {
697 bitpos = 0;
698 bytepos++;
699 }
700 }
47747218
SA
701 }
702
27a3f09b
SA
703 segment_->append_payload(output, (end - start) * segment_->unit_size());
704 delete[] output;
705
706 for (const uint8_t* data : signal_data)
707 delete[] data;
708}
709
710void DecodeSignal::logic_mux_proc()
711{
712 do {
27a3f09b
SA
713 const uint64_t input_sample_count = get_working_sample_count();
714 const uint64_t output_sample_count = segment_->get_sample_count();
715
716 const uint64_t samples_to_process =
717 (input_sample_count > output_sample_count) ?
718 (input_sample_count - output_sample_count) : 0;
719
720 // Process the samples if necessary...
721 if (samples_to_process > 0) {
722 const uint64_t unit_size = segment_->unit_size();
723 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
724
725 uint64_t processed_samples = 0;
726 do {
727 const uint64_t start_sample = output_sample_count + processed_samples;
728 const uint64_t sample_count =
729 min(samples_to_process - processed_samples, chunk_sample_count);
730
731 mux_logic_samples(start_sample, start_sample + sample_count);
732 processed_samples += sample_count;
733
734 // ...and process the newly muxed logic data
735 decode_input_cond_.notify_one();
736 } while (processed_samples < samples_to_process);
737 }
738
1ec191ed 739 if (samples_to_process == 0) {
27a3f09b
SA
740 // Wait for more input
741 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
742 logic_mux_cond_.wait(logic_mux_lock);
743 }
1ec191ed 744 } while (!logic_mux_interrupt_);
27a3f09b
SA
745
746 // No more input data and session is stopped, let the decode thread
747 // process any pending data, terminate and release the global SRD mutex
748 // in order to let other decoders run
749 decode_input_cond_.notify_one();
47747218
SA
750}
751
a3ebd556
SA
752void DecodeSignal::query_input_metadata()
753{
754 // Update the samplerate and start time because we cannot start
755 // the libsrd session without the current samplerate
756
757 // TODO Currently we assume all channels have the same sample rate
758 // and start time
759 bool samplerate_valid = false;
8ebf8079
SA
760 data::DecodeChannel *any_channel;
761 shared_ptr<Logic> logic_data;
a3ebd556 762
8ebf8079
SA
763 do {
764 any_channel = &(*find_if(channels_.begin(), channels_.end(),
765 [](data::DecodeChannel ch) { return ch.assigned_signal; }));
a3ebd556 766
8ebf8079
SA
767 logic_data = any_channel->assigned_signal->logic_data();
768
769 if (!logic_data) {
770 // Wait until input data is available or an interrupt was requested
771 unique_lock<mutex> input_wait_lock(input_mutex_);
772 decode_input_cond_.wait(input_wait_lock);
773 }
774 } while (!logic_data && !decode_interrupt_);
775
776 if (decode_interrupt_)
777 return;
a3ebd556
SA
778
779 do {
780 if (!logic_data->logic_segments().empty()) {
781 shared_ptr<LogicSegment> first_segment =
782 any_channel->assigned_signal->logic_data()->logic_segments().front();
783 start_time_ = first_segment->start_time();
784 samplerate_ = first_segment->samplerate();
785 if (samplerate_ > 0)
786 samplerate_valid = true;
787 }
788
1ec191ed
SA
789 if (!samplerate_valid) {
790 // Wait until input data is available or an interrupt was requested
791 unique_lock<mutex> input_wait_lock(input_mutex_);
792 decode_input_cond_.wait(input_wait_lock);
793 }
a3ebd556
SA
794 } while (!samplerate_valid && !decode_interrupt_);
795}
796
47747218 797void DecodeSignal::decode_data(
e91883bb 798 const int64_t abs_start_samplenum, const int64_t sample_count)
47747218 799{
27a3f09b
SA
800 const int64_t unit_size = segment_->unit_size();
801 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
47747218
SA
802
803 for (int64_t i = abs_start_samplenum;
804 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
805 i += chunk_sample_count) {
806
807 const int64_t chunk_end = min(i + chunk_sample_count,
808 abs_start_samplenum + sample_count);
809
b82243f7
SA
810 int64_t data_size = (chunk_end - i) * unit_size;
811 uint8_t* chunk = new uint8_t[data_size];
812 segment_->get_samples(i, chunk_end, chunk);
47747218 813
e91883bb 814 if (srd_session_send(srd_session_, i, chunk_end, chunk,
b82243f7 815 data_size, unit_size) != SRD_OK) {
47747218
SA
816 error_message_ = tr("Decoder reported an error");
817 delete[] chunk;
818 break;
819 }
a3ebd556 820
47747218
SA
821 delete[] chunk;
822
823 {
824 lock_guard<mutex> lock(output_mutex_);
825 samples_decoded_ = chunk_end;
826 }
1b56c646
SA
827
828 // Notify the frontend that we processed some data and
829 // possibly have new annotations as well
830 new_annotations();
47747218
SA
831 }
832}
833
834void DecodeSignal::decode_proc()
835{
a3ebd556
SA
836 query_input_metadata();
837
838 if (decode_interrupt_)
839 return;
840
e91883bb 841 start_srd_session();
47747218 842
27a3f09b
SA
843 uint64_t sample_count;
844 uint64_t abs_start_samplenum = 0;
47747218 845 do {
27a3f09b
SA
846 // Keep processing new samples until we exhaust the input data
847 do {
767bf4e7
SA
848 lock_guard<mutex> input_lock(input_mutex_);
849 sample_count = segment_->get_sample_count() - abs_start_samplenum;
27a3f09b
SA
850
851 if (sample_count > 0) {
e91883bb 852 decode_data(abs_start_samplenum, sample_count);
27a3f09b
SA
853 abs_start_samplenum += sample_count;
854 }
1b56c646
SA
855 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
856
857 if (error_message_.isEmpty() && !decode_interrupt_) {
858 if (sample_count == 0)
859 decode_finished();
27a3f09b 860
a3ebd556 861 // Wait for new input data or an interrupt was requested
27a3f09b
SA
862 unique_lock<mutex> input_wait_lock(input_mutex_);
863 decode_input_cond_.wait(input_wait_lock);
864 }
865 } while (error_message_.isEmpty() && !decode_interrupt_);
e91883bb
SA
866}
867
868void DecodeSignal::start_srd_session()
869{
a3ebd556
SA
870 if (srd_session_)
871 stop_srd_session();
e91883bb 872
a3ebd556
SA
873 // Create the session
874 srd_session_new(&srd_session_);
875 assert(srd_session_);
47747218 876
a3ebd556
SA
877 // Create the decoders
878 srd_decoder_inst *prev_di = nullptr;
879 for (const shared_ptr<decode::Decoder> &dec : stack_) {
880 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
e91883bb 881
a3ebd556
SA
882 if (!di) {
883 error_message_ = tr("Failed to create decoder instance");
884 srd_session_destroy(srd_session_);
885 return;
886 }
e91883bb 887
a3ebd556
SA
888 if (prev_di)
889 srd_inst_stack(srd_session_, prev_di, di);
e91883bb 890
a3ebd556 891 prev_di = di;
e91883bb 892 }
a3ebd556
SA
893
894 // Start the session
895 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
896 g_variant_new_uint64(samplerate_));
897
898 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
899 DecodeSignal::annotation_callback, this);
900
901 srd_session_start(srd_session_);
e91883bb 902}
47747218 903
e91883bb
SA
904void DecodeSignal::stop_srd_session()
905{
906 if (srd_session_) {
907 // Destroy the session
908 srd_session_destroy(srd_session_);
909 srd_session_ = nullptr;
910 }
47747218
SA
911}
912
a8a9222d
SA
913void DecodeSignal::connect_input_notifiers()
914{
915 // Disconnect the notification slot from the previous set of signals
1b56c646 916 disconnect(this, SLOT(on_data_cleared()));
a8a9222d
SA
917 disconnect(this, SLOT(on_data_received()));
918
919 // Connect the currently used signals to our slot
920 for (data::DecodeChannel &ch : channels_) {
921 if (!ch.assigned_signal)
922 continue;
923
1b56c646
SA
924 const data::SignalBase *signal = ch.assigned_signal;
925 connect(signal, SIGNAL(samples_cleared()),
926 this, SLOT(on_data_cleared()));
927 connect(signal, SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
a8a9222d
SA
928 this, SLOT(on_data_received()));
929 }
930}
931
47747218
SA
932void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
933{
934 assert(pdata);
b21501d6 935 assert(decode_signal);
47747218
SA
936
937 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
938 assert(ds);
939
940 lock_guard<mutex> lock(ds->output_mutex_);
941
942 const decode::Annotation a(pdata);
943
944 // Find the row
945 assert(pdata->pdo);
946 assert(pdata->pdo->di);
947 const srd_decoder *const decc = pdata->pdo->di->decoder;
948 assert(decc);
949
950 auto row_iter = ds->rows_.end();
951
952 // Try looking up the sub-row of this class
953 const auto r = ds->class_rows_.find(make_pair(decc, a.format()));
954 if (r != ds->class_rows_.end())
955 row_iter = ds->rows_.find((*r).second);
956 else {
957 // Failing that, use the decoder as a key
958 row_iter = ds->rows_.find(Row(decc));
959 }
960
961 assert(row_iter != ds->rows_.end());
962 if (row_iter == ds->rows_.end()) {
963 qDebug() << "Unexpected annotation: decoder = " << decc <<
964 ", format = " << a.format();
965 assert(false);
966 return;
967 }
968
969 // Add the annotation
970 (*row_iter).second.push_annotation(a);
47747218
SA
971}
972
973void DecodeSignal::on_capture_state_changed(int state)
974{
975 // If a new acquisition was started, we need to start decoding from scratch
976 if (state == Session::Running)
977 begin_decode();
978}
979
1b56c646
SA
980void DecodeSignal::on_data_cleared()
981{
982 reset_decode();
983}
984
47747218
SA
985void DecodeSignal::on_data_received()
986{
1b56c646
SA
987 if (!logic_mux_thread_.joinable())
988 begin_decode();
989 else
990 logic_mux_cond_.notify_one();
47747218
SA
991}
992
ad908057
SA
993} // namespace data
994} // namespace pv