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