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