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