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