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