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