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