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