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