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