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