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