]> sigrok.org Git - pulseview.git/blame - pv/data/decodesignal.cpp
SignalBase: Speed up conversion and prevent leaving samples unconverted
[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
0c5fe73e
SA
20#include <limits>
21
47747218
SA
22#include <QDebug>
23
ad908057
SA
24#include "logic.hpp"
25#include "logicsegment.hpp"
26#include "decodesignal.hpp"
27#include "signaldata.hpp"
28
29#include <pv/binding/decoder.hpp>
30#include <pv/data/decode/decoder.hpp>
ecd07c20 31#include <pv/data/decode/row.hpp>
d3feec23 32#include <pv/globalsettings.hpp>
ad908057
SA
33#include <pv/session.hpp>
34
47747218
SA
35using std::lock_guard;
36using std::make_pair;
ad908057 37using std::make_shared;
0c5fe73e 38using std::min;
5ecf957f 39using std::out_of_range;
ad908057 40using std::shared_ptr;
47747218
SA
41using std::unique_lock;
42using pv::data::decode::Annotation;
ad908057 43using pv::data::decode::Decoder;
ecd07c20 44using pv::data::decode::Row;
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),
8a603e13 59 current_segment_id_(0)
ad908057 60{
47747218
SA
61 connect(&session_, SIGNAL(capture_state_changed(int)),
62 this, SLOT(on_capture_state_changed(int)));
ad908057
SA
63}
64
47747218 65DecodeSignal::~DecodeSignal()
ad908057 66{
1b56c646 67 reset_decode();
ad908057
SA
68}
69
47747218 70const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
ecd07c20 71{
47747218 72 return stack_;
ecd07c20
SA
73}
74
c8e60bdf 75void DecodeSignal::stack_decoder(const srd_decoder *decoder)
ad908057
SA
76{
77 assert(decoder);
762ab7a4
SA
78 const shared_ptr<Decoder> dec = make_shared<decode::Decoder>(decoder);
79
80 stack_.push_back(dec);
47747218
SA
81
82 // Set name if this decoder is the first in the list
83 if (stack_.size() == 1)
84 set_name(QString::fromUtf8(decoder->name));
132a5c6d 85
27a3f09b 86 // Include the newly created decode channels in the channel lists
9f97b357 87 update_channel_list();
132a5c6d 88
762ab7a4 89 auto_assign_signals(dec);
27a3f09b 90 commit_decoder_channels();
47747218 91 begin_decode();
ad908057
SA
92}
93
94void DecodeSignal::remove_decoder(int index)
95{
47747218
SA
96 assert(index >= 0);
97 assert(index < (int)stack_.size());
98
99 // Find the decoder in the stack
100 auto iter = stack_.begin();
101 for (int i = 0; i < index; i++, iter++)
102 assert(iter != stack_.end());
103
104 // Delete the element
105 stack_.erase(iter);
106
107 // Update channels and decoded data
9f97b357 108 update_channel_list();
47747218 109 begin_decode();
ad908057
SA
110}
111
112bool DecodeSignal::toggle_decoder_visibility(int index)
113{
47747218 114 auto iter = stack_.cbegin();
ad908057 115 for (int i = 0; i < index; i++, iter++)
47747218 116 assert(iter != stack_.end());
ad908057
SA
117
118 shared_ptr<Decoder> dec = *iter;
119
120 // Toggle decoder visibility
121 bool state = false;
122 if (dec) {
123 state = !dec->shown();
124 dec->show(state);
125 }
126
127 return state;
128}
129
47747218
SA
130void DecodeSignal::reset_decode()
131{
1b56c646
SA
132 if (decode_thread_.joinable()) {
133 decode_interrupt_ = true;
134 decode_input_cond_.notify_one();
135 decode_thread_.join();
136 }
137
138 if (logic_mux_thread_.joinable()) {
139 logic_mux_interrupt_ = true;
140 logic_mux_cond_.notify_one();
141 logic_mux_thread_.join();
142 }
143
e91883bb
SA
144 stop_srd_session();
145
47747218 146 class_rows_.clear();
8a603e13 147 current_segment_id_ = 0;
72435789 148 segments_.clear();
1b56c646
SA
149
150 logic_mux_data_.reset();
151 logic_mux_data_invalid_ = true;
eee3eab9 152
72435789
SA
153 error_message_ = QString();
154
eee3eab9 155 decode_reset();
47747218
SA
156}
157
946b52e1
SA
158void DecodeSignal::begin_decode()
159{
47747218
SA
160 if (decode_thread_.joinable()) {
161 decode_interrupt_ = true;
162 decode_input_cond_.notify_one();
163 decode_thread_.join();
164 }
165
166 if (logic_mux_thread_.joinable()) {
167 logic_mux_interrupt_ = true;
168 logic_mux_cond_.notify_one();
169 logic_mux_thread_.join();
170 }
171
172 reset_decode();
173
27a3f09b
SA
174 if (stack_.size() == 0) {
175 error_message_ = tr("No decoders");
176 return;
177 }
178
179 assert(channels_.size() > 0);
180
181 if (get_assigned_signal_count() == 0) {
182 error_message_ = tr("There are no channels assigned to this decoder");
183 return;
184 }
185
04627946
SA
186 // Make sure that all assigned channels still provide logic data
187 // (can happen when a converted signal was assigned but the
188 // conversion removed in the meanwhile)
189 for (data::DecodeChannel &ch : channels_)
190 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
191 ch.assigned_signal = nullptr;
192
47747218
SA
193 // Check that all decoders have the required channels
194 for (const shared_ptr<decode::Decoder> &dec : stack_)
195 if (!dec->have_required_channels()) {
196 error_message_ = tr("One or more required channels "
197 "have not been specified");
198 return;
199 }
200
4913560f 201 // Map out all the annotation classes
47747218
SA
202 for (const shared_ptr<decode::Decoder> &dec : stack_) {
203 assert(dec);
204 const srd_decoder *const decc = dec->decoder();
205 assert(dec->decoder());
206
47747218
SA
207 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
208 const srd_decoder_annotation_row *const ann_row =
209 (srd_decoder_annotation_row *)l->data;
210 assert(ann_row);
211
212 const Row row(decc, ann_row);
213
47747218
SA
214 for (const GSList *ll = ann_row->ann_classes;
215 ll; ll = ll->next)
216 class_rows_[make_pair(decc,
217 GPOINTER_TO_INT(ll->data))] = row;
218 }
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) {
ed535cd7
SA
235 error_message_ = tr("No input data");
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
ecd07c20
SA
248QString DecodeSignal::error_message() const
249{
47747218
SA
250 lock_guard<mutex> lock(output_mutex_);
251 return error_message_;
ecd07c20
SA
252}
253
47747218 254const vector<data::DecodeChannel> DecodeSignal::get_channels() const
9f97b357
SA
255{
256 return channels_;
257}
258
762ab7a4 259void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
132a5c6d 260{
47747218
SA
261 bool new_assignment = false;
262
132a5c6d
SA
263 // Try to auto-select channels that don't have signals assigned yet
264 for (data::DecodeChannel &ch : channels_) {
762ab7a4
SA
265 // If a decoder is given, auto-assign only its channels
266 if (dec && (ch.decoder_ != dec))
267 continue;
268
132a5c6d
SA
269 if (ch.assigned_signal)
270 continue;
271
692f6093
SA
272 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
273 const QString ch_name = ch.name.toLower();
274 const QString s_name = s->name().toLower();
275
276 if (s->logic_data() &&
277 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
132a5c6d 278 ch.assigned_signal = s.get();
47747218
SA
279 new_assignment = true;
280 }
692f6093 281 }
47747218
SA
282 }
283
284 if (new_assignment) {
285 logic_mux_data_invalid_ = true;
27a3f09b 286 commit_decoder_channels();
47747218 287 channels_updated();
132a5c6d
SA
288 }
289}
290
9f97b357
SA
291void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
292{
293 for (data::DecodeChannel &ch : channels_)
47747218 294 if (ch.id == channel_id) {
9f97b357 295 ch.assigned_signal = signal;
47747218
SA
296 logic_mux_data_invalid_ = true;
297 }
9f97b357 298
27a3f09b 299 commit_decoder_channels();
9f97b357 300 channels_updated();
47747218 301 begin_decode();
9f97b357
SA
302}
303
27a3f09b
SA
304int DecodeSignal::get_assigned_signal_count() const
305{
306 // Count all channels that have a signal assigned to them
307 return count_if(channels_.begin(), channels_.end(),
308 [](data::DecodeChannel ch) { return ch.assigned_signal; });
309}
310
9f97b357
SA
311void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
312{
313 for (data::DecodeChannel &ch : channels_)
314 if (ch.id == channel_id)
315 ch.initial_pin_state = init_state;
316
317 channels_updated();
318
47747218 319 begin_decode();
9f97b357
SA
320}
321
ff83d980
SA
322double DecodeSignal::samplerate() const
323{
72435789
SA
324 double result = 0;
325
326 // TODO For now, we simply return the first samplerate that we have
8a603e13
SA
327 if (segments_.size() > 0)
328 result = segments_.front().samplerate;
72435789
SA
329
330 return result;
ff83d980
SA
331}
332
72435789 333const pv::util::Timestamp DecodeSignal::start_time() const
ff83d980 334{
72435789
SA
335 pv::util::Timestamp result;
336
337 // TODO For now, we simply return the first start time that we have
8a603e13
SA
338 if (segments_.size() > 0)
339 result = segments_.front().start_time;
72435789
SA
340
341 return result;
ff83d980
SA
342}
343
5ecf957f 344int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
0c5fe73e
SA
345{
346 // The working sample count is the highest sample number for
ed535cd7
SA
347 // which all used signals have data available, so go through all
348 // channels and use the lowest overall sample count of the segment
0c5fe73e 349
0c5fe73e
SA
350 int64_t count = std::numeric_limits<int64_t>::max();
351 bool no_signals_assigned = true;
352
353 for (const data::DecodeChannel &ch : channels_)
354 if (ch.assigned_signal) {
355 no_signals_assigned = false;
356
357 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
358 if (!logic_data || logic_data->logic_segments().empty())
359 return 0;
360
5ecf957f
SA
361 try {
362 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
363 count = min(count, (int64_t)segment->get_sample_count());
364 } catch (out_of_range) {
365 return 0;
366 }
0c5fe73e
SA
367 }
368
369 return (no_signals_assigned ? 0 : count);
370}
371
5ecf957f 372int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id) const
ff83d980 373{
47747218 374 lock_guard<mutex> decode_lock(output_mutex_);
5ecf957f
SA
375
376 int64_t result = 0;
377
72435789
SA
378 try {
379 const DecodeSegment *segment = &(segments_.at(segment_id));
380 result = segment->samples_decoded;
381 } catch (out_of_range) {
382 // Do nothing
383 }
5ecf957f
SA
384
385 return result;
ff83d980
SA
386}
387
ecd07c20
SA
388vector<Row> DecodeSignal::visible_rows() const
389{
47747218
SA
390 lock_guard<mutex> lock(output_mutex_);
391
392 vector<Row> rows;
393
394 for (const shared_ptr<decode::Decoder> &dec : stack_) {
395 assert(dec);
396 if (!dec->shown())
397 continue;
398
399 const srd_decoder *const decc = dec->decoder();
400 assert(dec->decoder());
401
402 // Add a row for the decoder if it doesn't have a row list
403 if (!decc->annotation_rows)
404 rows.emplace_back(decc);
405
406 // Add the decoder rows
407 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
408 const srd_decoder_annotation_row *const ann_row =
409 (srd_decoder_annotation_row *)l->data;
410 assert(ann_row);
411 rows.emplace_back(decc, ann_row);
412 }
413 }
414
415 return rows;
ecd07c20
SA
416}
417
418void DecodeSignal::get_annotation_subset(
419 vector<pv::data::decode::Annotation> &dest,
72435789 420 const decode::Row &row, uint32_t segment_id, uint64_t start_sample,
ecd07c20
SA
421 uint64_t end_sample) const
422{
47747218
SA
423 lock_guard<mutex> lock(output_mutex_);
424
72435789
SA
425 try {
426 const DecodeSegment *segment = &(segments_.at(segment_id));
427 const map<const decode::Row, decode::RowData> *rows =
428 &(segment->annotation_rows);
429
430 const auto iter = rows->find(row);
431 if (iter != rows->end())
432 (*iter).second.get_annotation_subset(dest,
433 start_sample, end_sample);
434 } catch (out_of_range) {
435 // Do nothing
436 }
47747218
SA
437}
438
439void DecodeSignal::save_settings(QSettings &settings) const
440{
441 SignalBase::save_settings(settings);
442
c8e60bdf
SA
443 settings.setValue("decoders", (int)(stack_.size()));
444
8b5ea5a1 445 // Save decoder stack
c8e60bdf
SA
446 int decoder_idx = 0;
447 for (shared_ptr<decode::Decoder> decoder : stack_) {
448 settings.beginGroup("decoder" + QString::number(decoder_idx++));
449
450 settings.setValue("id", decoder->decoder()->id);
451
d3feec23
SA
452 // Save decoder options
453 const map<string, GVariant*>& options = decoder->options();
454
455 settings.setValue("options", (int)options.size());
456
457 // Note: decode::Decoder::options() returns only the options
458 // that differ from the default. See binding::Decoder::getter()
459 int i = 0;
460 for (auto option : options) {
461 settings.beginGroup("option" + QString::number(i));
462 settings.setValue("name", QString::fromStdString(option.first));
463 GlobalSettings::store_gvariant(settings, option.second);
464 settings.endGroup();
465 i++;
466 }
467
c8e60bdf
SA
468 settings.endGroup();
469 }
470
8b5ea5a1
SA
471 // Save channel mapping
472 settings.setValue("channels", (int)channels_.size());
473
474 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
475 auto channel = find_if(channels_.begin(), channels_.end(),
476 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
477
478 if (channel == channels_.end()) {
479 qDebug() << "ERROR: Gap in channel index:" << channel_id;
480 continue;
481 }
482
483 settings.beginGroup("channel" + QString::number(channel_id));
484
485 settings.setValue("name", channel->name); // Useful for debugging
486 settings.setValue("initial_pin_state", channel->initial_pin_state);
487
488 if (channel->assigned_signal)
489 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
490
491 settings.endGroup();
492 }
47747218
SA
493}
494
495void DecodeSignal::restore_settings(QSettings &settings)
496{
497 SignalBase::restore_settings(settings);
498
8b5ea5a1 499 // Restore decoder stack
c8e60bdf
SA
500 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
501
502 int decoders = settings.value("decoders").toInt();
503
504 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
505 settings.beginGroup("decoder" + QString::number(decoder_idx));
506
507 QString id = settings.value("id").toString();
508
509 for (GSList *entry = dec_list; entry; entry = entry->next) {
510 const srd_decoder *dec = (srd_decoder*)entry->data;
511 if (!dec)
512 continue;
513
514 if (QString::fromUtf8(dec->id) == id) {
d3feec23
SA
515 shared_ptr<decode::Decoder> decoder =
516 make_shared<decode::Decoder>(dec);
517
518 stack_.push_back(decoder);
519
520 // Restore decoder options that differ from their default
521 int options = settings.value("options").toInt();
522
523 for (int i = 0; i < options; i++) {
524 settings.beginGroup("option" + QString::number(i));
525 QString name = settings.value("name").toString();
526 GVariant *value = GlobalSettings::restore_gvariant(settings);
527 decoder->set_option(name.toUtf8(), value);
528 settings.endGroup();
529 }
c8e60bdf
SA
530
531 // Include the newly created decode channels in the channel lists
532 update_channel_list();
533 break;
534 }
535 }
536
537 settings.endGroup();
4ca06ec3 538 channels_updated();
c8e60bdf
SA
539 }
540
8b5ea5a1
SA
541 // Restore channel mapping
542 unsigned int channels = settings.value("channels").toInt();
543
544 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
545 session_.signalbases();
546
547 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
548 auto channel = find_if(channels_.begin(), channels_.end(),
549 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
550
551 if (channel == channels_.end()) {
552 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
553 continue;
554 }
555
556 settings.beginGroup("channel" + QString::number(channel_id));
557
558 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
559
560 for (shared_ptr<data::SignalBase> signal : signalbases)
561 if (signal->name() == assigned_signal_name)
562 channel->assigned_signal = signal.get();
563
564 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
565
566 settings.endGroup();
567 }
568
aa71890d
SA
569 // Update the internal structures
570 update_channel_list();
571 commit_decoder_channels();
572
8b5ea5a1 573 begin_decode();
47747218
SA
574}
575
8a603e13
SA
576uint32_t DecodeSignal::get_input_segment_count() const
577{
578 uint64_t count = std::numeric_limits<uint64_t>::max();
579 bool no_signals_assigned = true;
580
581 for (const data::DecodeChannel &ch : channels_)
582 if (ch.assigned_signal) {
583 no_signals_assigned = false;
584
585 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
586 if (!logic_data || logic_data->logic_segments().empty())
587 return 0;
588
589 // Find the min value of all segment counts
590 if ((uint64_t)(logic_data->logic_segments().size()) < count)
591 count = logic_data->logic_segments().size();
592 }
593
594 return (no_signals_assigned ? 0 : count);
595}
596
597uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
598{
599 double samplerate = 0;
600
601 for (const data::DecodeChannel &ch : channels_)
602 if (ch.assigned_signal) {
603 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
604 if (!logic_data || logic_data->logic_segments().empty())
605 continue;
606
607 try {
608 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
609 samplerate = segment->samplerate();
610 } catch (out_of_range) {
611 // Do nothing
612 }
613 break;
614 }
615
616 return samplerate;
617}
618
9f97b357
SA
619void DecodeSignal::update_channel_list()
620{
47747218 621 vector<data::DecodeChannel> prev_channels = channels_;
9f97b357
SA
622 channels_.clear();
623
624 uint16_t id = 0;
625
626 // Copy existing entries, create new as needed
47747218 627 for (shared_ptr<Decoder> decoder : stack_) {
9f97b357
SA
628 const srd_decoder* srd_d = decoder->decoder();
629 const GSList *l;
630
631 // Mandatory channels
632 for (l = srd_d->channels; l; l = l->next) {
633 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
634 bool ch_added = false;
635
636 // Copy but update ID if this channel was in the list before
47747218 637 for (data::DecodeChannel &ch : prev_channels)
9f97b357
SA
638 if (ch.pdch_ == pdch) {
639 ch.id = id++;
640 channels_.push_back(ch);
641 ch_added = true;
642 break;
643 }
644
645 if (!ch_added) {
646 // Create new entry without a mapped signal
6e7a4a00 647 data::DecodeChannel ch = {id++, 0, false, nullptr,
9f97b357
SA
648 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
649 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
650 channels_.push_back(ch);
651 }
652 }
653
654 // Optional channels
655 for (l = srd_d->opt_channels; l; l = l->next) {
656 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
657 bool ch_added = false;
658
659 // Copy but update ID if this channel was in the list before
47747218 660 for (data::DecodeChannel &ch : prev_channels)
9f97b357
SA
661 if (ch.pdch_ == pdch) {
662 ch.id = id++;
663 channels_.push_back(ch);
664 ch_added = true;
665 break;
666 }
667
668 if (!ch_added) {
669 // Create new entry without a mapped signal
6e7a4a00 670 data::DecodeChannel ch = {id++, 0, true, nullptr,
9f97b357
SA
671 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
672 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
673 channels_.push_back(ch);
674 }
675 }
676 }
677
47747218
SA
678 // Invalidate the logic output data if the channel assignment changed
679 if (prev_channels.size() != channels_.size()) {
680 // The number of channels changed, there's definitely a difference
681 logic_mux_data_invalid_ = true;
682 } else {
683 // Same number but assignment may still differ, so compare all channels
684 for (size_t i = 0; i < channels_.size(); i++) {
685 const data::DecodeChannel &p_ch = prev_channels[i];
686 const data::DecodeChannel &ch = channels_[i];
687
688 if ((p_ch.pdch_ != ch.pdch_) ||
689 (p_ch.assigned_signal != ch.assigned_signal)) {
690 logic_mux_data_invalid_ = true;
691 break;
692 }
693 }
694
695 }
696
9f97b357
SA
697 channels_updated();
698}
699
27a3f09b 700void DecodeSignal::commit_decoder_channels()
ad908057 701{
27a3f09b
SA
702 // Submit channel list to every decoder, containing only the relevant channels
703 for (shared_ptr<decode::Decoder> dec : stack_) {
704 vector<data::DecodeChannel*> channel_list;
705
706 for (data::DecodeChannel &ch : channels_)
707 if (ch.decoder_ == dec)
708 channel_list.push_back(&ch);
47747218 709
27a3f09b
SA
710 dec->set_channels(channel_list);
711 }
aa71890d
SA
712
713 // Channel bit IDs must be in sync with the channel's apperance in channels_
714 int id = 0;
715 for (data::DecodeChannel &ch : channels_)
716 if (ch.assigned_signal)
717 ch.bit_id = id++;
47747218
SA
718}
719
ed535cd7 720void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
47747218 721{
27a3f09b
SA
722 // Enforce end to be greater than start
723 if (end <= start)
724 return;
725
ed535cd7 726 // Fetch the channel segments and their data
27a3f09b
SA
727 vector<shared_ptr<LogicSegment> > segments;
728 vector<const uint8_t*> signal_data;
729 vector<uint8_t> signal_in_bytepos;
730 vector<uint8_t> signal_in_bitpos;
731
732 for (data::DecodeChannel &ch : channels_)
733 if (ch.assigned_signal) {
734 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
ed535cd7
SA
735
736 shared_ptr<LogicSegment> segment;
737 try {
738 segment = logic_data->logic_segments().at(segment_id);
739 } catch (out_of_range) {
740 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
741 << "has no logic segment" << segment_id;
742 return;
743 }
27a3f09b 744 segments.push_back(segment);
b82243f7
SA
745
746 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
747 segment->get_samples(start, end, data);
748 signal_data.push_back(data);
27a3f09b
SA
749
750 const int bitpos = ch.assigned_signal->logic_bit_index();
751 signal_in_bytepos.push_back(bitpos / 8);
752 signal_in_bitpos.push_back(bitpos % 8);
753 }
754
ed535cd7
SA
755
756 shared_ptr<LogicSegment> output_segment;
757 try {
758 output_segment = logic_mux_data_->logic_segments().at(segment_id);
759 } catch (out_of_range) {
760 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
761 << segment_id << "in mux_logic_samples(), mux segments size is" \
762 << logic_mux_data_->logic_segments().size();
763 return;
764 }
765
27a3f09b 766 // Perform the muxing of signal data into the output data
8a603e13 767 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
27a3f09b
SA
768 unsigned int signal_count = signal_data.size();
769
770 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
771 int bitpos = 0;
772 uint8_t bytepos = 0;
773
8a603e13
SA
774 const int out_sample_pos = sample_cnt * output_segment->unit_size();
775 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
27a3f09b 776 output[out_sample_pos + i] = 0;
47747218 777
27a3f09b
SA
778 for (unsigned int i = 0; i < signal_count; i++) {
779 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
780 const uint8_t in_sample = 1 &
781 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
47747218 782
27a3f09b
SA
783 const uint8_t out_sample = output[out_sample_pos + bytepos];
784
785 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
786
787 bitpos++;
788 if (bitpos > 7) {
789 bitpos = 0;
790 bytepos++;
791 }
792 }
47747218
SA
793 }
794
8a603e13 795 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
27a3f09b
SA
796 delete[] output;
797
798 for (const uint8_t* data : signal_data)
799 delete[] data;
800}
801
802void DecodeSignal::logic_mux_proc()
803{
ed535cd7
SA
804 uint32_t segment_id = 0;
805
8a603e13
SA
806 assert(logic_mux_data_);
807
65efd025
SA
808 // Create initial logic mux segment
809 shared_ptr<LogicSegment> output_segment =
85a70280
SA
810 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
811 logic_mux_unit_size_, 0);
65efd025 812 logic_mux_data_->push_segment(output_segment);
8a603e13
SA
813
814 output_segment->set_samplerate(get_input_samplerate(0));
ed535cd7 815
27a3f09b 816 do {
ed535cd7 817 const uint64_t input_sample_count = get_working_sample_count(segment_id);
8a603e13 818 const uint64_t output_sample_count = output_segment->get_sample_count();
27a3f09b
SA
819
820 const uint64_t samples_to_process =
821 (input_sample_count > output_sample_count) ?
822 (input_sample_count - output_sample_count) : 0;
823
824 // Process the samples if necessary...
825 if (samples_to_process > 0) {
8a603e13 826 const uint64_t unit_size = output_segment->unit_size();
27a3f09b
SA
827 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
828
829 uint64_t processed_samples = 0;
830 do {
831 const uint64_t start_sample = output_sample_count + processed_samples;
832 const uint64_t sample_count =
833 min(samples_to_process - processed_samples, chunk_sample_count);
834
ed535cd7 835 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
27a3f09b
SA
836 processed_samples += sample_count;
837
838 // ...and process the newly muxed logic data
839 decode_input_cond_.notify_one();
840 } while (processed_samples < samples_to_process);
841 }
842
1ec191ed 843 if (samples_to_process == 0) {
ed535cd7
SA
844 // TODO Optimize this by caching the input segment count and only
845 // querying it when the cached value was reached
846 if (segment_id < get_input_segment_count() - 1) {
847 // Process next segment
848 segment_id++;
849
65efd025 850 output_segment =
85a70280
SA
851 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
852 logic_mux_unit_size_, 0);
65efd025 853 logic_mux_data_->push_segment(output_segment);
ba5f2186 854
8a603e13
SA
855 output_segment->set_samplerate(get_input_samplerate(segment_id));
856
ed535cd7
SA
857 } else {
858 // All segments have been processed
859 logic_mux_data_invalid_ = false;
860
861 // Wait for more input
862 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
863 logic_mux_cond_.wait(logic_mux_lock);
864 }
27a3f09b 865 }
1ec191ed 866 } while (!logic_mux_interrupt_);
47747218
SA
867}
868
869void DecodeSignal::decode_data(
8a603e13
SA
870 const int64_t abs_start_samplenum, const int64_t sample_count,
871 const shared_ptr<LogicSegment> input_segment)
47747218 872{
8a603e13 873 const int64_t unit_size = input_segment->unit_size();
27a3f09b 874 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
47747218
SA
875
876 for (int64_t i = abs_start_samplenum;
877 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
878 i += chunk_sample_count) {
879
880 const int64_t chunk_end = min(i + chunk_sample_count,
881 abs_start_samplenum + sample_count);
882
b82243f7
SA
883 int64_t data_size = (chunk_end - i) * unit_size;
884 uint8_t* chunk = new uint8_t[data_size];
8a603e13 885 input_segment->get_samples(i, chunk_end, chunk);
47747218 886
e91883bb 887 if (srd_session_send(srd_session_, i, chunk_end, chunk,
b82243f7 888 data_size, unit_size) != SRD_OK) {
47747218
SA
889 error_message_ = tr("Decoder reported an error");
890 delete[] chunk;
891 break;
892 }
a3ebd556 893
47747218
SA
894 delete[] chunk;
895
896 {
897 lock_guard<mutex> lock(output_mutex_);
8a603e13 898 segments_.at(current_segment_id_).samples_decoded = chunk_end;
47747218 899 }
1b56c646
SA
900
901 // Notify the frontend that we processed some data and
902 // possibly have new annotations as well
903 new_annotations();
47747218
SA
904 }
905}
906
907void DecodeSignal::decode_proc()
908{
65efd025
SA
909 current_segment_id_ = 0;
910
911 // If there is no input data available yet, wait until it is or we're interrupted
912 if (logic_mux_data_->logic_segments().size() == 0) {
913 unique_lock<mutex> input_wait_lock(input_mutex_);
914 decode_input_cond_.wait(input_wait_lock);
915 }
a3ebd556
SA
916
917 if (decode_interrupt_)
918 return;
919
8a603e13 920 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
8a603e13 921 assert(input_segment);
65efd025
SA
922
923 // Create the initial segment and set its sample rate so that we can pass it to SRD
924 create_decode_segment();
8a603e13 925 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 926 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 927
65efd025
SA
928 start_srd_session();
929
930 uint64_t sample_count = 0;
27a3f09b 931 uint64_t abs_start_samplenum = 0;
47747218 932 do {
27a3f09b
SA
933 // Keep processing new samples until we exhaust the input data
934 do {
767bf4e7 935 lock_guard<mutex> input_lock(input_mutex_);
8a603e13 936 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
27a3f09b
SA
937
938 if (sample_count > 0) {
8a603e13 939 decode_data(abs_start_samplenum, sample_count, input_segment);
27a3f09b
SA
940 abs_start_samplenum += sample_count;
941 }
1b56c646
SA
942 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
943
8a603e13
SA
944 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
945 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
946 // Process next segment
947 current_segment_id_++;
948
949 try {
950 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
951 } catch (out_of_range) {
952 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
953 << current_segment_id_ << "in decode_proc(), mux segments size is" \
954 << logic_mux_data_->logic_segments().size();
955 return;
956 }
957 abs_start_samplenum = 0;
958
65efd025
SA
959 // Create the next segment and set its metadata
960 create_decode_segment();
8a603e13 961 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 962 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13
SA
963
964 // Reset decoder state
965 stop_srd_session();
966 start_srd_session();
967 } else {
968 // All segments have been processed
1b56c646 969 decode_finished();
27a3f09b 970
8a603e13
SA
971 // Wait for new input data or an interrupt was requested
972 unique_lock<mutex> input_wait_lock(input_mutex_);
973 decode_input_cond_.wait(input_wait_lock);
974 }
27a3f09b
SA
975 }
976 } while (error_message_.isEmpty() && !decode_interrupt_);
e91883bb
SA
977}
978
979void DecodeSignal::start_srd_session()
980{
4349dc21
GS
981 uint64_t samplerate;
982
a3ebd556
SA
983 if (srd_session_)
984 stop_srd_session();
e91883bb 985
a3ebd556
SA
986 // Create the session
987 srd_session_new(&srd_session_);
988 assert(srd_session_);
47747218 989
a3ebd556
SA
990 // Create the decoders
991 srd_decoder_inst *prev_di = nullptr;
992 for (const shared_ptr<decode::Decoder> &dec : stack_) {
993 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
e91883bb 994
a3ebd556
SA
995 if (!di) {
996 error_message_ = tr("Failed to create decoder instance");
997 srd_session_destroy(srd_session_);
c5f9553c 998 srd_session_ = nullptr;
a3ebd556
SA
999 return;
1000 }
e91883bb 1001
a3ebd556
SA
1002 if (prev_di)
1003 srd_inst_stack(srd_session_, prev_di, di);
e91883bb 1004
a3ebd556 1005 prev_di = di;
e91883bb 1006 }
a3ebd556
SA
1007
1008 // Start the session
4349dc21
GS
1009 samplerate = segments_.at(current_segment_id_).samplerate;
1010 if (samplerate)
1011 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1012 g_variant_new_uint64(samplerate));
a3ebd556
SA
1013
1014 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1015 DecodeSignal::annotation_callback, this);
1016
1017 srd_session_start(srd_session_);
e91883bb 1018}
47747218 1019
e91883bb
SA
1020void DecodeSignal::stop_srd_session()
1021{
1022 if (srd_session_) {
1023 // Destroy the session
1024 srd_session_destroy(srd_session_);
1025 srd_session_ = nullptr;
1026 }
47747218
SA
1027}
1028
a8a9222d
SA
1029void DecodeSignal::connect_input_notifiers()
1030{
1031 // Disconnect the notification slot from the previous set of signals
1b56c646 1032 disconnect(this, SLOT(on_data_cleared()));
a8a9222d
SA
1033 disconnect(this, SLOT(on_data_received()));
1034
1035 // Connect the currently used signals to our slot
1036 for (data::DecodeChannel &ch : channels_) {
1037 if (!ch.assigned_signal)
1038 continue;
1039
1b56c646
SA
1040 const data::SignalBase *signal = ch.assigned_signal;
1041 connect(signal, SIGNAL(samples_cleared()),
1042 this, SLOT(on_data_cleared()));
b10b58f4 1043 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
a8a9222d
SA
1044 this, SLOT(on_data_received()));
1045 }
1046}
1047
65efd025 1048void DecodeSignal::create_decode_segment()
4913560f 1049{
65efd025
SA
1050 // Create annotation segment
1051 segments_.emplace_back(DecodeSegment());
72435789 1052
65efd025
SA
1053 // Add annotation classes
1054 for (const shared_ptr<decode::Decoder> &dec : stack_) {
1055 assert(dec);
1056 const srd_decoder *const decc = dec->decoder();
1057 assert(dec->decoder());
4913560f 1058
65efd025
SA
1059 // Add a row for the decoder if it doesn't have a row list
1060 if (!decc->annotation_rows)
1061 (segments_.back().annotation_rows)[Row(decc)] =
1062 decode::RowData();
4913560f 1063
65efd025
SA
1064 // Add the decoder rows
1065 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
1066 const srd_decoder_annotation_row *const ann_row =
1067 (srd_decoder_annotation_row *)l->data;
1068 assert(ann_row);
4913560f 1069
65efd025 1070 const Row row(decc, ann_row);
4913560f 1071
65efd025
SA
1072 // Add a new empty row data object
1073 (segments_.back().annotation_rows)[row] =
1074 decode::RowData();
4913560f
SA
1075 }
1076 }
1077}
1078
47747218
SA
1079void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1080{
1081 assert(pdata);
b21501d6 1082 assert(decode_signal);
47747218
SA
1083
1084 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1085 assert(ds);
1086
1087 lock_guard<mutex> lock(ds->output_mutex_);
1088
47747218
SA
1089 // Find the row
1090 assert(pdata->pdo);
1091 assert(pdata->pdo->di);
1092 const srd_decoder *const decc = pdata->pdo->di->decoder;
1093 assert(decc);
1094
1becee23
UH
1095 const srd_proto_data_annotation *const pda =
1096 (const srd_proto_data_annotation*)pdata->data;
1097 assert(pda);
1098
8a603e13 1099 auto row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.end();
47747218
SA
1100
1101 // Try looking up the sub-row of this class
1becee23
UH
1102 const auto format = pda->ann_class;
1103 const auto r = ds->class_rows_.find(make_pair(decc, format));
47747218 1104 if (r != ds->class_rows_.end())
8a603e13 1105 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find((*r).second);
47747218
SA
1106 else {
1107 // Failing that, use the decoder as a key
8a603e13 1108 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find(Row(decc));
47747218
SA
1109 }
1110
8a603e13 1111 if (row_iter == ds->segments_.at(ds->current_segment_id_).annotation_rows.end()) {
47747218 1112 qDebug() << "Unexpected annotation: decoder = " << decc <<
1becee23 1113 ", format = " << format;
47747218
SA
1114 assert(false);
1115 return;
1116 }
1117
1118 // Add the annotation
1becee23 1119 (*row_iter).second.emplace_annotation(pdata);
47747218
SA
1120}
1121
1122void DecodeSignal::on_capture_state_changed(int state)
1123{
1124 // If a new acquisition was started, we need to start decoding from scratch
ba5f2186
SA
1125 if (state == Session::Running) {
1126 logic_mux_data_invalid_ = true;
47747218 1127 begin_decode();
ba5f2186 1128 }
47747218
SA
1129}
1130
1b56c646
SA
1131void DecodeSignal::on_data_cleared()
1132{
1133 reset_decode();
1134}
1135
47747218
SA
1136void DecodeSignal::on_data_received()
1137{
1b56c646
SA
1138 if (!logic_mux_thread_.joinable())
1139 begin_decode();
1140 else
1141 logic_mux_cond_.notify_one();
47747218
SA
1142}
1143
ad908057
SA
1144} // namespace data
1145} // namespace pv