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