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