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