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