]> sigrok.org Git - pulseview.git/blame - pv/data/decodesignal.cpp
Fix #1629 more by fixing the notification 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),
f6a93932 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 172 if (!error_message_.isEmpty()) {
66b6f41b 173 error_message_.clear();
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
144e72c9 234 if (get_input_segment_count() == 0)
403c3e87 235 set_error_message(tr("No input data"));
ed535cd7 236
27a3f09b
SA
237 // Make sure the logic output data is complete and up-to-date
238 logic_mux_interrupt_ = false;
239 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
240
241 // Decode the muxed logic data
47747218
SA
242 decode_interrupt_ = false;
243 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
946b52e1
SA
244}
245
556259d2
SA
246void DecodeSignal::pause_decode()
247{
248 decode_paused_ = true;
249}
250
251void DecodeSignal::resume_decode()
252{
253 // Manual unlocking is done before notifying, to avoid waking up the
254 // waiting thread only to block again (see notify_one for details)
255 decode_pause_mutex_.unlock();
256 decode_pause_cond_.notify_one();
257 decode_paused_ = false;
258}
259
260bool DecodeSignal::is_paused() const
261{
262 return decode_paused_;
263}
264
a82325d1 265const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
9f97b357
SA
266{
267 return channels_;
268}
269
762ab7a4 270void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
132a5c6d 271{
47747218
SA
272 bool new_assignment = false;
273
db51130d
SA
274 // Disconnect all input signal notifications so we don't have duplicate connections
275 disconnect_input_notifiers();
276
132a5c6d 277 // Try to auto-select channels that don't have signals assigned yet
a82325d1 278 for (decode::DecodeChannel& ch : channels_) {
762ab7a4
SA
279 // If a decoder is given, auto-assign only its channels
280 if (dec && (ch.decoder_ != dec))
281 continue;
282
132a5c6d
SA
283 if (ch.assigned_signal)
284 continue;
285
c526a8fd
SA
286 QString ch_name = ch.name.toLower();
287 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
a8030bb0
SA
288
289 shared_ptr<data::SignalBase> match;
f4ab4b5c 290 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
f9ebf303
SA
291 if (!s->enabled())
292 continue;
293
c526a8fd
SA
294 QString s_name = s->name().toLower();
295 s_name = s_name.replace(QRegExp("[-_.]"), " ");
692f6093
SA
296
297 if (s->logic_data() &&
298 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
a8030bb0
SA
299 if (!match)
300 match = s;
301 else {
302 // Only replace an existing match if it matches more characters
303 int old_unmatched = ch_name.length() - match->name().length();
304 int new_unmatched = ch_name.length() - s->name().length();
305 if (abs(new_unmatched) < abs(old_unmatched))
306 match = s;
307 }
47747218 308 }
692f6093 309 }
a8030bb0 310
8ff61402
SA
311 // Prevent using a signal more than once as D1 would match e.g. D1 and D10
312 bool signal_not_already_used = true;
313 for (decode::DecodeChannel& ch : channels_)
314 if (ch.assigned_signal && (ch.assigned_signal == match))
315 signal_not_already_used = false;
316
317 if (match && signal_not_already_used) {
cf1541a1 318 ch.assigned_signal = match;
a8030bb0
SA
319 new_assignment = true;
320 }
47747218
SA
321 }
322
323 if (new_assignment) {
db51130d
SA
324 // Receive notifications when new sample data is available
325 connect_input_notifiers();
326
47747218 327 logic_mux_data_invalid_ = true;
e3202557 328 stack_config_changed_ = true;
27a3f09b 329 commit_decoder_channels();
47747218 330 channels_updated();
132a5c6d
SA
331 }
332}
333
cf1541a1 334void DecodeSignal::assign_signal(const uint16_t channel_id, shared_ptr<const SignalBase> signal)
9f97b357 335{
db51130d
SA
336 // Disconnect all input signal notifications so we don't have duplicate connections
337 disconnect_input_notifiers();
338
a82325d1 339 for (decode::DecodeChannel& ch : channels_)
47747218 340 if (ch.id == channel_id) {
9f97b357 341 ch.assigned_signal = signal;
47747218
SA
342 logic_mux_data_invalid_ = true;
343 }
9f97b357 344
db51130d
SA
345 // Receive notifications when new sample data is available
346 connect_input_notifiers();
347
e3202557 348 stack_config_changed_ = true;
27a3f09b 349 commit_decoder_channels();
9f97b357 350 channels_updated();
47747218 351 begin_decode();
9f97b357
SA
352}
353
27a3f09b
SA
354int DecodeSignal::get_assigned_signal_count() const
355{
356 // Count all channels that have a signal assigned to them
357 return count_if(channels_.begin(), channels_.end(),
cf1541a1 358 [](decode::DecodeChannel ch) { return ch.assigned_signal.get(); });
27a3f09b
SA
359}
360
9f97b357
SA
361void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
362{
a82325d1 363 for (decode::DecodeChannel& ch : channels_)
9f97b357
SA
364 if (ch.id == channel_id)
365 ch.initial_pin_state = init_state;
366
e3202557 367 stack_config_changed_ = true;
9f97b357 368 channels_updated();
47747218 369 begin_decode();
9f97b357
SA
370}
371
85125b0f 372double DecodeSignal::get_samplerate() const
ff83d980 373{
72435789
SA
374 double result = 0;
375
376 // TODO For now, we simply return the first samplerate that we have
8a603e13
SA
377 if (segments_.size() > 0)
378 result = segments_.front().samplerate;
72435789
SA
379
380 return result;
ff83d980
SA
381}
382
72435789 383const pv::util::Timestamp DecodeSignal::start_time() const
ff83d980 384{
72435789
SA
385 pv::util::Timestamp result;
386
387 // TODO For now, we simply return the first start time that we have
8a603e13
SA
388 if (segments_.size() > 0)
389 result = segments_.front().start_time;
72435789
SA
390
391 return result;
ff83d980
SA
392}
393
5ecf957f 394int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
0c5fe73e
SA
395{
396 // The working sample count is the highest sample number for
ed535cd7
SA
397 // which all used signals have data available, so go through all
398 // channels and use the lowest overall sample count of the segment
0c5fe73e 399
0c5fe73e
SA
400 int64_t count = std::numeric_limits<int64_t>::max();
401 bool no_signals_assigned = true;
402
a82325d1 403 for (const decode::DecodeChannel& ch : channels_)
0c5fe73e 404 if (ch.assigned_signal) {
1774d669
SA
405 if (!ch.assigned_signal->logic_data())
406 return 0;
407
0c5fe73e
SA
408 no_signals_assigned = false;
409
410 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
1774d669 411 if (logic_data->logic_segments().empty())
0c5fe73e
SA
412 return 0;
413
1774d669 414 if (segment_id >= logic_data->logic_segments().size())
5ecf957f 415 return 0;
1774d669 416
cf1541a1
SA
417 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
418 if (segment)
419 count = min(count, (int64_t)segment->get_sample_count());
0c5fe73e
SA
420 }
421
422 return (no_signals_assigned ? 0 : count);
423}
424
b82908ab
SA
425int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
426 bool include_processing) const
ff83d980 427{
47747218 428 lock_guard<mutex> decode_lock(output_mutex_);
5ecf957f
SA
429
430 int64_t result = 0;
431
c8a6db0e
SA
432 if (segment_id >= segments_.size())
433 return result;
434
435 if (include_processing)
436 result = segments_[segment_id].samples_decoded_incl;
437 else
438 result = segments_[segment_id].samples_decoded_excl;
5ecf957f
SA
439
440 return result;
ff83d980
SA
441}
442
6a26fc44 443vector<Row*> DecodeSignal::get_rows(bool visible_only)
ecd07c20 444{
6a26fc44 445 vector<Row*> rows;
47747218 446
6a26fc44 447 for (const shared_ptr<Decoder>& dec : stack_) {
47747218 448 assert(dec);
5d3ca591 449 if (visible_only && !dec->visible())
cbb2e4da
SA
450 continue;
451
6a26fc44
SA
452 for (Row* row : dec->get_rows())
453 rows.push_back(row);
454 }
47747218 455
6a26fc44
SA
456 return rows;
457}
47747218 458
6a26fc44
SA
459vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
460{
461 vector<const Row*> rows;
462
463 for (const shared_ptr<Decoder>& dec : stack_) {
464 assert(dec);
5d3ca591 465 if (visible_only && !dec->visible())
6a26fc44
SA
466 continue;
467
468 for (const Row* row : dec->get_rows())
469 rows.push_back(row);
47747218
SA
470 }
471
472 return rows;
ecd07c20
SA
473}
474
6a26fc44
SA
475
476uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
f994f496
SA
477{
478 if (segment_id >= segments_.size())
479 return 0;
480
6a26fc44 481 const DecodeSegment* segment = &(segments_.at(segment_id));
f994f496 482
6a26fc44 483 auto row_it = segment->annotation_rows.find(row);
f994f496 484
6a26fc44 485 const RowData* rd;
5a9146ac 486 if (row_it == segment->annotation_rows.end())
6a26fc44 487 return 0;
5a9146ac 488 else
6a26fc44
SA
489 rd = &(row_it->second);
490
491 return rd->get_annotation_count();
f994f496
SA
492}
493
462941e2 494void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
6a26fc44 495 const Row* row, uint32_t segment_id, uint64_t start_sample,
ecd07c20
SA
496 uint64_t end_sample) const
497{
47747218
SA
498 lock_guard<mutex> lock(output_mutex_);
499
c8a6db0e
SA
500 if (segment_id >= segments_.size())
501 return;
72435789 502
6a26fc44
SA
503 const DecodeSegment* segment = &(segments_.at(segment_id));
504
505 auto row_it = segment->annotation_rows.find(row);
c8a6db0e 506
6a26fc44 507 const RowData* rd;
5a9146ac 508 if (row_it == segment->annotation_rows.end())
6a26fc44 509 return;
5a9146ac 510 else
6a26fc44
SA
511 rd = &(row_it->second);
512
513 rd->get_annotation_subset(dest, start_sample, end_sample);
47747218
SA
514}
515
462941e2 516void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
5a914348
SA
517 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
518{
462941e2
SA
519 for (const Row* row : get_rows())
520 get_annotation_subset(dest, row, segment_id, start_sample, end_sample);
5a914348
SA
521}
522
e77de61f 523uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
ac9494ef 524 const Decoder* dec, uint32_t bin_class_id) const
c0c3e62a 525{
1774d669 526 if ((segments_.size() == 0) || (segment_id >= segments_.size()))
c8a6db0e
SA
527 return 0;
528
1774d669 529 const DecodeSegment *segment = &(segments_[segment_id]);
e77de61f 530
1774d669
SA
531 for (const DecodeBinaryClass& bc : segment->binary_classes)
532 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
533 return bc.chunks.size();
c0c3e62a 534
e77de61f 535 return 0;
c0c3e62a
SA
536}
537
e77de61f 538void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
ac9494ef 539 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
c0c3e62a
SA
540 const vector<uint8_t> **dest, uint64_t *size)
541{
1774d669
SA
542 if (segment_id >= segments_.size())
543 return;
e77de61f 544
1774d669
SA
545 const DecodeSegment *segment = &(segments_[segment_id]);
546
547 for (const DecodeBinaryClass& bc : segment->binary_classes)
548 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
549 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
550 if (size) *size = bc.chunks.at(chunk_id).data.size();
551 return;
552 }
c0c3e62a
SA
553}
554
13b726cd 555void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
ac9494ef 556 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
e77de61f 557 uint64_t end_sample, vector<uint8_t> *dest) const
c0c3e62a
SA
558{
559 assert(dest != nullptr);
560
1774d669
SA
561 if (segment_id >= segments_.size())
562 return;
563
564 const DecodeSegment *segment = &(segments_[segment_id]);
565
566 const DecodeBinaryClass* bin_class = nullptr;
567 for (const DecodeBinaryClass& bc : segment->binary_classes)
568 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
569 bin_class = &bc;
570
571 // Determine overall size before copying to resize dest vector only once
572 uint64_t size = 0;
573 uint64_t matches = 0;
574 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
575 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
576 size += chunk.data.size();
577 matches++;
578 }
579 dest->resize(size);
580
581 uint64_t offset = 0;
582 uint64_t matches2 = 0;
583 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
584 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
585 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
586 offset += chunk.data.size();
587 matches2++;
588
589 // Make sure we don't overwrite memory if the array grew in the meanwhile
590 if (matches2 == matches)
591 break;
592 }
c0c3e62a
SA
593}
594
13b726cd 595void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
6a26fc44
SA
596 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
597 vector<uint8_t> *dest) const
13b726cd
SA
598{
599 assert(dest != nullptr);
600
1774d669
SA
601 if (segment_id >= segments_.size())
602 return;
13b726cd 603
1774d669
SA
604 const DecodeSegment *segment = &(segments_[segment_id]);
605
606 const DecodeBinaryClass* bin_class = nullptr;
607 for (const DecodeBinaryClass& bc : segment->binary_classes)
608 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
609 bin_class = &bc;
610
611 // Determine overall size before copying to resize dest vector only once
612 uint64_t size = 0;
613 uint64_t offset = 0;
614 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
615 if (offset >= start)
616 size += chunk.data.size();
617 offset += chunk.data.size();
618 if (offset >= end)
619 break;
620 }
621 dest->resize(size);
622
623 offset = 0;
624 uint64_t dest_offset = 0;
625 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
626 if (offset >= start) {
627 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
628 dest_offset += chunk.data.size();
13b726cd 629 }
1774d669
SA
630 offset += chunk.data.size();
631 if (offset >= end)
632 break;
13b726cd
SA
633 }
634}
635
628b45cc 636const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
6a26fc44 637 const Decoder* dec, uint32_t bin_class_id) const
628b45cc 638{
1774d669
SA
639 if (segment_id >= segments_.size())
640 return nullptr;
628b45cc 641
1774d669
SA
642 const DecodeSegment *segment = &(segments_[segment_id]);
643
644 for (const DecodeBinaryClass& bc : segment->binary_classes)
645 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
646 return &bc;
628b45cc
SA
647
648 return nullptr;
649}
c0c3e62a 650
f54e68b0
SA
651const deque<const Annotation*>* DecodeSignal::get_all_annotations_by_segment(
652 uint32_t segment_id) const
653{
1774d669
SA
654 if (segment_id >= segments_.size())
655 return nullptr;
f54e68b0 656
1774d669
SA
657 const DecodeSegment *segment = &(segments_[segment_id]);
658
659 return &(segment->all_annotations);
f54e68b0
SA
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)
2cc02460 825 if ((signal->name() == assigned_signal_name) && (signal->type() != SignalBase::DecodeChannel))
cf1541a1 826 channel->assigned_signal = signal;
8b5ea5a1
SA
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
144e72c9
SA
841bool DecodeSignal::all_input_segments_complete(uint32_t segment_id) const
842{
843 bool all_complete = true;
844
845 for (const decode::DecodeChannel& ch : channels_)
846 if (ch.assigned_signal) {
847 if (!ch.assigned_signal->logic_data())
848 continue;
849
850 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
851 if (logic_data->logic_segments().empty())
852 return false;
853
854 if (segment_id >= logic_data->logic_segments().size())
855 return false;
856
cf1541a1
SA
857 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
858 if (segment && !segment->is_complete())
144e72c9
SA
859 all_complete = false;
860 }
861
862 return all_complete;
863}
864
8a603e13
SA
865uint32_t DecodeSignal::get_input_segment_count() const
866{
867 uint64_t count = std::numeric_limits<uint64_t>::max();
868 bool no_signals_assigned = true;
869
a82325d1 870 for (const decode::DecodeChannel& ch : channels_)
8a603e13
SA
871 if (ch.assigned_signal) {
872 no_signals_assigned = false;
873
874 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
875 if (!logic_data || logic_data->logic_segments().empty())
876 return 0;
877
878 // Find the min value of all segment counts
879 if ((uint64_t)(logic_data->logic_segments().size()) < count)
880 count = logic_data->logic_segments().size();
881 }
882
883 return (no_signals_assigned ? 0 : count);
884}
885
2a12830c 886double DecodeSignal::get_input_samplerate(uint32_t segment_id) const
8a603e13
SA
887{
888 double samplerate = 0;
889
a82325d1 890 for (const decode::DecodeChannel& ch : channels_)
8a603e13
SA
891 if (ch.assigned_signal) {
892 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
893 if (!logic_data || logic_data->logic_segments().empty())
894 continue;
895
896 try {
cf1541a1
SA
897 const shared_ptr<const LogicSegment> segment =
898 logic_data->logic_segments().at(segment_id)->get_shared_ptr();
899 if (segment)
900 samplerate = segment->samplerate();
30677c13 901 } catch (out_of_range&) {
8a603e13
SA
902 // Do nothing
903 }
904 break;
905 }
906
907 return samplerate;
908}
909
6a26fc44
SA
910Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
911{
912 for (shared_ptr<Decoder>& d : stack_)
913 if (d->get_srd_decoder() == srd_dec)
914 return d.get();
915
916 return nullptr;
917}
918
9f97b357
SA
919void DecodeSignal::update_channel_list()
920{
a82325d1 921 vector<decode::DecodeChannel> prev_channels = channels_;
9f97b357
SA
922 channels_.clear();
923
924 uint16_t id = 0;
925
926 // Copy existing entries, create new as needed
f4ab4b5c 927 for (shared_ptr<Decoder>& decoder : stack_) {
6a26fc44 928 const srd_decoder* srd_dec = decoder->get_srd_decoder();
9f97b357
SA
929 const GSList *l;
930
931 // Mandatory channels
6a26fc44 932 for (l = srd_dec->channels; l; l = l->next) {
9f97b357
SA
933 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
934 bool ch_added = false;
935
936 // Copy but update ID if this channel was in the list before
a82325d1 937 for (decode::DecodeChannel& ch : prev_channels)
9f97b357
SA
938 if (ch.pdch_ == pdch) {
939 ch.id = id++;
940 channels_.push_back(ch);
941 ch_added = true;
942 break;
943 }
944
945 if (!ch_added) {
946 // Create new entry without a mapped signal
a82325d1 947 decode::DecodeChannel ch = {id++, 0, false, nullptr,
9f97b357
SA
948 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
949 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
950 channels_.push_back(ch);
951 }
952 }
953
954 // Optional channels
6a26fc44 955 for (l = srd_dec->opt_channels; l; l = l->next) {
9f97b357
SA
956 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
957 bool ch_added = false;
958
959 // Copy but update ID if this channel was in the list before
a82325d1 960 for (decode::DecodeChannel& ch : prev_channels)
9f97b357
SA
961 if (ch.pdch_ == pdch) {
962 ch.id = id++;
963 channels_.push_back(ch);
964 ch_added = true;
965 break;
966 }
967
968 if (!ch_added) {
969 // Create new entry without a mapped signal
a82325d1 970 decode::DecodeChannel ch = {id++, 0, true, nullptr,
9f97b357
SA
971 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
972 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
973 channels_.push_back(ch);
974 }
975 }
976 }
977
47747218
SA
978 // Invalidate the logic output data if the channel assignment changed
979 if (prev_channels.size() != channels_.size()) {
980 // The number of channels changed, there's definitely a difference
981 logic_mux_data_invalid_ = true;
982 } else {
983 // Same number but assignment may still differ, so compare all channels
984 for (size_t i = 0; i < channels_.size(); i++) {
a82325d1
SA
985 const decode::DecodeChannel& p_ch = prev_channels[i];
986 const decode::DecodeChannel& ch = channels_[i];
47747218
SA
987
988 if ((p_ch.pdch_ != ch.pdch_) ||
989 (p_ch.assigned_signal != ch.assigned_signal)) {
990 logic_mux_data_invalid_ = true;
991 break;
992 }
993 }
994
995 }
996
9f97b357
SA
997 channels_updated();
998}
999
27a3f09b 1000void DecodeSignal::commit_decoder_channels()
ad908057 1001{
27a3f09b 1002 // Submit channel list to every decoder, containing only the relevant channels
6a26fc44 1003 for (shared_ptr<Decoder> dec : stack_) {
a82325d1 1004 vector<decode::DecodeChannel*> channel_list;
27a3f09b 1005
a82325d1 1006 for (decode::DecodeChannel& ch : channels_)
27a3f09b
SA
1007 if (ch.decoder_ == dec)
1008 channel_list.push_back(&ch);
47747218 1009
27a3f09b
SA
1010 dec->set_channels(channel_list);
1011 }
aa71890d
SA
1012
1013 // Channel bit IDs must be in sync with the channel's apperance in channels_
1014 int id = 0;
a82325d1 1015 for (decode::DecodeChannel& ch : channels_)
aa71890d
SA
1016 if (ch.assigned_signal)
1017 ch.bit_id = id++;
47747218
SA
1018}
1019
ed535cd7 1020void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
47747218 1021{
27a3f09b
SA
1022 // Enforce end to be greater than start
1023 if (end <= start)
1024 return;
1025
ed535cd7 1026 // Fetch the channel segments and their data
cf1541a1 1027 vector<shared_ptr<const LogicSegment> > segments;
27a3f09b
SA
1028 vector<const uint8_t*> signal_data;
1029 vector<uint8_t> signal_in_bytepos;
1030 vector<uint8_t> signal_in_bitpos;
1031
a82325d1 1032 for (decode::DecodeChannel& ch : channels_)
27a3f09b
SA
1033 if (ch.assigned_signal) {
1034 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
ed535cd7 1035
cf1541a1 1036 shared_ptr<const LogicSegment> segment;
f5a26d5e 1037 if (segment_id < logic_data->logic_segments().size()) {
cf1541a1 1038 segment = logic_data->logic_segments().at(segment_id)->get_shared_ptr();
f5a26d5e 1039 } else {
ed535cd7
SA
1040 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
1041 << "has no logic segment" << segment_id;
cf1541a1 1042 logic_mux_interrupt_ = true;
ed535cd7
SA
1043 return;
1044 }
cf1541a1 1045
f5a26d5e
SA
1046 if (!segment)
1047 return;
cf1541a1 1048
27a3f09b 1049 segments.push_back(segment);
b82243f7
SA
1050
1051 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
1052 segment->get_samples(start, end, data);
1053 signal_data.push_back(data);
27a3f09b
SA
1054
1055 const int bitpos = ch.assigned_signal->logic_bit_index();
1056 signal_in_bytepos.push_back(bitpos / 8);
1057 signal_in_bitpos.push_back(bitpos % 8);
1058 }
1059
ed535cd7
SA
1060 shared_ptr<LogicSegment> output_segment;
1061 try {
1062 output_segment = logic_mux_data_->logic_segments().at(segment_id);
30677c13 1063 } catch (out_of_range&) {
ed535cd7
SA
1064 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1065 << segment_id << "in mux_logic_samples(), mux segments size is" \
1066 << logic_mux_data_->logic_segments().size();
cf1541a1 1067 logic_mux_interrupt_ = true;
ed535cd7
SA
1068 return;
1069 }
1070
27a3f09b 1071 // Perform the muxing of signal data into the output data
8a603e13 1072 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
27a3f09b
SA
1073 unsigned int signal_count = signal_data.size();
1074
3b5282a2
SA
1075 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1076 sample_cnt++) {
1077
27a3f09b
SA
1078 int bitpos = 0;
1079 uint8_t bytepos = 0;
1080
8a603e13
SA
1081 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1082 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
27a3f09b 1083 output[out_sample_pos + i] = 0;
47747218 1084
27a3f09b
SA
1085 for (unsigned int i = 0; i < signal_count; i++) {
1086 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1087 const uint8_t in_sample = 1 &
1088 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
47747218 1089
27a3f09b
SA
1090 const uint8_t out_sample = output[out_sample_pos + bytepos];
1091
1092 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1093
1094 bitpos++;
1095 if (bitpos > 7) {
1096 bitpos = 0;
1097 bytepos++;
1098 }
1099 }
47747218
SA
1100 }
1101
8a603e13 1102 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
27a3f09b
SA
1103 delete[] output;
1104
1105 for (const uint8_t* data : signal_data)
1106 delete[] data;
1107}
1108
1109void DecodeSignal::logic_mux_proc()
1110{
144e72c9
SA
1111 uint32_t input_segment_count;
1112 do {
1113 input_segment_count = get_input_segment_count();
1114 if (input_segment_count == 0) {
1115 // Wait for input data
1116 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1117 logic_mux_cond_.wait(logic_mux_lock);
1118 }
1119 } while ((!logic_mux_interrupt_) && (input_segment_count == 0));
1120
1121 if (logic_mux_interrupt_)
1122 return;
ed535cd7 1123
8a603e13
SA
1124 assert(logic_mux_data_);
1125
144e72c9
SA
1126 uint32_t segment_id = 0;
1127
65efd025
SA
1128 // Create initial logic mux segment
1129 shared_ptr<LogicSegment> output_segment =
cf1541a1 1130 make_shared<LogicSegment>(*logic_mux_data_, segment_id, logic_mux_unit_size_, 0);
65efd025 1131 logic_mux_data_->push_segment(output_segment);
8a603e13
SA
1132
1133 output_segment->set_samplerate(get_input_samplerate(0));
ed535cd7 1134
144e72c9
SA
1135 // Logic mux data is being updated
1136 logic_mux_data_invalid_ = false;
1137
db51130d
SA
1138 connect_input_segment_notifiers(segment_id);
1139
144e72c9 1140 uint64_t samples_to_process;
27a3f09b 1141 do {
144e72c9
SA
1142 do {
1143 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1144 const uint64_t output_sample_count = output_segment->get_sample_count();
27a3f09b 1145
144e72c9
SA
1146 samples_to_process =
1147 (input_sample_count > output_sample_count) ?
1148 (input_sample_count - output_sample_count) : 0;
ed535cd7 1149
144e72c9
SA
1150 if (samples_to_process > 0) {
1151 const uint64_t unit_size = output_segment->unit_size();
1152 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
ba5f2186 1153
144e72c9
SA
1154 uint64_t processed_samples = 0;
1155 do {
1156 const uint64_t start_sample = output_sample_count + processed_samples;
1157 const uint64_t sample_count =
1158 min(samples_to_process - processed_samples, chunk_sample_count);
1159
1160 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1161 processed_samples += sample_count;
1162
1163 // ...and process the newly muxed logic data
1164 decode_input_cond_.notify_one();
1165 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1166 }
1167 } while (!logic_mux_interrupt_ && (samples_to_process > 0));
1168
1169 if (!logic_mux_interrupt_) {
1170 // samples_to_process is now 0, we've exhausted the currently available input data
1171
1172 // If the input segments are complete, we've completed this segment
1173 if (all_input_segments_complete(segment_id)) {
1174 if (!output_segment->is_complete())
1175 output_segment->set_complete();
1176
1177 if (segment_id < get_input_segment_count() - 1) {
db51130d
SA
1178
1179 disconnect_input_segment_notifiers(segment_id);
1180
144e72c9
SA
1181 // Process next segment
1182 segment_id++;
ed535cd7 1183
144e72c9
SA
1184 output_segment =
1185 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1186 logic_mux_unit_size_, 0);
1187 logic_mux_data_->push_segment(output_segment);
1188
1189 output_segment->set_samplerate(get_input_samplerate(segment_id));
db51130d
SA
1190
1191 connect_input_segment_notifiers(segment_id);
9431e2d3
SA
1192 } else {
1193 // Wait for more input data if we're processing the currently last segment
1194 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1195 logic_mux_cond_.wait(logic_mux_lock);
144e72c9 1196 }
db51130d
SA
1197 } else {
1198 // Input segments aren't all complete yet but samples_to_process is 0, wait for more input data
1199 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1200 logic_mux_cond_.wait(logic_mux_lock);
69e95096 1201 }
27a3f09b 1202 }
1ec191ed 1203 } while (!logic_mux_interrupt_);
db51130d
SA
1204
1205 disconnect_input_segment_notifiers(segment_id);
47747218
SA
1206}
1207
1208void DecodeSignal::decode_data(
8a603e13 1209 const int64_t abs_start_samplenum, const int64_t sample_count,
cf1541a1 1210 const shared_ptr<const LogicSegment> input_segment)
47747218 1211{
8a603e13 1212 const int64_t unit_size = input_segment->unit_size();
27a3f09b 1213 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
47747218
SA
1214
1215 for (int64_t i = abs_start_samplenum;
69e95096 1216 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
47747218
SA
1217 i += chunk_sample_count) {
1218
1219 const int64_t chunk_end = min(i + chunk_sample_count,
1220 abs_start_samplenum + sample_count);
1221
e06cf18d
SA
1222 {
1223 lock_guard<mutex> lock(output_mutex_);
b82908ab
SA
1224 // Update the sample count showing the samples including currently processed ones
1225 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
e06cf18d
SA
1226 }
1227
b82243f7
SA
1228 int64_t data_size = (chunk_end - i) * unit_size;
1229 uint8_t* chunk = new uint8_t[data_size];
8a603e13 1230 input_segment->get_samples(i, chunk_end, chunk);
47747218 1231
e91883bb 1232 if (srd_session_send(srd_session_, i, chunk_end, chunk,
144e72c9 1233 data_size, unit_size) != SRD_OK) {
403c3e87 1234 set_error_message(tr("Decoder reported an error"));
144e72c9
SA
1235 decode_interrupt_ = true;
1236 }
a3ebd556 1237
47747218
SA
1238 delete[] chunk;
1239
b82908ab
SA
1240 {
1241 lock_guard<mutex> lock(output_mutex_);
1242 // Now that all samples are processed, the exclusive sample count catches up
1243 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1244 }
1245
1b56c646
SA
1246 // Notify the frontend that we processed some data and
1247 // possibly have new annotations as well
1248 new_annotations();
556259d2
SA
1249
1250 if (decode_paused_) {
1251 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1252 decode_pause_cond_.wait(pause_wait_lock);
1253 }
47747218
SA
1254 }
1255}
1256
1257void DecodeSignal::decode_proc()
1258{
65efd025
SA
1259 current_segment_id_ = 0;
1260
1261 // If there is no input data available yet, wait until it is or we're interrupted
144e72c9
SA
1262 do {
1263 if (logic_mux_data_->logic_segments().size() == 0) {
1264 // Wait for input data
1265 unique_lock<mutex> input_wait_lock(input_mutex_);
1266 decode_input_cond_.wait(input_wait_lock);
1267 }
1268 } while ((!decode_interrupt_) && (logic_mux_data_->logic_segments().size() == 0));
a3ebd556
SA
1269
1270 if (decode_interrupt_)
1271 return;
1272
cf1541a1
SA
1273 shared_ptr<const LogicSegment> input_segment = logic_mux_data_->logic_segments().front()->get_shared_ptr();
1274 if (!input_segment)
1275 return;
65efd025
SA
1276
1277 // Create the initial segment and set its sample rate so that we can pass it to SRD
1278 create_decode_segment();
8a603e13 1279 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 1280 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 1281
65efd025
SA
1282 start_srd_session();
1283
144e72c9 1284 uint64_t samples_to_process = 0;
27a3f09b 1285 uint64_t abs_start_samplenum = 0;
47747218 1286 do {
27a3f09b
SA
1287 // Keep processing new samples until we exhaust the input data
1288 do {
144e72c9 1289 samples_to_process = input_segment->get_sample_count() - abs_start_samplenum;
27a3f09b 1290
144e72c9
SA
1291 if (samples_to_process > 0) {
1292 decode_data(abs_start_samplenum, samples_to_process, input_segment);
1293 abs_start_samplenum += samples_to_process;
27a3f09b 1294 }
144e72c9
SA
1295 } while (!decode_interrupt_ && (samples_to_process > 0));
1296
1297 if (!decode_interrupt_) {
1298 // samples_to_process is now 0, we've exhausted the currently available input data
1299
1300 // If the input segment is complete, we've exhausted this segment
1301 if (input_segment->is_complete()) {
69e95096 1302 if (current_segment_id_ < (logic_mux_data_->logic_segments().size() - 1)) {
144e72c9
SA
1303 // Process next segment
1304 current_segment_id_++;
1305
1306 try {
1307 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1308 } catch (out_of_range&) {
1309 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1310 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1311 << logic_mux_data_->logic_segments().size();
1312 decode_interrupt_ = true;
1313 return;
1314 }
1315 abs_start_samplenum = 0;
1316
1317 // Create the next segment and set its metadata
1318 create_decode_segment();
1319 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1320 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1321
1322 // Reset decoder state but keep the decoder stack intact
1323 terminate_srd_session();
1324 } else {
1325 // All segments have been processed
f5a26d5e
SA
1326 if (!decode_interrupt_)
1327 decode_finished();
9431e2d3
SA
1328
1329 // Wait for more input data
1330 unique_lock<mutex> input_wait_lock(input_mutex_);
1331 decode_input_cond_.wait(input_wait_lock);
8a603e13 1332 }
db51130d
SA
1333 } else {
1334 // Input segment isn't complete yet but samples_to_process is 0, wait for more input data
1335 unique_lock<mutex> input_wait_lock(input_mutex_);
1336 decode_input_cond_.wait(input_wait_lock);
69e95096
SA
1337 }
1338
27a3f09b 1339 }
144e72c9 1340 } while (!decode_interrupt_);
e91883bb
SA
1341}
1342
1343void DecodeSignal::start_srd_session()
1344{
8ce0e732
SA
1345 // If there were stack changes, the session has been destroyed by now, so if
1346 // it hasn't been destroyed, we can just reset and re-use it
ce0b6a40
GS
1347 if (srd_session_) {
1348 // When a decoder stack was created before, re-use it
1349 // for the next stream of input data, after terminating
1350 // potentially still executing operations, and resetting
1351 // internal state. Skip the rather expensive (teardown
1352 // and) construction of another decoder stack.
1353
1354 // TODO Reduce redundancy, use a common code path for
72486b78 1355 // the meta/start sequence?
ce0b6a40 1356 terminate_srd_session();
72486b78
SA
1357
1358 // Metadata is cleared also, so re-set it
ba5b52e1 1359 uint64_t samplerate = 0;
7dd518b8 1360 if (segments_.size() > 0)
ba5b52e1
GS
1361 samplerate = segments_.at(current_segment_id_).samplerate;
1362 if (samplerate)
7dd518b8 1363 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
ba5b52e1 1364 g_variant_new_uint64(samplerate));
6a26fc44 1365 for (const shared_ptr<Decoder>& dec : stack_)
72486b78 1366 dec->apply_all_options();
ce0b6a40 1367 srd_session_start(srd_session_);
72486b78 1368
ce0b6a40
GS
1369 return;
1370 }
e91883bb 1371
a3ebd556
SA
1372 // Create the session
1373 srd_session_new(&srd_session_);
1374 assert(srd_session_);
47747218 1375
a3ebd556
SA
1376 // Create the decoders
1377 srd_decoder_inst *prev_di = nullptr;
6a26fc44 1378 for (const shared_ptr<Decoder>& dec : stack_) {
a3ebd556 1379 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
e91883bb 1380
a3ebd556 1381 if (!di) {
403c3e87 1382 set_error_message(tr("Failed to create decoder instance"));
a3ebd556 1383 srd_session_destroy(srd_session_);
c5f9553c 1384 srd_session_ = nullptr;
a3ebd556
SA
1385 return;
1386 }
e91883bb 1387
a3ebd556
SA
1388 if (prev_di)
1389 srd_inst_stack(srd_session_, prev_di, di);
e91883bb 1390
a3ebd556 1391 prev_di = di;
e91883bb 1392 }
a3ebd556
SA
1393
1394 // Start the session
7dd518b8
SA
1395 if (segments_.size() > 0)
1396 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1397 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
a3ebd556
SA
1398
1399 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1400 DecodeSignal::annotation_callback, this);
1401
c0c3e62a
SA
1402 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1403 DecodeSignal::binary_callback, this);
1404
a3ebd556 1405 srd_session_start(srd_session_);
e3202557
SA
1406
1407 // We just recreated the srd session, so all stack changes are applied now
1408 stack_config_changed_ = false;
e91883bb 1409}
47747218 1410
ce0b6a40
GS
1411void DecodeSignal::terminate_srd_session()
1412{
1413 // Call the "terminate and reset" routine for the decoder stack
1414 // (if available). This does not harm those stacks which already
1415 // have completed their operation, and reduces response time for
1416 // those stacks which still are processing data while the
1417 // application no longer wants them to.
72486b78 1418 if (srd_session_) {
ce0b6a40 1419 srd_session_terminate_reset(srd_session_);
72486b78
SA
1420
1421 // Metadata is cleared also, so re-set it
ba5b52e1 1422 uint64_t samplerate = 0;
7dd518b8 1423 if (segments_.size() > 0)
ba5b52e1
GS
1424 samplerate = segments_.at(current_segment_id_).samplerate;
1425 if (samplerate)
7dd518b8 1426 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
ba5b52e1 1427 g_variant_new_uint64(samplerate));
6a26fc44 1428 for (const shared_ptr<Decoder>& dec : stack_)
72486b78
SA
1429 dec->apply_all_options();
1430 }
ce0b6a40
GS
1431}
1432
e91883bb
SA
1433void DecodeSignal::stop_srd_session()
1434{
1435 if (srd_session_) {
1436 // Destroy the session
1437 srd_session_destroy(srd_session_);
1438 srd_session_ = nullptr;
8ce0e732
SA
1439
1440 // Mark the decoder instances as non-existant since they were deleted
6a26fc44 1441 for (const shared_ptr<Decoder>& dec : stack_)
8ce0e732 1442 dec->invalidate_decoder_inst();
e91883bb 1443 }
47747218
SA
1444}
1445
a8a9222d
SA
1446void DecodeSignal::connect_input_notifiers()
1447{
a8a9222d 1448 // Connect the currently used signals to our slot
a82325d1 1449 for (decode::DecodeChannel& ch : channels_) {
a8a9222d
SA
1450 if (!ch.assigned_signal)
1451 continue;
db51130d
SA
1452 const data::SignalBase *signal = ch.assigned_signal.get();
1453 connect(signal, SIGNAL(samples_cleared()),
1454 this, SLOT(on_data_cleared()));
1455 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1456 this, SLOT(on_data_received()));
1457 }
1458}
a8a9222d 1459
db51130d
SA
1460void DecodeSignal::disconnect_input_notifiers()
1461{
1462 // Disconnect the notification slot from the previous set of signals
1463 for (decode::DecodeChannel& ch : channels_) {
1464 if (!ch.assigned_signal)
1465 continue;
cf1541a1 1466 const data::SignalBase *signal = ch.assigned_signal.get();
db51130d
SA
1467 disconnect(signal, nullptr, this, SLOT(on_data_cleared()));
1468 disconnect(signal, nullptr, this, SLOT(on_data_received()));
a8a9222d
SA
1469 }
1470}
1471
db51130d
SA
1472void DecodeSignal::connect_input_segment_notifiers(uint32_t segment_id)
1473{
1474 for (decode::DecodeChannel& ch : channels_)
1475 if (ch.assigned_signal) {
1476 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
1477
1478 shared_ptr<const LogicSegment> segment;
1479 if (segment_id < logic_data->logic_segments().size()) {
1480 segment = logic_data->logic_segments().at(segment_id)->get_shared_ptr();
1481 } else {
1482 qWarning() << "Signal" << name() << ":" << ch.assigned_signal->name() \
1483 << "has no logic segment, can't connect notifier" << segment_id;
1484 continue;
1485 }
1486
1487 if (!segment)
1488 continue;
1489
1490 connect(segment.get(), SIGNAL(completed()), this, SLOT(on_input_segment_completed()));
1491 }
1492}
1493
1494void DecodeSignal::disconnect_input_segment_notifiers(uint32_t segment_id)
1495{
1496 for (decode::DecodeChannel& ch : channels_)
1497 if (ch.assigned_signal) {
1498 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
1499
1500 shared_ptr<const LogicSegment> segment;
1501 if (segment_id < logic_data->logic_segments().size()) {
1502 segment = logic_data->logic_segments().at(segment_id)->get_shared_ptr();
1503 } else {
1504 continue;
1505 }
1506
1507 if (!segment)
1508 continue;
1509
1510 disconnect(segment.get(), SIGNAL(completed()), this, SLOT(on_input_segment_completed()));
1511 }
1512}
1513
65efd025 1514void DecodeSignal::create_decode_segment()
4913560f 1515{
65efd025 1516 // Create annotation segment
f54e68b0 1517 segments_.emplace_back();
72435789 1518
65efd025 1519 // Add annotation classes
feda6c6b 1520 for (const shared_ptr<Decoder>& dec : stack_)
6a26fc44
SA
1521 for (Row* row : dec->get_rows())
1522 segments_.back().annotation_rows.emplace(row, RowData(row));
e77de61f
SA
1523
1524 // Prepare our binary output classes
6a26fc44 1525 for (const shared_ptr<Decoder>& dec : stack_) {
ac9494ef 1526 uint32_t n = dec->get_binary_class_count();
e77de61f 1527
ac9494ef 1528 for (uint32_t i = 0; i < n; i++)
e77de61f 1529 segments_.back().binary_classes.push_back(
c8a6db0e 1530 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
e77de61f 1531 }
4913560f
SA
1532}
1533
47747218
SA
1534void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1535{
1536 assert(pdata);
b21501d6 1537 assert(decode_signal);
47747218
SA
1538
1539 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1540 assert(ds);
1541
3b5282a2
SA
1542 if (ds->decode_interrupt_)
1543 return;
1544
02c87df7
SA
1545 if (ds->segments_.empty())
1546 return;
1547
47747218
SA
1548 lock_guard<mutex> lock(ds->output_mutex_);
1549
c0c3e62a 1550 // Get the decoder and the annotation data
47747218
SA
1551 assert(pdata->pdo);
1552 assert(pdata->pdo->di);
6a26fc44
SA
1553 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1554 assert(srd_dec);
47747218 1555
c0c3e62a 1556 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1becee23
UH
1557 assert(pda);
1558
c0c3e62a 1559 // Find the row
6a26fc44
SA
1560 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1561 assert(dec);
47747218 1562
6a26fc44 1563 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
4526de63
SA
1564 if (!ann_class) {
1565 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1566 "with class ID" << pda->ann_class << "but there are only" <<
1567 dec->ann_classes().size() << "known classes";
1568 return;
1569 }
6a26fc44
SA
1570
1571 const Row* row = ann_class->row;
1572
1573 if (!row)
1574 row = dec->get_row_by_id(0);
47747218 1575
f54e68b0
SA
1576 RowData& row_data = ds->segments_[ds->current_segment_id_].annotation_rows.at(row);
1577
1578 // Add the annotation to the row
1579 const Annotation* ann = row_data.emplace_annotation(pdata);
1580
ca9a5918
SA
1581 // We insert the annotation into the global annotation list in a way so that
1582 // the annotation list is sorted by start sample and length. Otherwise, we'd
1583 // have to sort the model, which is expensive
f54e68b0
SA
1584 deque<const Annotation*>& all_annotations =
1585 ds->segments_[ds->current_segment_id_].all_annotations;
ca9a5918
SA
1586
1587 if (all_annotations.empty()) {
1588 all_annotations.emplace_back(ann);
1589 } else {
1590 const uint64_t new_ann_len = (pdata->end_sample - pdata->start_sample);
1591 bool ann_has_earlier_start = (pdata->start_sample < all_annotations.back()->start_sample());
1592 bool ann_is_longer = (new_ann_len >
1593 (all_annotations.back()->end_sample() - all_annotations.back()->start_sample()));
1594
1595 if (ann_has_earlier_start && ann_is_longer) {
1596 bool ann_has_same_start;
1597 auto it = all_annotations.end();
1598
1599 do {
1600 it--;
1601 ann_has_earlier_start = (pdata->start_sample < (*it)->start_sample());
1602 ann_has_same_start = (pdata->start_sample == (*it)->start_sample());
d656b010 1603 ann_is_longer = (new_ann_len > (*it)->length());
ca9a5918
SA
1604 } while ((ann_has_earlier_start || (ann_has_same_start && ann_is_longer)) && (it != all_annotations.begin()));
1605
1606 // Allow inserting at the front
1607 if (it != all_annotations.begin())
1608 it++;
1609
1610 all_annotations.emplace(it, ann);
1611 } else
1612 all_annotations.emplace_back(ann);
1613 }
88a25978
SA
1614
1615 // When emplace_annotation() inserts instead of appends an annotation,
1616 // the pointers in all_annotations that follow the inserted annotation and
1617 // point to annotations for this row are off by one and must be updated
1618 if (&(row_data.annotations().back()) != ann) {
1619 // Search backwards until we find the annotation we just added
1620 auto row_it = row_data.annotations().end();
1621 auto all_it = all_annotations.end();
1622 do {
1623 all_it--;
1624 if ((*all_it)->row_data() == &row_data)
1625 row_it--;
1626 } while (&(*row_it) != ann);
1627
1628 // Update the annotation addresses for this row's annotations until the end
1629 do {
1630 if ((*all_it)->row_data() == &row_data) {
1631 *all_it = &(*row_it);
1632 row_it++;
1633 }
1634 all_it++;
1635 } while (all_it != all_annotations.end());
1636 }
47747218
SA
1637}
1638
c0c3e62a
SA
1639void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1640{
1641 assert(pdata);
1642 assert(decode_signal);
1643
1644 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1645 assert(ds);
1646
1647 if (ds->decode_interrupt_)
1648 return;
1649
e77de61f
SA
1650 // Get the decoder and the binary data
1651 assert(pdata->pdo);
1652 assert(pdata->pdo->di);
6a26fc44
SA
1653 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1654 assert(srd_dec);
e77de61f 1655
c0c3e62a
SA
1656 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1657 assert(pdb);
1658
e77de61f 1659 // Find the matching DecodeBinaryClass
c0c3e62a
SA
1660 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1661
e77de61f
SA
1662 DecodeBinaryClass* bin_class = nullptr;
1663 for (DecodeBinaryClass& bc : segment->binary_classes)
6a26fc44
SA
1664 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1665 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
e77de61f 1666 bin_class = &bc;
c0c3e62a 1667
e77de61f
SA
1668 if (!bin_class) {
1669 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1670 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1671 ", segment only knows" << segment->binary_classes.size() << "classes";
1672 return;
1673 }
c0c3e62a 1674
e77de61f
SA
1675 // Add the data chunk
1676 bin_class->chunks.emplace_back();
1677 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1678
1679 chunk->sample = pdata->start_sample;
1680 chunk->data.resize(pdb->size);
1681 memcpy(chunk->data.data(), pdb->data, pdb->size);
1682
6a26fc44 1683 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
b2b18d3a
SA
1684
1685 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
c0c3e62a
SA
1686}
1687
47747218
SA
1688void DecodeSignal::on_capture_state_changed(int state)
1689{
1690 // If a new acquisition was started, we need to start decoding from scratch
ba5f2186
SA
1691 if (state == Session::Running) {
1692 logic_mux_data_invalid_ = true;
47747218 1693 begin_decode();
ba5f2186 1694 }
47747218
SA
1695}
1696
1b56c646
SA
1697void DecodeSignal::on_data_cleared()
1698{
1699 reset_decode();
1700}
1701
47747218
SA
1702void DecodeSignal::on_data_received()
1703{
5620539c
SA
1704 // If we detected a lack of input data when trying to start decoding,
1705 // we have set an error message. Only try again if we now have data
1706 // to work with
1707 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1708 return;
69e95096
SA
1709 else {
1710 error_message_.clear();
1711 // TODO Emulate noquote()
1712 qDebug().nospace() << name() << ": Error cleared";
1713 }
5620539c 1714
1b56c646
SA
1715 if (!logic_mux_thread_.joinable())
1716 begin_decode();
1717 else
1718 logic_mux_cond_.notify_one();
47747218
SA
1719}
1720
db51130d
SA
1721void DecodeSignal::on_input_segment_completed()
1722{
1723 if (!logic_mux_thread_.joinable())
1724 logic_mux_cond_.notify_one();
1725}
1726
02078aa1
SA
1727void DecodeSignal::on_annotation_visibility_changed()
1728{
1729 annotation_visibility_changed();
1730}
1731
ad908057
SA
1732} // namespace data
1733} // namespace pv