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