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