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