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