]> sigrok.org Git - pulseview.git/blob - pv/data/decodesignal.cpp
Fix #831 by saving/restoring PD options
[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::shared_ptr;
40 using std::unique_lock;
41 using pv::data::decode::Annotation;
42 using pv::data::decode::Decoder;
43 using pv::data::decode::Row;
44
45 namespace pv {
46 namespace data {
47
48 const double DecodeSignal::DecodeMargin = 1.0;
49 const double DecodeSignal::DecodeThreshold = 0.2;
50 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
51
52 mutex DecodeSignal::global_srd_mutex_;
53
54
55 DecodeSignal::DecodeSignal(pv::Session &session) :
56         SignalBase(nullptr, SignalBase::DecodeChannel),
57         session_(session),
58         srd_session_(nullptr),
59         logic_mux_data_invalid_(false),
60         start_time_(0),
61         samplerate_(0),
62         samples_decoded_(0),
63         frame_complete_(false)
64 {
65         connect(&session_, SIGNAL(capture_state_changed(int)),
66                 this, SLOT(on_capture_state_changed(int)));
67
68         set_name(tr("Empty decoder signal"));
69 }
70
71 DecodeSignal::~DecodeSignal()
72 {
73         reset_decode();
74 }
75
76 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
77 {
78         return stack_;
79 }
80
81 void DecodeSignal::stack_decoder(const srd_decoder *decoder)
82 {
83         assert(decoder);
84         stack_.push_back(make_shared<decode::Decoder>(decoder));
85
86         // Set name if this decoder is the first in the list
87         if (stack_.size() == 1)
88                 set_name(QString::fromUtf8(decoder->name));
89
90         // Include the newly created decode channels in the channel lists
91         update_channel_list();
92
93         auto_assign_signals();
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         update_channel_list();
113         begin_decode();
114 }
115
116 bool DecodeSignal::toggle_decoder_visibility(int index)
117 {
118         auto iter = stack_.cbegin();
119         for (int i = 0; i < index; i++, iter++)
120                 assert(iter != stack_.end());
121
122         shared_ptr<Decoder> dec = *iter;
123
124         // Toggle decoder visibility
125         bool state = false;
126         if (dec) {
127                 state = !dec->shown();
128                 dec->show(state);
129         }
130
131         return state;
132 }
133
134 void DecodeSignal::reset_decode()
135 {
136         if (decode_thread_.joinable()) {
137                 decode_interrupt_ = true;
138                 decode_input_cond_.notify_one();
139                 decode_thread_.join();
140         }
141
142         if (logic_mux_thread_.joinable()) {
143                 logic_mux_interrupt_ = true;
144                 logic_mux_cond_.notify_one();
145                 logic_mux_thread_.join();
146         }
147
148         stop_srd_session();
149
150         frame_complete_ = false;
151         samples_decoded_ = 0;
152         error_message_ = QString();
153
154         rows_.clear();
155         class_rows_.clear();
156
157         logic_mux_data_.reset();
158         logic_mux_data_invalid_ = true;
159 }
160
161 void DecodeSignal::begin_decode()
162 {
163         if (decode_thread_.joinable()) {
164                 decode_interrupt_ = true;
165                 decode_input_cond_.notify_one();
166                 decode_thread_.join();
167         }
168
169         if (logic_mux_thread_.joinable()) {
170                 logic_mux_interrupt_ = true;
171                 logic_mux_cond_.notify_one();
172                 logic_mux_thread_.join();
173         }
174
175         reset_decode();
176
177         if (stack_.size() == 0) {
178                 error_message_ = tr("No decoders");
179                 return;
180         }
181
182         assert(channels_.size() > 0);
183
184         if (get_assigned_signal_count() == 0) {
185                 error_message_ = tr("There are no channels assigned to this decoder");
186                 return;
187         }
188
189         // Make sure that all assigned channels still provide logic data
190         // (can happen when a converted signal was assigned but the
191         // conversion removed in the meanwhile)
192         for (data::DecodeChannel &ch : channels_)
193                 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
194                         ch.assigned_signal = nullptr;
195
196         // Check that all decoders have the required channels
197         for (const shared_ptr<decode::Decoder> &dec : stack_)
198                 if (!dec->have_required_channels()) {
199                         error_message_ = tr("One or more required channels "
200                                 "have not been specified");
201                         return;
202                 }
203
204         // Add annotation classes
205         for (const shared_ptr<decode::Decoder> &dec : stack_) {
206                 assert(dec);
207                 const srd_decoder *const decc = dec->decoder();
208                 assert(dec->decoder());
209
210                 // Add a row for the decoder if it doesn't have a row list
211                 if (!decc->annotation_rows)
212                         rows_[Row(decc)] = decode::RowData();
213
214                 // Add the decoder rows
215                 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
216                         const srd_decoder_annotation_row *const ann_row =
217                                 (srd_decoder_annotation_row *)l->data;
218                         assert(ann_row);
219
220                         const Row row(decc, ann_row);
221
222                         // Add a new empty row data object
223                         rows_[row] = decode::RowData();
224
225                         // Map out all the classes
226                         for (const GSList *ll = ann_row->ann_classes;
227                                 ll; ll = ll->next)
228                                 class_rows_[make_pair(decc,
229                                         GPOINTER_TO_INT(ll->data))] = row;
230                 }
231         }
232
233         // Free the logic data and its segment(s) if it needs to be updated
234         if (logic_mux_data_invalid_)
235                 logic_mux_data_.reset();
236
237         if (!logic_mux_data_) {
238                 const int64_t ch_count = get_assigned_signal_count();
239                 const int64_t unit_size = (ch_count + 7) / 8;
240                 logic_mux_data_ = make_shared<Logic>(ch_count);
241                 segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
242                 logic_mux_data_->push_segment(segment_);
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         // Receive notifications when new sample data is available
254         connect_input_notifiers();
255 }
256
257 QString DecodeSignal::error_message() const
258 {
259         lock_guard<mutex> lock(output_mutex_);
260         return error_message_;
261 }
262
263 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
264 {
265         return channels_;
266 }
267
268 void DecodeSignal::auto_assign_signals()
269 {
270         bool new_assignment = false;
271
272         // Try to auto-select channels that don't have signals assigned yet
273         for (data::DecodeChannel &ch : channels_) {
274                 if (ch.assigned_signal)
275                         continue;
276
277                 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
278                         const QString ch_name = ch.name.toLower();
279                         const QString s_name = s->name().toLower();
280
281                         if (s->logic_data() &&
282                                 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
283                                 ch.assigned_signal = s.get();
284                                 new_assignment = true;
285                         }
286                 }
287         }
288
289         if (new_assignment) {
290                 logic_mux_data_invalid_ = true;
291                 commit_decoder_channels();
292                 channels_updated();
293         }
294 }
295
296 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
297 {
298         for (data::DecodeChannel &ch : channels_)
299                 if (ch.id == channel_id) {
300                         ch.assigned_signal = signal;
301                         logic_mux_data_invalid_ = true;
302                 }
303
304         commit_decoder_channels();
305         channels_updated();
306         begin_decode();
307 }
308
309 int DecodeSignal::get_assigned_signal_count() const
310 {
311         // Count all channels that have a signal assigned to them
312         return count_if(channels_.begin(), channels_.end(),
313                 [](data::DecodeChannel ch) { return ch.assigned_signal; });
314 }
315
316 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
317 {
318         for (data::DecodeChannel &ch : channels_)
319                 if (ch.id == channel_id)
320                         ch.initial_pin_state = init_state;
321
322         channels_updated();
323
324         begin_decode();
325 }
326
327 double DecodeSignal::samplerate() const
328 {
329         return samplerate_;
330 }
331
332 const pv::util::Timestamp& DecodeSignal::start_time() const
333 {
334         return start_time_;
335 }
336
337 int64_t DecodeSignal::get_working_sample_count() const
338 {
339         // The working sample count is the highest sample number for
340         // which all used signals have data available, so go through
341         // all channels and use the lowest overall sample count of the
342         // current segment
343
344         // TODO Currently, we assume only a single segment exists
345
346         int64_t count = std::numeric_limits<int64_t>::max();
347         bool no_signals_assigned = true;
348
349         for (const data::DecodeChannel &ch : channels_)
350                 if (ch.assigned_signal) {
351                         no_signals_assigned = false;
352
353                         const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
354                         if (!logic_data || logic_data->logic_segments().empty())
355                                 return 0;
356
357                         const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
358                         count = min(count, (int64_t)segment->get_sample_count());
359                 }
360
361         return (no_signals_assigned ? 0 : count);
362 }
363
364 int64_t DecodeSignal::get_decoded_sample_count() const
365 {
366         lock_guard<mutex> decode_lock(output_mutex_);
367         return samples_decoded_;
368 }
369
370 vector<Row> DecodeSignal::visible_rows() const
371 {
372         lock_guard<mutex> lock(output_mutex_);
373
374         vector<Row> rows;
375
376         for (const shared_ptr<decode::Decoder> &dec : stack_) {
377                 assert(dec);
378                 if (!dec->shown())
379                         continue;
380
381                 const srd_decoder *const decc = dec->decoder();
382                 assert(dec->decoder());
383
384                 // Add a row for the decoder if it doesn't have a row list
385                 if (!decc->annotation_rows)
386                         rows.emplace_back(decc);
387
388                 // Add the decoder rows
389                 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
390                         const srd_decoder_annotation_row *const ann_row =
391                                 (srd_decoder_annotation_row *)l->data;
392                         assert(ann_row);
393                         rows.emplace_back(decc, ann_row);
394                 }
395         }
396
397         return rows;
398 }
399
400 void DecodeSignal::get_annotation_subset(
401         vector<pv::data::decode::Annotation> &dest,
402         const decode::Row &row, uint64_t start_sample,
403         uint64_t end_sample) const
404 {
405         lock_guard<mutex> lock(output_mutex_);
406
407         const auto iter = rows_.find(row);
408         if (iter != rows_.end())
409                 (*iter).second.get_annotation_subset(dest,
410                         start_sample, end_sample);
411 }
412
413 void DecodeSignal::save_settings(QSettings &settings) const
414 {
415         SignalBase::save_settings(settings);
416
417         settings.setValue("decoders", (int)(stack_.size()));
418
419         // Save decoder stack
420         int decoder_idx = 0;
421         for (shared_ptr<decode::Decoder> decoder : stack_) {
422                 settings.beginGroup("decoder" + QString::number(decoder_idx++));
423
424                 settings.setValue("id", decoder->decoder()->id);
425
426                 // Save decoder options
427                 const map<string, GVariant*>& options = decoder->options();
428
429                 settings.setValue("options", (int)options.size());
430
431                 // Note: decode::Decoder::options() returns only the options
432                 // that differ from the default. See binding::Decoder::getter()
433                 int i = 0;
434                 for (auto option : options) {
435                         settings.beginGroup("option" + QString::number(i));
436                         settings.setValue("name", QString::fromStdString(option.first));
437                         GlobalSettings::store_gvariant(settings, option.second);
438                         settings.endGroup();
439                         i++;
440                 }
441
442                 settings.endGroup();
443         }
444
445         // Save channel mapping
446         settings.setValue("channels", (int)channels_.size());
447
448         for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
449                 auto channel = find_if(channels_.begin(), channels_.end(),
450                         [&](data::DecodeChannel ch) { return ch.id == channel_id; });
451
452                 if (channel == channels_.end()) {
453                         qDebug() << "ERROR: Gap in channel index:" << channel_id;
454                         continue;
455                 }
456
457                 settings.beginGroup("channel" + QString::number(channel_id));
458
459                 settings.setValue("name", channel->name);  // Useful for debugging
460                 settings.setValue("initial_pin_state", channel->initial_pin_state);
461
462                 if (channel->assigned_signal)
463                         settings.setValue("assigned_signal_name", channel->assigned_signal->name());
464
465                 settings.endGroup();
466         }
467 }
468
469 void DecodeSignal::restore_settings(QSettings &settings)
470 {
471         SignalBase::restore_settings(settings);
472
473         // Restore decoder stack
474         GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
475
476         int decoders = settings.value("decoders").toInt();
477
478         for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
479                 settings.beginGroup("decoder" + QString::number(decoder_idx));
480
481                 QString id = settings.value("id").toString();
482
483                 for (GSList *entry = dec_list; entry; entry = entry->next) {
484                         const srd_decoder *dec = (srd_decoder*)entry->data;
485                         if (!dec)
486                                 continue;
487
488                         if (QString::fromUtf8(dec->id) == id) {
489                                 shared_ptr<decode::Decoder> decoder =
490                                         make_shared<decode::Decoder>(dec);
491
492                                 stack_.push_back(decoder);
493
494                                 // Restore decoder options that differ from their default
495                                 int options = settings.value("options").toInt();
496
497                                 for (int i = 0; i < options; i++) {
498                                         settings.beginGroup("option" + QString::number(i));
499                                         QString name = settings.value("name").toString();
500                                         GVariant *value = GlobalSettings::restore_gvariant(settings);
501                                         decoder->set_option(name.toUtf8(), value);
502                                         settings.endGroup();
503                                 }
504
505                                 // Include the newly created decode channels in the channel lists
506                                 update_channel_list();
507                                 break;
508                         }
509                 }
510
511                 settings.endGroup();
512         }
513
514         // Restore channel mapping
515         unsigned int channels = settings.value("channels").toInt();
516
517         const unordered_set< shared_ptr<data::SignalBase> > signalbases =
518                 session_.signalbases();
519
520         for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
521                 auto channel = find_if(channels_.begin(), channels_.end(),
522                         [&](data::DecodeChannel ch) { return ch.id == channel_id; });
523
524                 if (channel == channels_.end()) {
525                         qDebug() << "ERROR: Non-existant channel index:" << channel_id;
526                         continue;
527                 }
528
529                 settings.beginGroup("channel" + QString::number(channel_id));
530
531                 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
532
533                 for (shared_ptr<data::SignalBase> signal : signalbases)
534                         if (signal->name() == assigned_signal_name)
535                                 channel->assigned_signal = signal.get();
536
537                 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
538
539                 settings.endGroup();
540         }
541
542         begin_decode();
543 }
544
545 void DecodeSignal::update_channel_list()
546 {
547         vector<data::DecodeChannel> prev_channels = channels_;
548         channels_.clear();
549
550         uint16_t id = 0;
551
552         // Copy existing entries, create new as needed
553         for (shared_ptr<Decoder> decoder : stack_) {
554                 const srd_decoder* srd_d = decoder->decoder();
555                 const GSList *l;
556
557                 // Mandatory channels
558                 for (l = srd_d->channels; l; l = l->next) {
559                         const struct srd_channel *const pdch = (struct srd_channel *)l->data;
560                         bool ch_added = false;
561
562                         // Copy but update ID if this channel was in the list before
563                         for (data::DecodeChannel &ch : prev_channels)
564                                 if (ch.pdch_ == pdch) {
565                                         ch.id = id++;
566                                         channels_.push_back(ch);
567                                         ch_added = true;
568                                         break;
569                                 }
570
571                         if (!ch_added) {
572                                 // Create new entry without a mapped signal
573                                 data::DecodeChannel ch = {id++, false, nullptr,
574                                         QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
575                                         SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
576                                 channels_.push_back(ch);
577                         }
578                 }
579
580                 // Optional channels
581                 for (l = srd_d->opt_channels; l; l = l->next) {
582                         const struct srd_channel *const pdch = (struct srd_channel *)l->data;
583                         bool ch_added = false;
584
585                         // Copy but update ID if this channel was in the list before
586                         for (data::DecodeChannel &ch : prev_channels)
587                                 if (ch.pdch_ == pdch) {
588                                         ch.id = id++;
589                                         channels_.push_back(ch);
590                                         ch_added = true;
591                                         break;
592                                 }
593
594                         if (!ch_added) {
595                                 // Create new entry without a mapped signal
596                                 data::DecodeChannel ch = {id++, true, nullptr,
597                                         QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
598                                         SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
599                                 channels_.push_back(ch);
600                         }
601                 }
602         }
603
604         // Invalidate the logic output data if the channel assignment changed
605         if (prev_channels.size() != channels_.size()) {
606                 // The number of channels changed, there's definitely a difference
607                 logic_mux_data_invalid_ = true;
608         } else {
609                 // Same number but assignment may still differ, so compare all channels
610                 for (size_t i = 0; i < channels_.size(); i++) {
611                         const data::DecodeChannel &p_ch = prev_channels[i];
612                         const data::DecodeChannel &ch = channels_[i];
613
614                         if ((p_ch.pdch_ != ch.pdch_) ||
615                                 (p_ch.assigned_signal != ch.assigned_signal)) {
616                                 logic_mux_data_invalid_ = true;
617                                 break;
618                         }
619                 }
620
621         }
622
623         channels_updated();
624 }
625
626 void DecodeSignal::commit_decoder_channels()
627 {
628         // Submit channel list to every decoder, containing only the relevant channels
629         for (shared_ptr<decode::Decoder> dec : stack_) {
630                 vector<data::DecodeChannel*> channel_list;
631
632                 for (data::DecodeChannel &ch : channels_)
633                         if (ch.decoder_ == dec)
634                                 channel_list.push_back(&ch);
635
636                 dec->set_channels(channel_list);
637         }
638 }
639
640 void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
641 {
642         // Enforce end to be greater than start
643         if (end <= start)
644                 return;
645
646         // Fetch all segments and their data
647         // TODO Currently, we assume only a single segment exists
648         vector<shared_ptr<LogicSegment> > segments;
649         vector<const uint8_t*> signal_data;
650         vector<uint8_t> signal_in_bytepos;
651         vector<uint8_t> signal_in_bitpos;
652
653         for (data::DecodeChannel &ch : channels_)
654                 if (ch.assigned_signal) {
655                         const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
656                         const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
657                         segments.push_back(segment);
658                         signal_data.push_back(segment->get_samples(start, end));
659
660                         const int bitpos = ch.assigned_signal->logic_bit_index();
661                         signal_in_bytepos.push_back(bitpos / 8);
662                         signal_in_bitpos.push_back(bitpos % 8);
663                 }
664
665         // Perform the muxing of signal data into the output data
666         uint8_t* output = new uint8_t[(end - start) * segment_->unit_size()];
667         unsigned int signal_count = signal_data.size();
668
669         for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
670                 int bitpos = 0;
671                 uint8_t bytepos = 0;
672
673                 const int out_sample_pos = sample_cnt * segment_->unit_size();
674                 for (unsigned int i = 0; i < segment_->unit_size(); i++)
675                         output[out_sample_pos + i] = 0;
676
677                 for (unsigned int i = 0; i < signal_count; i++) {
678                         const int in_sample_pos = sample_cnt * segments[i]->unit_size();
679                         const uint8_t in_sample = 1 &
680                                 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
681
682                         const uint8_t out_sample = output[out_sample_pos + bytepos];
683
684                         output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
685
686                         bitpos++;
687                         if (bitpos > 7) {
688                                 bitpos = 0;
689                                 bytepos++;
690                         }
691                 }
692         }
693
694         segment_->append_payload(output, (end - start) * segment_->unit_size());
695         delete[] output;
696
697         for (const uint8_t* data : signal_data)
698                 delete[] data;
699 }
700
701 void DecodeSignal::logic_mux_proc()
702 {
703         do {
704                 const uint64_t input_sample_count = get_working_sample_count();
705                 const uint64_t output_sample_count = segment_->get_sample_count();
706
707                 const uint64_t samples_to_process =
708                         (input_sample_count > output_sample_count) ?
709                         (input_sample_count - output_sample_count) : 0;
710
711                 // Process the samples if necessary...
712                 if (samples_to_process > 0) {
713                         const uint64_t unit_size = segment_->unit_size();
714                         const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
715
716                         uint64_t processed_samples = 0;
717                         do {
718                                 const uint64_t start_sample = output_sample_count + processed_samples;
719                                 const uint64_t sample_count =
720                                         min(samples_to_process - processed_samples,     chunk_sample_count);
721
722                                 mux_logic_samples(start_sample, start_sample + sample_count);
723                                 processed_samples += sample_count;
724
725                                 // ...and process the newly muxed logic data
726                                 decode_input_cond_.notify_one();
727                         } while (processed_samples < samples_to_process);
728                 }
729
730                 if (samples_to_process == 0) {
731                         // Wait for more input
732                         unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
733                         logic_mux_cond_.wait(logic_mux_lock);
734                 }
735         } while (!logic_mux_interrupt_);
736
737         // No more input data and session is stopped, let the decode thread
738         // process any pending data, terminate and release the global SRD mutex
739         // in order to let other decoders run
740         decode_input_cond_.notify_one();
741 }
742
743 void DecodeSignal::query_input_metadata()
744 {
745         // Update the samplerate and start time because we cannot start
746         // the libsrd session without the current samplerate
747
748         // TODO Currently we assume all channels have the same sample rate
749         // and start time
750         bool samplerate_valid = false;
751
752         auto any_channel = find_if(channels_.begin(), channels_.end(),
753                 [](data::DecodeChannel ch) { return ch.assigned_signal; });
754
755         shared_ptr<Logic> logic_data =
756                 any_channel->assigned_signal->logic_data();
757
758         do {
759                 if (!logic_data->logic_segments().empty()) {
760                         shared_ptr<LogicSegment> first_segment =
761                                 any_channel->assigned_signal->logic_data()->logic_segments().front();
762                         start_time_ = first_segment->start_time();
763                         samplerate_ = first_segment->samplerate();
764                         if (samplerate_ > 0)
765                                 samplerate_valid = true;
766                 }
767
768                 if (!samplerate_valid) {
769                         // Wait until input data is available or an interrupt was requested
770                         unique_lock<mutex> input_wait_lock(input_mutex_);
771                         decode_input_cond_.wait(input_wait_lock);
772                 }
773         } while (!samplerate_valid && !decode_interrupt_);
774 }
775
776 void DecodeSignal::decode_data(
777         const int64_t abs_start_samplenum, const int64_t sample_count)
778 {
779         const int64_t unit_size = segment_->unit_size();
780         const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
781
782         for (int64_t i = abs_start_samplenum;
783                 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
784                 i += chunk_sample_count) {
785
786                 const int64_t chunk_end = min(i + chunk_sample_count,
787                         abs_start_samplenum + sample_count);
788
789                 const uint8_t* chunk = segment_->get_samples(i, chunk_end);
790
791                 if (srd_session_send(srd_session_, i, chunk_end, chunk,
792                                 (chunk_end - i) * unit_size, unit_size) != SRD_OK) {
793                         error_message_ = tr("Decoder reported an error");
794                         delete[] chunk;
795                         break;
796                 }
797
798                 delete[] chunk;
799
800                 {
801                         lock_guard<mutex> lock(output_mutex_);
802                         samples_decoded_ = chunk_end;
803                 }
804
805                 // Notify the frontend that we processed some data and
806                 // possibly have new annotations as well
807                 new_annotations();
808         }
809 }
810
811 void DecodeSignal::decode_proc()
812 {
813         query_input_metadata();
814
815         if (decode_interrupt_)
816                 return;
817
818         start_srd_session();
819
820         uint64_t sample_count;
821         uint64_t abs_start_samplenum = 0;
822         do {
823                 // Keep processing new samples until we exhaust the input data
824                 do {
825                         // Prevent any other decode threads from accessing libsigrokdecode
826                         lock_guard<mutex> srd_lock(global_srd_mutex_);
827
828                         {
829                                 lock_guard<mutex> input_lock(input_mutex_);
830                                 sample_count = segment_->get_sample_count() - abs_start_samplenum;
831                         }
832
833                         if (sample_count > 0) {
834                                 decode_data(abs_start_samplenum, sample_count);
835                                 abs_start_samplenum += sample_count;
836                         }
837                 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
838
839                 if (error_message_.isEmpty() && !decode_interrupt_) {
840                         if (sample_count == 0)
841                                 decode_finished();
842
843                         // Wait for new input data or an interrupt was requested
844                         unique_lock<mutex> input_wait_lock(input_mutex_);
845                         decode_input_cond_.wait(input_wait_lock);
846                 }
847         } while (error_message_.isEmpty() && !decode_interrupt_);
848 }
849
850 void DecodeSignal::start_srd_session()
851 {
852         if (srd_session_)
853                 stop_srd_session();
854
855         // Create the session
856         srd_session_new(&srd_session_);
857         assert(srd_session_);
858
859         // Create the decoders
860         srd_decoder_inst *prev_di = nullptr;
861         for (const shared_ptr<decode::Decoder> &dec : stack_) {
862                 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
863
864                 if (!di) {
865                         error_message_ = tr("Failed to create decoder instance");
866                         srd_session_destroy(srd_session_);
867                         return;
868                 }
869
870                 if (prev_di)
871                         srd_inst_stack(srd_session_, prev_di, di);
872
873                 prev_di = di;
874         }
875
876         // Start the session
877         srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
878                 g_variant_new_uint64(samplerate_));
879
880         srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
881                 DecodeSignal::annotation_callback, this);
882
883         srd_session_start(srd_session_);
884 }
885
886 void DecodeSignal::stop_srd_session()
887 {
888         if (srd_session_) {
889                 // Destroy the session
890                 srd_session_destroy(srd_session_);
891                 srd_session_ = nullptr;
892         }
893 }
894
895 void DecodeSignal::connect_input_notifiers()
896 {
897         // Disconnect the notification slot from the previous set of signals
898         disconnect(this, SLOT(on_data_cleared()));
899         disconnect(this, SLOT(on_data_received()));
900
901         // Connect the currently used signals to our slot
902         for (data::DecodeChannel &ch : channels_) {
903                 if (!ch.assigned_signal)
904                         continue;
905
906                 const data::SignalBase *signal = ch.assigned_signal;
907                 connect(signal, SIGNAL(samples_cleared()),
908                         this, SLOT(on_data_cleared()));
909                 connect(signal, SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
910                         this, SLOT(on_data_received()));
911         }
912 }
913
914 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
915 {
916         assert(pdata);
917         assert(decoder);
918
919         DecodeSignal *const ds = (DecodeSignal*)decode_signal;
920         assert(ds);
921
922         lock_guard<mutex> lock(ds->output_mutex_);
923
924         const decode::Annotation a(pdata);
925
926         // Find the row
927         assert(pdata->pdo);
928         assert(pdata->pdo->di);
929         const srd_decoder *const decc = pdata->pdo->di->decoder;
930         assert(decc);
931
932         auto row_iter = ds->rows_.end();
933
934         // Try looking up the sub-row of this class
935         const auto r = ds->class_rows_.find(make_pair(decc, a.format()));
936         if (r != ds->class_rows_.end())
937                 row_iter = ds->rows_.find((*r).second);
938         else {
939                 // Failing that, use the decoder as a key
940                 row_iter = ds->rows_.find(Row(decc));
941         }
942
943         assert(row_iter != ds->rows_.end());
944         if (row_iter == ds->rows_.end()) {
945                 qDebug() << "Unexpected annotation: decoder = " << decc <<
946                         ", format = " << a.format();
947                 assert(false);
948                 return;
949         }
950
951         // Add the annotation
952         (*row_iter).second.push_annotation(a);
953 }
954
955 void DecodeSignal::on_capture_state_changed(int state)
956 {
957         // If a new acquisition was started, we need to start decoding from scratch
958         if (state == Session::Running)
959                 begin_decode();
960 }
961
962 void DecodeSignal::on_data_cleared()
963 {
964         reset_decode();
965 }
966
967 void DecodeSignal::on_data_received()
968 {
969         if (!logic_mux_thread_.joinable())
970                 begin_decode();
971         else
972                 logic_mux_cond_.notify_one();
973 }
974
975 } // namespace data
976 } // namespace pv