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