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