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