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