]> sigrok.org Git - pulseview.git/blame - pv/data/decodesignal.cpp
Continue reworking the channel/signal handling
[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
c0c3e62a 20#include <cstring>
5a914348 21#include <forward_list>
0c5fe73e
SA
22#include <limits>
23
47747218
SA
24#include <QDebug>
25
ad908057
SA
26#include "logic.hpp"
27#include "logicsegment.hpp"
28#include "decodesignal.hpp"
29#include "signaldata.hpp"
30
ad908057 31#include <pv/data/decode/decoder.hpp>
ecd07c20 32#include <pv/data/decode/row.hpp>
d3feec23 33#include <pv/globalsettings.hpp>
ad908057
SA
34#include <pv/session.hpp>
35
47747218 36using std::lock_guard;
ad908057 37using std::make_shared;
0c5fe73e 38using std::min;
5ecf957f 39using std::out_of_range;
ad908057 40using std::shared_ptr;
47747218 41using std::unique_lock;
6a26fc44 42using pv::data::decode::AnnotationClass;
a82325d1 43using pv::data::decode::DecodeChannel;
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 57 logic_mux_data_invalid_(false),
e3202557 58 stack_config_changed_(true),
8a603e13 59 current_segment_id_(0)
ad908057 60{
47747218
SA
61 connect(&session_, SIGNAL(capture_state_changed(int)),
62 this, SLOT(on_capture_state_changed(int)));
ad908057
SA
63}
64
47747218 65DecodeSignal::~DecodeSignal()
ad908057 66{
8ce0e732 67 reset_decode(true);
ad908057
SA
68}
69
47747218 70const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
ecd07c20 71{
47747218 72 return stack_;
ecd07c20
SA
73}
74
ed75426f 75void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
ad908057
SA
76{
77 assert(decoder);
762ab7a4 78
b9591f3a 79 // Set name if this decoder is the first in the list or the name is unchanged
6a26fc44
SA
80 const srd_decoder* prev_dec = stack_.empty() ? nullptr : stack_.back()->get_srd_decoder();
81 const QString prev_dec_name = prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
47747218 82
b9591f3a 83 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
47747218 84 set_name(QString::fromUtf8(decoder->name));
132a5c6d 85
f54e68b0 86 const shared_ptr<Decoder> dec = make_shared<Decoder>(decoder, stack_.size());
b9591f3a
SA
87 stack_.push_back(dec);
88
02078aa1
SA
89 connect(dec.get(), SIGNAL(annotation_visibility_changed()),
90 this, SLOT(on_annotation_visibility_changed()));
91
27a3f09b 92 // Include the newly created decode channels in the channel lists
9f97b357 93 update_channel_list();
132a5c6d 94
e3202557 95 stack_config_changed_ = true;
762ab7a4 96 auto_assign_signals(dec);
27a3f09b 97 commit_decoder_channels();
e77de61f
SA
98
99 decoder_stacked((void*)dec.get());
100
ed75426f
SA
101 if (restart_decode)
102 begin_decode();
ad908057
SA
103}
104
105void DecodeSignal::remove_decoder(int index)
106{
47747218
SA
107 assert(index >= 0);
108 assert(index < (int)stack_.size());
109
110 // Find the decoder in the stack
f9a0fd83
SA
111 auto iter = stack_.begin() + index;
112 assert(iter != stack_.end());
47747218 113
f9a0fd83
SA
114 shared_ptr<Decoder> dec = *iter;
115
116 decoder_removed(dec.get());
e77de61f 117
47747218
SA
118 // Delete the element
119 stack_.erase(iter);
120
121 // Update channels and decoded data
e3202557 122 stack_config_changed_ = true;
9f97b357 123 update_channel_list();
47747218 124 begin_decode();
ad908057
SA
125}
126
127bool DecodeSignal::toggle_decoder_visibility(int index)
128{
47747218 129 auto iter = stack_.cbegin();
ad908057 130 for (int i = 0; i < index; i++, iter++)
47747218 131 assert(iter != stack_.end());
ad908057
SA
132
133 shared_ptr<Decoder> dec = *iter;
134
135 // Toggle decoder visibility
136 bool state = false;
137 if (dec) {
5d3ca591
SA
138 state = !dec->visible();
139 dec->set_visible(state);
ad908057
SA
140 }
141
142 return state;
143}
144
8ce0e732 145void DecodeSignal::reset_decode(bool shutting_down)
47747218 146{
8b24af15
SA
147 resume_decode(); // Make sure the decode thread isn't blocked by pausing
148
8ce0e732 149 if (stack_config_changed_ || shutting_down)
e3202557
SA
150 stop_srd_session();
151 else
152 terminate_srd_session();
ce0b6a40 153
1b56c646
SA
154 if (decode_thread_.joinable()) {
155 decode_interrupt_ = true;
156 decode_input_cond_.notify_one();
157 decode_thread_.join();
158 }
159
160 if (logic_mux_thread_.joinable()) {
161 logic_mux_interrupt_ = true;
162 logic_mux_cond_.notify_one();
163 logic_mux_thread_.join();
164 }
165
8a603e13 166 current_segment_id_ = 0;
72435789 167 segments_.clear();
1b56c646
SA
168
169 logic_mux_data_.reset();
170 logic_mux_data_invalid_ = true;
eee3eab9 171
403c3e87
SA
172 if (!error_message_.isEmpty()) {
173 error_message_ = QString();
fe060a48
SA
174 // TODO Emulate noquote()
175 qDebug().nospace() << name() << ": Error cleared";
403c3e87 176 }
72435789 177
eee3eab9 178 decode_reset();
47747218
SA
179}
180
946b52e1
SA
181void DecodeSignal::begin_decode()
182{
47747218
SA
183 if (decode_thread_.joinable()) {
184 decode_interrupt_ = true;
185 decode_input_cond_.notify_one();
186 decode_thread_.join();
187 }
188
189 if (logic_mux_thread_.joinable()) {
190 logic_mux_interrupt_ = true;
191 logic_mux_cond_.notify_one();
192 logic_mux_thread_.join();
193 }
194
195 reset_decode();
196
27a3f09b 197 if (stack_.size() == 0) {
403c3e87 198 set_error_message(tr("No decoders"));
27a3f09b
SA
199 return;
200 }
201
202 assert(channels_.size() > 0);
203
204 if (get_assigned_signal_count() == 0) {
403c3e87 205 set_error_message(tr("There are no channels assigned to this decoder"));
27a3f09b
SA
206 return;
207 }
208
04627946
SA
209 // Make sure that all assigned channels still provide logic data
210 // (can happen when a converted signal was assigned but the
211 // conversion removed in the meanwhile)
a82325d1 212 for (decode::DecodeChannel& ch : channels_)
04627946
SA
213 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
214 ch.assigned_signal = nullptr;
215
47747218 216 // Check that all decoders have the required channels
6a26fc44 217 for (const shared_ptr<Decoder>& dec : stack_)
47747218 218 if (!dec->have_required_channels()) {
403c3e87
SA
219 set_error_message(tr("One or more required channels "
220 "have not been specified"));
47747218
SA
221 return;
222 }
223
27a3f09b
SA
224 // Free the logic data and its segment(s) if it needs to be updated
225 if (logic_mux_data_invalid_)
226 logic_mux_data_.reset();
227
228 if (!logic_mux_data_) {
72435789 229 const uint32_t ch_count = get_assigned_signal_count();
ed535cd7 230 logic_mux_unit_size_ = (ch_count + 7) / 8;
27a3f09b 231 logic_mux_data_ = make_shared<Logic>(ch_count);
27a3f09b 232 }
47747218 233
ed535cd7
SA
234 // Receive notifications when new sample data is available
235 connect_input_notifiers();
236
8a603e13 237 if (get_input_segment_count() == 0) {
403c3e87 238 set_error_message(tr("No input data"));
ed535cd7
SA
239 return;
240 }
241
27a3f09b
SA
242 // Make sure the logic output data is complete and up-to-date
243 logic_mux_interrupt_ = false;
244 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
245
246 // Decode the muxed logic data
47747218
SA
247 decode_interrupt_ = false;
248 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
946b52e1
SA
249}
250
556259d2
SA
251void DecodeSignal::pause_decode()
252{
253 decode_paused_ = true;
254}
255
256void DecodeSignal::resume_decode()
257{
258 // Manual unlocking is done before notifying, to avoid waking up the
259 // waiting thread only to block again (see notify_one for details)
260 decode_pause_mutex_.unlock();
261 decode_pause_cond_.notify_one();
262 decode_paused_ = false;
263}
264
265bool DecodeSignal::is_paused() const
266{
267 return decode_paused_;
268}
269
ecd07c20
SA
270QString DecodeSignal::error_message() const
271{
47747218
SA
272 lock_guard<mutex> lock(output_mutex_);
273 return error_message_;
ecd07c20
SA
274}
275
a82325d1 276const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
9f97b357
SA
277{
278 return channels_;
279}
280
762ab7a4 281void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
132a5c6d 282{
47747218
SA
283 bool new_assignment = false;
284
132a5c6d 285 // Try to auto-select channels that don't have signals assigned yet
a82325d1 286 for (decode::DecodeChannel& ch : channels_) {
762ab7a4
SA
287 // If a decoder is given, auto-assign only its channels
288 if (dec && (ch.decoder_ != dec))
289 continue;
290
132a5c6d
SA
291 if (ch.assigned_signal)
292 continue;
293
c526a8fd
SA
294 QString ch_name = ch.name.toLower();
295 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
a8030bb0
SA
296
297 shared_ptr<data::SignalBase> match;
f4ab4b5c 298 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
f9ebf303
SA
299 if (!s->enabled())
300 continue;
301
c526a8fd
SA
302 QString s_name = s->name().toLower();
303 s_name = s_name.replace(QRegExp("[-_.]"), " ");
692f6093
SA
304
305 if (s->logic_data() &&
306 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
a8030bb0
SA
307 if (!match)
308 match = s;
309 else {
310 // Only replace an existing match if it matches more characters
311 int old_unmatched = ch_name.length() - match->name().length();
312 int new_unmatched = ch_name.length() - s->name().length();
313 if (abs(new_unmatched) < abs(old_unmatched))
314 match = s;
315 }
47747218 316 }
692f6093 317 }
a8030bb0
SA
318
319 if (match) {
320 ch.assigned_signal = match.get();
321 new_assignment = true;
322 }
47747218
SA
323 }
324
325 if (new_assignment) {
326 logic_mux_data_invalid_ = true;
e3202557 327 stack_config_changed_ = true;
27a3f09b 328 commit_decoder_channels();
47747218 329 channels_updated();
132a5c6d
SA
330 }
331}
332
9f97b357
SA
333void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
334{
a82325d1 335 for (decode::DecodeChannel& ch : channels_)
47747218 336 if (ch.id == channel_id) {
9f97b357 337 ch.assigned_signal = signal;
47747218
SA
338 logic_mux_data_invalid_ = true;
339 }
9f97b357 340
e3202557 341 stack_config_changed_ = true;
27a3f09b 342 commit_decoder_channels();
9f97b357 343 channels_updated();
47747218 344 begin_decode();
9f97b357
SA
345}
346
27a3f09b
SA
347int DecodeSignal::get_assigned_signal_count() const
348{
349 // Count all channels that have a signal assigned to them
350 return count_if(channels_.begin(), channels_.end(),
a82325d1 351 [](decode::DecodeChannel ch) { return ch.assigned_signal; });
27a3f09b
SA
352}
353
9f97b357
SA
354void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
355{
a82325d1 356 for (decode::DecodeChannel& ch : channels_)
9f97b357
SA
357 if (ch.id == channel_id)
358 ch.initial_pin_state = init_state;
359
e3202557 360 stack_config_changed_ = true;
9f97b357 361 channels_updated();
47747218 362 begin_decode();
9f97b357
SA
363}
364
85125b0f 365double DecodeSignal::get_samplerate() const
ff83d980 366{
72435789
SA
367 double result = 0;
368
369 // TODO For now, we simply return the first samplerate that we have
8a603e13
SA
370 if (segments_.size() > 0)
371 result = segments_.front().samplerate;
72435789
SA
372
373 return result;
ff83d980
SA
374}
375
72435789 376const pv::util::Timestamp DecodeSignal::start_time() const
ff83d980 377{
72435789
SA
378 pv::util::Timestamp result;
379
380 // TODO For now, we simply return the first start time that we have
8a603e13
SA
381 if (segments_.size() > 0)
382 result = segments_.front().start_time;
72435789
SA
383
384 return result;
ff83d980
SA
385}
386
5ecf957f 387int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
0c5fe73e
SA
388{
389 // The working sample count is the highest sample number for
ed535cd7
SA
390 // which all used signals have data available, so go through all
391 // channels and use the lowest overall sample count of the segment
0c5fe73e 392
0c5fe73e
SA
393 int64_t count = std::numeric_limits<int64_t>::max();
394 bool no_signals_assigned = true;
395
a82325d1 396 for (const decode::DecodeChannel& ch : channels_)
0c5fe73e
SA
397 if (ch.assigned_signal) {
398 no_signals_assigned = false;
399
400 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
401 if (!logic_data || logic_data->logic_segments().empty())
402 return 0;
403
5ecf957f
SA
404 try {
405 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
406 count = min(count, (int64_t)segment->get_sample_count());
30677c13 407 } catch (out_of_range&) {
5ecf957f
SA
408 return 0;
409 }
0c5fe73e
SA
410 }
411
412 return (no_signals_assigned ? 0 : count);
413}
414
b82908ab
SA
415int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
416 bool include_processing) const
ff83d980 417{
47747218 418 lock_guard<mutex> decode_lock(output_mutex_);
5ecf957f
SA
419
420 int64_t result = 0;
421
c8a6db0e
SA
422 if (segment_id >= segments_.size())
423 return result;
424
425 if (include_processing)
426 result = segments_[segment_id].samples_decoded_incl;
427 else
428 result = segments_[segment_id].samples_decoded_excl;
5ecf957f
SA
429
430 return result;
ff83d980
SA
431}
432
6a26fc44 433vector<Row*> DecodeSignal::get_rows(bool visible_only)
ecd07c20 434{
6a26fc44 435 vector<Row*> rows;
47747218 436
6a26fc44 437 for (const shared_ptr<Decoder>& dec : stack_) {
47747218 438 assert(dec);
5d3ca591 439 if (visible_only && !dec->visible())
cbb2e4da
SA
440 continue;
441
6a26fc44
SA
442 for (Row* row : dec->get_rows())
443 rows.push_back(row);
444 }
47747218 445
6a26fc44
SA
446 return rows;
447}
47747218 448
6a26fc44
SA
449vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
450{
451 vector<const Row*> rows;
452
453 for (const shared_ptr<Decoder>& dec : stack_) {
454 assert(dec);
5d3ca591 455 if (visible_only && !dec->visible())
6a26fc44
SA
456 continue;
457
458 for (const Row* row : dec->get_rows())
459 rows.push_back(row);
47747218
SA
460 }
461
462 return rows;
ecd07c20
SA
463}
464
6a26fc44
SA
465
466uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
f994f496
SA
467{
468 if (segment_id >= segments_.size())
469 return 0;
470
6a26fc44 471 const DecodeSegment* segment = &(segments_.at(segment_id));
f994f496 472
6a26fc44 473 auto row_it = segment->annotation_rows.find(row);
f994f496 474
6a26fc44 475 const RowData* rd;
5a9146ac 476 if (row_it == segment->annotation_rows.end())
6a26fc44 477 return 0;
5a9146ac 478 else
6a26fc44
SA
479 rd = &(row_it->second);
480
481 return rd->get_annotation_count();
f994f496
SA
482}
483
462941e2 484void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
6a26fc44 485 const Row* row, uint32_t segment_id, uint64_t start_sample,
ecd07c20
SA
486 uint64_t end_sample) const
487{
47747218
SA
488 lock_guard<mutex> lock(output_mutex_);
489
c8a6db0e
SA
490 if (segment_id >= segments_.size())
491 return;
72435789 492
6a26fc44
SA
493 const DecodeSegment* segment = &(segments_.at(segment_id));
494
495 auto row_it = segment->annotation_rows.find(row);
c8a6db0e 496
6a26fc44 497 const RowData* rd;
5a9146ac 498 if (row_it == segment->annotation_rows.end())
6a26fc44 499 return;
5a9146ac 500 else
6a26fc44
SA
501 rd = &(row_it->second);
502
503 rd->get_annotation_subset(dest, start_sample, end_sample);
47747218
SA
504}
505
462941e2 506void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
5a914348
SA
507 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
508{
462941e2
SA
509 for (const Row* row : get_rows())
510 get_annotation_subset(dest, row, segment_id, start_sample, end_sample);
5a914348
SA
511}
512
e77de61f 513uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
ac9494ef 514 const Decoder* dec, uint32_t bin_class_id) const
c0c3e62a 515{
c8a6db0e
SA
516 if (segments_.size() == 0)
517 return 0;
518
c0c3e62a
SA
519 try {
520 const DecodeSegment *segment = &(segments_.at(segment_id));
e77de61f
SA
521
522 for (const DecodeBinaryClass& bc : segment->binary_classes)
523 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
524 return bc.chunks.size();
c0c3e62a
SA
525 } catch (out_of_range&) {
526 // Do nothing
527 }
528
e77de61f 529 return 0;
c0c3e62a
SA
530}
531
e77de61f 532void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
ac9494ef 533 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
c0c3e62a
SA
534 const vector<uint8_t> **dest, uint64_t *size)
535{
536 try {
537 const DecodeSegment *segment = &(segments_.at(segment_id));
e77de61f
SA
538
539 for (const DecodeBinaryClass& bc : segment->binary_classes)
540 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
541 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
542 if (size) *size = bc.chunks.at(chunk_id).data.size();
543 return;
544 }
c0c3e62a
SA
545 } catch (out_of_range&) {
546 // Do nothing
547 }
548}
549
13b726cd 550void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
ac9494ef 551 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
e77de61f 552 uint64_t end_sample, vector<uint8_t> *dest) const
c0c3e62a
SA
553{
554 assert(dest != nullptr);
555
556 try {
557 const DecodeSegment *segment = &(segments_.at(segment_id));
558
e77de61f
SA
559 const DecodeBinaryClass* bin_class = nullptr;
560 for (const DecodeBinaryClass& bc : segment->binary_classes)
561 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
562 bin_class = &bc;
563
c0c3e62a
SA
564 // Determine overall size before copying to resize dest vector only once
565 uint64_t size = 0;
163f3499 566 uint64_t matches = 0;
e77de61f
SA
567 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
568 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
569 size += chunk.data.size();
4b97fe09
SA
570 matches++;
571 }
572 dest->resize(size);
c0c3e62a 573
163f3499
SA
574 uint64_t offset = 0;
575 uint64_t matches2 = 0;
e77de61f
SA
576 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
577 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
578 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
579 offset += chunk.data.size();
163f3499
SA
580 matches2++;
581
582 // Make sure we don't overwrite memory if the array grew in the meanwhile
583 if (matches2 == matches)
584 break;
c0c3e62a
SA
585 }
586 } catch (out_of_range&) {
587 // Do nothing
588 }
589}
590
13b726cd 591void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
6a26fc44
SA
592 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
593 vector<uint8_t> *dest) const
13b726cd
SA
594{
595 assert(dest != nullptr);
596
597 try {
598 const DecodeSegment *segment = &(segments_.at(segment_id));
599
600 const DecodeBinaryClass* bin_class = nullptr;
601 for (const DecodeBinaryClass& bc : segment->binary_classes)
602 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
603 bin_class = &bc;
604
605 // Determine overall size before copying to resize dest vector only once
606 uint64_t size = 0;
607 uint64_t offset = 0;
608 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
609 if (offset >= start)
610 size += chunk.data.size();
611 offset += chunk.data.size();
612 if (offset >= end)
613 break;
614 }
615 dest->resize(size);
616
617 offset = 0;
618 uint64_t dest_offset = 0;
619 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
620 if (offset >= start) {
621 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
622 dest_offset += chunk.data.size();
623 }
624 offset += chunk.data.size();
625 if (offset >= end)
626 break;
627 }
628 } catch (out_of_range&) {
629 // Do nothing
630 }
631}
632
628b45cc 633const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
6a26fc44 634 const Decoder* dec, uint32_t bin_class_id) const
628b45cc
SA
635{
636 try {
637 const DecodeSegment *segment = &(segments_.at(segment_id));
638
639 for (const DecodeBinaryClass& bc : segment->binary_classes)
640 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
641 return &bc;
642 } catch (out_of_range&) {
643 // Do nothing
644 }
645
646 return nullptr;
647}
c0c3e62a 648
f54e68b0
SA
649const deque<const Annotation*>* DecodeSignal::get_all_annotations_by_segment(
650 uint32_t segment_id) const
651{
652 try {
653 const DecodeSegment *segment = &(segments_.at(segment_id));
654 return &(segment->all_annotations);
655 } catch (out_of_range&) {
656 // Do nothing
657 }
658
659 return nullptr;
660}
661
47747218
SA
662void DecodeSignal::save_settings(QSettings &settings) const
663{
664 SignalBase::save_settings(settings);
665
c8e60bdf
SA
666 settings.setValue("decoders", (int)(stack_.size()));
667
8b5ea5a1 668 // Save decoder stack
c8e60bdf 669 int decoder_idx = 0;
6a26fc44 670 for (const shared_ptr<Decoder>& decoder : stack_) {
c8e60bdf
SA
671 settings.beginGroup("decoder" + QString::number(decoder_idx++));
672
6a26fc44 673 settings.setValue("id", decoder->get_srd_decoder()->id);
5d3ca591 674 settings.setValue("visible", decoder->visible());
c8e60bdf 675
d3feec23
SA
676 // Save decoder options
677 const map<string, GVariant*>& options = decoder->options();
678
679 settings.setValue("options", (int)options.size());
680
6a26fc44 681 // Note: Decoder::options() returns only the options
d3feec23
SA
682 // that differ from the default. See binding::Decoder::getter()
683 int i = 0;
f4ab4b5c 684 for (auto& option : options) {
d3feec23
SA
685 settings.beginGroup("option" + QString::number(i));
686 settings.setValue("name", QString::fromStdString(option.first));
687 GlobalSettings::store_gvariant(settings, option.second);
688 settings.endGroup();
689 i++;
690 }
691
e4cb8bcf
SA
692 // Save row properties
693 i = 0;
694 for (const Row* row : decoder->get_rows()) {
695 settings.beginGroup("row" + QString::number(i));
696 settings.setValue("visible", row->visible());
697 settings.endGroup();
698 i++;
699 }
700
701 // Save class properties
702 i = 0;
703 for (const AnnotationClass* ann_class : decoder->ann_classes()) {
704 settings.beginGroup("ann_class" + QString::number(i));
02078aa1 705 settings.setValue("visible", ann_class->visible());
e4cb8bcf
SA
706 settings.endGroup();
707 i++;
708 }
709
c8e60bdf
SA
710 settings.endGroup();
711 }
712
8b5ea5a1
SA
713 // Save channel mapping
714 settings.setValue("channels", (int)channels_.size());
715
716 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
717 auto channel = find_if(channels_.begin(), channels_.end(),
a82325d1 718 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
8b5ea5a1
SA
719
720 if (channel == channels_.end()) {
721 qDebug() << "ERROR: Gap in channel index:" << channel_id;
722 continue;
723 }
724
725 settings.beginGroup("channel" + QString::number(channel_id));
726
727 settings.setValue("name", channel->name); // Useful for debugging
728 settings.setValue("initial_pin_state", channel->initial_pin_state);
729
730 if (channel->assigned_signal)
731 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
732
733 settings.endGroup();
734 }
47747218
SA
735}
736
737void DecodeSignal::restore_settings(QSettings &settings)
738{
739 SignalBase::restore_settings(settings);
740
8b5ea5a1 741 // Restore decoder stack
c8e60bdf
SA
742 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
743
744 int decoders = settings.value("decoders").toInt();
745
746 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
747 settings.beginGroup("decoder" + QString::number(decoder_idx));
748
749 QString id = settings.value("id").toString();
750
751 for (GSList *entry = dec_list; entry; entry = entry->next) {
752 const srd_decoder *dec = (srd_decoder*)entry->data;
753 if (!dec)
754 continue;
755
756 if (QString::fromUtf8(dec->id) == id) {
f54e68b0 757 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec, stack_.size());
d3feec23 758
02078aa1
SA
759 connect(decoder.get(), SIGNAL(annotation_visibility_changed()),
760 this, SLOT(on_annotation_visibility_changed()));
761
d3feec23 762 stack_.push_back(decoder);
5d3ca591 763 decoder->set_visible(settings.value("visible", true).toBool());
d3feec23
SA
764
765 // Restore decoder options that differ from their default
766 int options = settings.value("options").toInt();
767
768 for (int i = 0; i < options; i++) {
769 settings.beginGroup("option" + QString::number(i));
770 QString name = settings.value("name").toString();
771 GVariant *value = GlobalSettings::restore_gvariant(settings);
772 decoder->set_option(name.toUtf8(), value);
773 settings.endGroup();
774 }
c8e60bdf
SA
775
776 // Include the newly created decode channels in the channel lists
777 update_channel_list();
e4cb8bcf
SA
778
779 // Restore row properties
780 int i = 0;
781 for (Row* row : decoder->get_rows()) {
782 settings.beginGroup("row" + QString::number(i));
783 row->set_visible(settings.value("visible", true).toBool());
784 settings.endGroup();
785 i++;
786 }
787
788 // Restore class properties
789 i = 0;
790 for (AnnotationClass* ann_class : decoder->ann_classes()) {
791 settings.beginGroup("ann_class" + QString::number(i));
02078aa1 792 ann_class->set_visible(settings.value("visible", true).toBool());
e4cb8bcf
SA
793 settings.endGroup();
794 i++;
795 }
796
c8e60bdf
SA
797 break;
798 }
799 }
800
801 settings.endGroup();
4ca06ec3 802 channels_updated();
c8e60bdf
SA
803 }
804
8b5ea5a1
SA
805 // Restore channel mapping
806 unsigned int channels = settings.value("channels").toInt();
807
56c4de9a 808 const vector< shared_ptr<data::SignalBase> > signalbases =
8b5ea5a1
SA
809 session_.signalbases();
810
811 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
812 auto channel = find_if(channels_.begin(), channels_.end(),
a82325d1 813 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
8b5ea5a1
SA
814
815 if (channel == channels_.end()) {
816 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
817 continue;
818 }
819
820 settings.beginGroup("channel" + QString::number(channel_id));
821
822 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
823
f4ab4b5c 824 for (const shared_ptr<data::SignalBase>& signal : signalbases)
8b5ea5a1
SA
825 if (signal->name() == assigned_signal_name)
826 channel->assigned_signal = signal.get();
827
828 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
829
830 settings.endGroup();
831 }
832
aa71890d 833 // Update the internal structures
e3202557 834 stack_config_changed_ = true;
aa71890d
SA
835 update_channel_list();
836 commit_decoder_channels();
837
8b5ea5a1 838 begin_decode();
47747218
SA
839}
840
403c3e87
SA
841void DecodeSignal::set_error_message(QString msg)
842{
843 error_message_ = msg;
fe060a48
SA
844 // TODO Emulate noquote()
845 qDebug().nospace() << name() << ": " << msg;
403c3e87
SA
846}
847
8a603e13
SA
848uint32_t DecodeSignal::get_input_segment_count() const
849{
850 uint64_t count = std::numeric_limits<uint64_t>::max();
851 bool no_signals_assigned = true;
852
a82325d1 853 for (const decode::DecodeChannel& ch : channels_)
8a603e13
SA
854 if (ch.assigned_signal) {
855 no_signals_assigned = false;
856
857 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
858 if (!logic_data || logic_data->logic_segments().empty())
859 return 0;
860
861 // Find the min value of all segment counts
862 if ((uint64_t)(logic_data->logic_segments().size()) < count)
863 count = logic_data->logic_segments().size();
864 }
865
866 return (no_signals_assigned ? 0 : count);
867}
868
869uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
870{
871 double samplerate = 0;
872
a82325d1 873 for (const decode::DecodeChannel& ch : channels_)
8a603e13
SA
874 if (ch.assigned_signal) {
875 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
876 if (!logic_data || logic_data->logic_segments().empty())
877 continue;
878
879 try {
880 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
881 samplerate = segment->samplerate();
30677c13 882 } catch (out_of_range&) {
8a603e13
SA
883 // Do nothing
884 }
885 break;
886 }
887
888 return samplerate;
889}
890
6a26fc44
SA
891Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
892{
893 for (shared_ptr<Decoder>& d : stack_)
894 if (d->get_srd_decoder() == srd_dec)
895 return d.get();
896
897 return nullptr;
898}
899
9f97b357
SA
900void DecodeSignal::update_channel_list()
901{
a82325d1 902 vector<decode::DecodeChannel> prev_channels = channels_;
9f97b357
SA
903 channels_.clear();
904
905 uint16_t id = 0;
906
907 // Copy existing entries, create new as needed
f4ab4b5c 908 for (shared_ptr<Decoder>& decoder : stack_) {
6a26fc44 909 const srd_decoder* srd_dec = decoder->get_srd_decoder();
9f97b357
SA
910 const GSList *l;
911
912 // Mandatory channels
6a26fc44 913 for (l = srd_dec->channels; l; l = l->next) {
9f97b357
SA
914 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
915 bool ch_added = false;
916
917 // Copy but update ID if this channel was in the list before
a82325d1 918 for (decode::DecodeChannel& ch : prev_channels)
9f97b357
SA
919 if (ch.pdch_ == pdch) {
920 ch.id = id++;
921 channels_.push_back(ch);
922 ch_added = true;
923 break;
924 }
925
926 if (!ch_added) {
927 // Create new entry without a mapped signal
a82325d1 928 decode::DecodeChannel ch = {id++, 0, false, nullptr,
9f97b357
SA
929 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
930 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
931 channels_.push_back(ch);
932 }
933 }
934
935 // Optional channels
6a26fc44 936 for (l = srd_dec->opt_channels; l; l = l->next) {
9f97b357
SA
937 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
938 bool ch_added = false;
939
940 // Copy but update ID if this channel was in the list before
a82325d1 941 for (decode::DecodeChannel& ch : prev_channels)
9f97b357
SA
942 if (ch.pdch_ == pdch) {
943 ch.id = id++;
944 channels_.push_back(ch);
945 ch_added = true;
946 break;
947 }
948
949 if (!ch_added) {
950 // Create new entry without a mapped signal
a82325d1 951 decode::DecodeChannel ch = {id++, 0, true, nullptr,
9f97b357
SA
952 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
953 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
954 channels_.push_back(ch);
955 }
956 }
957 }
958
47747218
SA
959 // Invalidate the logic output data if the channel assignment changed
960 if (prev_channels.size() != channels_.size()) {
961 // The number of channels changed, there's definitely a difference
962 logic_mux_data_invalid_ = true;
963 } else {
964 // Same number but assignment may still differ, so compare all channels
965 for (size_t i = 0; i < channels_.size(); i++) {
a82325d1
SA
966 const decode::DecodeChannel& p_ch = prev_channels[i];
967 const decode::DecodeChannel& ch = channels_[i];
47747218
SA
968
969 if ((p_ch.pdch_ != ch.pdch_) ||
970 (p_ch.assigned_signal != ch.assigned_signal)) {
971 logic_mux_data_invalid_ = true;
972 break;
973 }
974 }
975
976 }
977
9f97b357
SA
978 channels_updated();
979}
980
27a3f09b 981void DecodeSignal::commit_decoder_channels()
ad908057 982{
27a3f09b 983 // Submit channel list to every decoder, containing only the relevant channels
6a26fc44 984 for (shared_ptr<Decoder> dec : stack_) {
a82325d1 985 vector<decode::DecodeChannel*> channel_list;
27a3f09b 986
a82325d1 987 for (decode::DecodeChannel& ch : channels_)
27a3f09b
SA
988 if (ch.decoder_ == dec)
989 channel_list.push_back(&ch);
47747218 990
27a3f09b
SA
991 dec->set_channels(channel_list);
992 }
aa71890d
SA
993
994 // Channel bit IDs must be in sync with the channel's apperance in channels_
995 int id = 0;
a82325d1 996 for (decode::DecodeChannel& ch : channels_)
aa71890d
SA
997 if (ch.assigned_signal)
998 ch.bit_id = id++;
47747218
SA
999}
1000
ed535cd7 1001void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
47747218 1002{
27a3f09b
SA
1003 // Enforce end to be greater than start
1004 if (end <= start)
1005 return;
1006
ed535cd7 1007 // Fetch the channel segments and their data
27a3f09b
SA
1008 vector<shared_ptr<LogicSegment> > segments;
1009 vector<const uint8_t*> signal_data;
1010 vector<uint8_t> signal_in_bytepos;
1011 vector<uint8_t> signal_in_bitpos;
1012
a82325d1 1013 for (decode::DecodeChannel& ch : channels_)
27a3f09b
SA
1014 if (ch.assigned_signal) {
1015 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
ed535cd7
SA
1016
1017 shared_ptr<LogicSegment> segment;
1018 try {
1019 segment = logic_data->logic_segments().at(segment_id);
30677c13 1020 } catch (out_of_range&) {
ed535cd7
SA
1021 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
1022 << "has no logic segment" << segment_id;
1023 return;
1024 }
27a3f09b 1025 segments.push_back(segment);
b82243f7
SA
1026
1027 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
1028 segment->get_samples(start, end, data);
1029 signal_data.push_back(data);
27a3f09b
SA
1030
1031 const int bitpos = ch.assigned_signal->logic_bit_index();
1032 signal_in_bytepos.push_back(bitpos / 8);
1033 signal_in_bitpos.push_back(bitpos % 8);
1034 }
1035
ed535cd7
SA
1036
1037 shared_ptr<LogicSegment> output_segment;
1038 try {
1039 output_segment = logic_mux_data_->logic_segments().at(segment_id);
30677c13 1040 } catch (out_of_range&) {
ed535cd7
SA
1041 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1042 << segment_id << "in mux_logic_samples(), mux segments size is" \
1043 << logic_mux_data_->logic_segments().size();
1044 return;
1045 }
1046
27a3f09b 1047 // Perform the muxing of signal data into the output data
8a603e13 1048 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
27a3f09b
SA
1049 unsigned int signal_count = signal_data.size();
1050
3b5282a2
SA
1051 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1052 sample_cnt++) {
1053
27a3f09b
SA
1054 int bitpos = 0;
1055 uint8_t bytepos = 0;
1056
8a603e13
SA
1057 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1058 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
27a3f09b 1059 output[out_sample_pos + i] = 0;
47747218 1060
27a3f09b
SA
1061 for (unsigned int i = 0; i < signal_count; i++) {
1062 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1063 const uint8_t in_sample = 1 &
1064 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
47747218 1065
27a3f09b
SA
1066 const uint8_t out_sample = output[out_sample_pos + bytepos];
1067
1068 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1069
1070 bitpos++;
1071 if (bitpos > 7) {
1072 bitpos = 0;
1073 bytepos++;
1074 }
1075 }
47747218
SA
1076 }
1077
8a603e13 1078 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
27a3f09b
SA
1079 delete[] output;
1080
1081 for (const uint8_t* data : signal_data)
1082 delete[] data;
1083}
1084
1085void DecodeSignal::logic_mux_proc()
1086{
ed535cd7
SA
1087 uint32_t segment_id = 0;
1088
8a603e13
SA
1089 assert(logic_mux_data_);
1090
65efd025
SA
1091 // Create initial logic mux segment
1092 shared_ptr<LogicSegment> output_segment =
85a70280
SA
1093 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1094 logic_mux_unit_size_, 0);
65efd025 1095 logic_mux_data_->push_segment(output_segment);
8a603e13
SA
1096
1097 output_segment->set_samplerate(get_input_samplerate(0));
ed535cd7 1098
27a3f09b 1099 do {
ed535cd7 1100 const uint64_t input_sample_count = get_working_sample_count(segment_id);
8a603e13 1101 const uint64_t output_sample_count = output_segment->get_sample_count();
27a3f09b
SA
1102
1103 const uint64_t samples_to_process =
1104 (input_sample_count > output_sample_count) ?
1105 (input_sample_count - output_sample_count) : 0;
1106
1107 // Process the samples if necessary...
1108 if (samples_to_process > 0) {
8a603e13 1109 const uint64_t unit_size = output_segment->unit_size();
27a3f09b
SA
1110 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1111
1112 uint64_t processed_samples = 0;
1113 do {
1114 const uint64_t start_sample = output_sample_count + processed_samples;
1115 const uint64_t sample_count =
1116 min(samples_to_process - processed_samples, chunk_sample_count);
1117
ed535cd7 1118 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
27a3f09b
SA
1119 processed_samples += sample_count;
1120
1121 // ...and process the newly muxed logic data
1122 decode_input_cond_.notify_one();
3b5282a2 1123 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
27a3f09b
SA
1124 }
1125
1ec191ed 1126 if (samples_to_process == 0) {
ed535cd7
SA
1127 // TODO Optimize this by caching the input segment count and only
1128 // querying it when the cached value was reached
1129 if (segment_id < get_input_segment_count() - 1) {
1130 // Process next segment
1131 segment_id++;
1132
65efd025 1133 output_segment =
85a70280
SA
1134 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1135 logic_mux_unit_size_, 0);
65efd025 1136 logic_mux_data_->push_segment(output_segment);
ba5f2186 1137
8a603e13
SA
1138 output_segment->set_samplerate(get_input_samplerate(segment_id));
1139
ed535cd7
SA
1140 } else {
1141 // All segments have been processed
1142 logic_mux_data_invalid_ = false;
1143
1144 // Wait for more input
1145 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1146 logic_mux_cond_.wait(logic_mux_lock);
1147 }
27a3f09b 1148 }
1ae18301 1149
1ec191ed 1150 } while (!logic_mux_interrupt_);
47747218
SA
1151}
1152
1153void DecodeSignal::decode_data(
8a603e13
SA
1154 const int64_t abs_start_samplenum, const int64_t sample_count,
1155 const shared_ptr<LogicSegment> input_segment)
47747218 1156{
8a603e13 1157 const int64_t unit_size = input_segment->unit_size();
27a3f09b 1158 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
47747218
SA
1159
1160 for (int64_t i = abs_start_samplenum;
1ae18301
SA
1161 error_message_.isEmpty() && !decode_interrupt_ &&
1162 (i < (abs_start_samplenum + sample_count));
47747218
SA
1163 i += chunk_sample_count) {
1164
1165 const int64_t chunk_end = min(i + chunk_sample_count,
1166 abs_start_samplenum + sample_count);
1167
e06cf18d
SA
1168 {
1169 lock_guard<mutex> lock(output_mutex_);
b82908ab
SA
1170 // Update the sample count showing the samples including currently processed ones
1171 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
e06cf18d
SA
1172 }
1173
b82243f7
SA
1174 int64_t data_size = (chunk_end - i) * unit_size;
1175 uint8_t* chunk = new uint8_t[data_size];
8a603e13 1176 input_segment->get_samples(i, chunk_end, chunk);
47747218 1177
e91883bb 1178 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1ae18301 1179 data_size, unit_size) != SRD_OK)
403c3e87 1180 set_error_message(tr("Decoder reported an error"));
a3ebd556 1181
47747218
SA
1182 delete[] chunk;
1183
b82908ab
SA
1184 {
1185 lock_guard<mutex> lock(output_mutex_);
1186 // Now that all samples are processed, the exclusive sample count catches up
1187 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1188 }
1189
1b56c646
SA
1190 // Notify the frontend that we processed some data and
1191 // possibly have new annotations as well
1192 new_annotations();
556259d2
SA
1193
1194 if (decode_paused_) {
1195 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1196 decode_pause_cond_.wait(pause_wait_lock);
1197 }
47747218
SA
1198 }
1199}
1200
1201void DecodeSignal::decode_proc()
1202{
65efd025
SA
1203 current_segment_id_ = 0;
1204
1205 // If there is no input data available yet, wait until it is or we're interrupted
1206 if (logic_mux_data_->logic_segments().size() == 0) {
1207 unique_lock<mutex> input_wait_lock(input_mutex_);
1208 decode_input_cond_.wait(input_wait_lock);
1209 }
a3ebd556
SA
1210
1211 if (decode_interrupt_)
1212 return;
1213
8a603e13 1214 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
8a603e13 1215 assert(input_segment);
65efd025
SA
1216
1217 // Create the initial segment and set its sample rate so that we can pass it to SRD
1218 create_decode_segment();
8a603e13 1219 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 1220 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 1221
65efd025
SA
1222 start_srd_session();
1223
1224 uint64_t sample_count = 0;
27a3f09b 1225 uint64_t abs_start_samplenum = 0;
47747218 1226 do {
27a3f09b
SA
1227 // Keep processing new samples until we exhaust the input data
1228 do {
767bf4e7 1229 lock_guard<mutex> input_lock(input_mutex_);
8a603e13 1230 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
27a3f09b
SA
1231
1232 if (sample_count > 0) {
8a603e13 1233 decode_data(abs_start_samplenum, sample_count, input_segment);
27a3f09b
SA
1234 abs_start_samplenum += sample_count;
1235 }
1b56c646
SA
1236 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
1237
8a603e13
SA
1238 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
1239 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
1240 // Process next segment
1241 current_segment_id_++;
1242
1243 try {
1244 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
30677c13 1245 } catch (out_of_range&) {
8a603e13
SA
1246 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1247 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1248 << logic_mux_data_->logic_segments().size();
1249 return;
1250 }
1251 abs_start_samplenum = 0;
1252
65efd025
SA
1253 // Create the next segment and set its metadata
1254 create_decode_segment();
8a603e13 1255 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 1256 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 1257
90ca4cc8
SA
1258 // Reset decoder state but keep the decoder stack intact
1259 terminate_srd_session();
8a603e13
SA
1260 } else {
1261 // All segments have been processed
1b56c646 1262 decode_finished();
27a3f09b 1263
8a603e13
SA
1264 // Wait for new input data or an interrupt was requested
1265 unique_lock<mutex> input_wait_lock(input_mutex_);
1266 decode_input_cond_.wait(input_wait_lock);
1267 }
27a3f09b
SA
1268 }
1269 } while (error_message_.isEmpty() && !decode_interrupt_);
ce0b6a40
GS
1270
1271 // Potentially reap decoders when the application no longer is
1272 // interested in their (pending) results.
1273 if (decode_interrupt_)
1274 terminate_srd_session();
e91883bb
SA
1275}
1276
1277void DecodeSignal::start_srd_session()
1278{
8ce0e732
SA
1279 // If there were stack changes, the session has been destroyed by now, so if
1280 // it hasn't been destroyed, we can just reset and re-use it
ce0b6a40
GS
1281 if (srd_session_) {
1282 // When a decoder stack was created before, re-use it
1283 // for the next stream of input data, after terminating
1284 // potentially still executing operations, and resetting
1285 // internal state. Skip the rather expensive (teardown
1286 // and) construction of another decoder stack.
1287
1288 // TODO Reduce redundancy, use a common code path for
72486b78 1289 // the meta/start sequence?
ce0b6a40 1290 terminate_srd_session();
72486b78
SA
1291
1292 // Metadata is cleared also, so re-set it
ba5b52e1 1293 uint64_t samplerate = 0;
7dd518b8 1294 if (segments_.size() > 0)
ba5b52e1
GS
1295 samplerate = segments_.at(current_segment_id_).samplerate;
1296 if (samplerate)
7dd518b8 1297 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
ba5b52e1 1298 g_variant_new_uint64(samplerate));
6a26fc44 1299 for (const shared_ptr<Decoder>& dec : stack_)
72486b78 1300 dec->apply_all_options();
ce0b6a40 1301 srd_session_start(srd_session_);
72486b78 1302
ce0b6a40
GS
1303 return;
1304 }
e91883bb 1305
a3ebd556
SA
1306 // Create the session
1307 srd_session_new(&srd_session_);
1308 assert(srd_session_);
47747218 1309
a3ebd556
SA
1310 // Create the decoders
1311 srd_decoder_inst *prev_di = nullptr;
6a26fc44 1312 for (const shared_ptr<Decoder>& dec : stack_) {
a3ebd556 1313 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
e91883bb 1314
a3ebd556 1315 if (!di) {
403c3e87 1316 set_error_message(tr("Failed to create decoder instance"));
a3ebd556 1317 srd_session_destroy(srd_session_);
c5f9553c 1318 srd_session_ = nullptr;
a3ebd556
SA
1319 return;
1320 }
e91883bb 1321
a3ebd556
SA
1322 if (prev_di)
1323 srd_inst_stack(srd_session_, prev_di, di);
e91883bb 1324
a3ebd556 1325 prev_di = di;
e91883bb 1326 }
a3ebd556
SA
1327
1328 // Start the session
7dd518b8
SA
1329 if (segments_.size() > 0)
1330 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1331 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
a3ebd556
SA
1332
1333 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1334 DecodeSignal::annotation_callback, this);
1335
c0c3e62a
SA
1336 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1337 DecodeSignal::binary_callback, this);
1338
a3ebd556 1339 srd_session_start(srd_session_);
e3202557
SA
1340
1341 // We just recreated the srd session, so all stack changes are applied now
1342 stack_config_changed_ = false;
e91883bb 1343}
47747218 1344
ce0b6a40
GS
1345void DecodeSignal::terminate_srd_session()
1346{
1347 // Call the "terminate and reset" routine for the decoder stack
1348 // (if available). This does not harm those stacks which already
1349 // have completed their operation, and reduces response time for
1350 // those stacks which still are processing data while the
1351 // application no longer wants them to.
72486b78 1352 if (srd_session_) {
ce0b6a40 1353 srd_session_terminate_reset(srd_session_);
72486b78
SA
1354
1355 // Metadata is cleared also, so re-set it
ba5b52e1 1356 uint64_t samplerate = 0;
7dd518b8 1357 if (segments_.size() > 0)
ba5b52e1
GS
1358 samplerate = segments_.at(current_segment_id_).samplerate;
1359 if (samplerate)
7dd518b8 1360 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
ba5b52e1 1361 g_variant_new_uint64(samplerate));
6a26fc44 1362 for (const shared_ptr<Decoder>& dec : stack_)
72486b78
SA
1363 dec->apply_all_options();
1364 }
ce0b6a40
GS
1365}
1366
e91883bb
SA
1367void DecodeSignal::stop_srd_session()
1368{
1369 if (srd_session_) {
1370 // Destroy the session
1371 srd_session_destroy(srd_session_);
1372 srd_session_ = nullptr;
8ce0e732
SA
1373
1374 // Mark the decoder instances as non-existant since they were deleted
6a26fc44 1375 for (const shared_ptr<Decoder>& dec : stack_)
8ce0e732 1376 dec->invalidate_decoder_inst();
e91883bb 1377 }
47747218
SA
1378}
1379
a8a9222d
SA
1380void DecodeSignal::connect_input_notifiers()
1381{
1382 // Disconnect the notification slot from the previous set of signals
1b56c646 1383 disconnect(this, SLOT(on_data_cleared()));
a8a9222d
SA
1384 disconnect(this, SLOT(on_data_received()));
1385
1386 // Connect the currently used signals to our slot
a82325d1 1387 for (decode::DecodeChannel& ch : channels_) {
a8a9222d
SA
1388 if (!ch.assigned_signal)
1389 continue;
1390
1b56c646
SA
1391 const data::SignalBase *signal = ch.assigned_signal;
1392 connect(signal, SIGNAL(samples_cleared()),
1393 this, SLOT(on_data_cleared()));
b10b58f4 1394 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
a8a9222d
SA
1395 this, SLOT(on_data_received()));
1396 }
1397}
1398
65efd025 1399void DecodeSignal::create_decode_segment()
4913560f 1400{
65efd025 1401 // Create annotation segment
f54e68b0 1402 segments_.emplace_back();
72435789 1403
65efd025 1404 // Add annotation classes
feda6c6b 1405 for (const shared_ptr<Decoder>& dec : stack_)
6a26fc44
SA
1406 for (Row* row : dec->get_rows())
1407 segments_.back().annotation_rows.emplace(row, RowData(row));
e77de61f
SA
1408
1409 // Prepare our binary output classes
6a26fc44 1410 for (const shared_ptr<Decoder>& dec : stack_) {
ac9494ef 1411 uint32_t n = dec->get_binary_class_count();
e77de61f 1412
ac9494ef 1413 for (uint32_t i = 0; i < n; i++)
e77de61f 1414 segments_.back().binary_classes.push_back(
c8a6db0e 1415 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
e77de61f 1416 }
4913560f
SA
1417}
1418
47747218
SA
1419void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1420{
1421 assert(pdata);
b21501d6 1422 assert(decode_signal);
47747218
SA
1423
1424 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1425 assert(ds);
1426
3b5282a2
SA
1427 if (ds->decode_interrupt_)
1428 return;
1429
02c87df7
SA
1430 if (ds->segments_.empty())
1431 return;
1432
47747218
SA
1433 lock_guard<mutex> lock(ds->output_mutex_);
1434
c0c3e62a 1435 // Get the decoder and the annotation data
47747218
SA
1436 assert(pdata->pdo);
1437 assert(pdata->pdo->di);
6a26fc44
SA
1438 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1439 assert(srd_dec);
47747218 1440
c0c3e62a 1441 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1becee23
UH
1442 assert(pda);
1443
c0c3e62a 1444 // Find the row
6a26fc44
SA
1445 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1446 assert(dec);
47747218 1447
6a26fc44 1448 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
4526de63
SA
1449 if (!ann_class) {
1450 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1451 "with class ID" << pda->ann_class << "but there are only" <<
1452 dec->ann_classes().size() << "known classes";
1453 return;
1454 }
6a26fc44
SA
1455
1456 const Row* row = ann_class->row;
1457
1458 if (!row)
1459 row = dec->get_row_by_id(0);
47747218 1460
f54e68b0
SA
1461 RowData& row_data = ds->segments_[ds->current_segment_id_].annotation_rows.at(row);
1462
1463 // Add the annotation to the row
1464 const Annotation* ann = row_data.emplace_annotation(pdata);
1465
ca9a5918
SA
1466 // We insert the annotation into the global annotation list in a way so that
1467 // the annotation list is sorted by start sample and length. Otherwise, we'd
1468 // have to sort the model, which is expensive
f54e68b0
SA
1469 deque<const Annotation*>& all_annotations =
1470 ds->segments_[ds->current_segment_id_].all_annotations;
ca9a5918
SA
1471
1472 if (all_annotations.empty()) {
1473 all_annotations.emplace_back(ann);
1474 } else {
1475 const uint64_t new_ann_len = (pdata->end_sample - pdata->start_sample);
1476 bool ann_has_earlier_start = (pdata->start_sample < all_annotations.back()->start_sample());
1477 bool ann_is_longer = (new_ann_len >
1478 (all_annotations.back()->end_sample() - all_annotations.back()->start_sample()));
1479
1480 if (ann_has_earlier_start && ann_is_longer) {
1481 bool ann_has_same_start;
1482 auto it = all_annotations.end();
1483
1484 do {
1485 it--;
1486 ann_has_earlier_start = (pdata->start_sample < (*it)->start_sample());
1487 ann_has_same_start = (pdata->start_sample == (*it)->start_sample());
d656b010 1488 ann_is_longer = (new_ann_len > (*it)->length());
ca9a5918
SA
1489 } while ((ann_has_earlier_start || (ann_has_same_start && ann_is_longer)) && (it != all_annotations.begin()));
1490
1491 // Allow inserting at the front
1492 if (it != all_annotations.begin())
1493 it++;
1494
1495 all_annotations.emplace(it, ann);
1496 } else
1497 all_annotations.emplace_back(ann);
1498 }
88a25978
SA
1499
1500 // When emplace_annotation() inserts instead of appends an annotation,
1501 // the pointers in all_annotations that follow the inserted annotation and
1502 // point to annotations for this row are off by one and must be updated
1503 if (&(row_data.annotations().back()) != ann) {
1504 // Search backwards until we find the annotation we just added
1505 auto row_it = row_data.annotations().end();
1506 auto all_it = all_annotations.end();
1507 do {
1508 all_it--;
1509 if ((*all_it)->row_data() == &row_data)
1510 row_it--;
1511 } while (&(*row_it) != ann);
1512
1513 // Update the annotation addresses for this row's annotations until the end
1514 do {
1515 if ((*all_it)->row_data() == &row_data) {
1516 *all_it = &(*row_it);
1517 row_it++;
1518 }
1519 all_it++;
1520 } while (all_it != all_annotations.end());
1521 }
47747218
SA
1522}
1523
c0c3e62a
SA
1524void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1525{
1526 assert(pdata);
1527 assert(decode_signal);
1528
1529 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1530 assert(ds);
1531
1532 if (ds->decode_interrupt_)
1533 return;
1534
e77de61f
SA
1535 // Get the decoder and the binary data
1536 assert(pdata->pdo);
1537 assert(pdata->pdo->di);
6a26fc44
SA
1538 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1539 assert(srd_dec);
e77de61f 1540
c0c3e62a
SA
1541 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1542 assert(pdb);
1543
e77de61f 1544 // Find the matching DecodeBinaryClass
c0c3e62a
SA
1545 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1546
e77de61f
SA
1547 DecodeBinaryClass* bin_class = nullptr;
1548 for (DecodeBinaryClass& bc : segment->binary_classes)
6a26fc44
SA
1549 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1550 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
e77de61f 1551 bin_class = &bc;
c0c3e62a 1552
e77de61f
SA
1553 if (!bin_class) {
1554 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1555 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1556 ", segment only knows" << segment->binary_classes.size() << "classes";
1557 return;
1558 }
c0c3e62a 1559
e77de61f
SA
1560 // Add the data chunk
1561 bin_class->chunks.emplace_back();
1562 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1563
1564 chunk->sample = pdata->start_sample;
1565 chunk->data.resize(pdb->size);
1566 memcpy(chunk->data.data(), pdb->data, pdb->size);
1567
6a26fc44 1568 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
b2b18d3a
SA
1569
1570 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
c0c3e62a
SA
1571}
1572
47747218
SA
1573void DecodeSignal::on_capture_state_changed(int state)
1574{
1575 // If a new acquisition was started, we need to start decoding from scratch
ba5f2186
SA
1576 if (state == Session::Running) {
1577 logic_mux_data_invalid_ = true;
47747218 1578 begin_decode();
ba5f2186 1579 }
47747218
SA
1580}
1581
1b56c646
SA
1582void DecodeSignal::on_data_cleared()
1583{
1584 reset_decode();
1585}
1586
47747218
SA
1587void DecodeSignal::on_data_received()
1588{
5620539c
SA
1589 // If we detected a lack of input data when trying to start decoding,
1590 // we have set an error message. Only try again if we now have data
1591 // to work with
1592 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1593 return;
1594
1b56c646
SA
1595 if (!logic_mux_thread_.joinable())
1596 begin_decode();
1597 else
1598 logic_mux_cond_.notify_one();
47747218
SA
1599}
1600
02078aa1
SA
1601void DecodeSignal::on_annotation_visibility_changed()
1602{
1603 annotation_visibility_changed();
1604}
1605
ad908057
SA
1606} // namespace data
1607} // namespace pv