]> sigrok.org Git - pulseview.git/blob - pv/storesession.cpp
LogicSegment: Make constructor and append_payload() more generic
[pulseview.git] / pv / storesession.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2014 Joel Holdsworth <joel@airwebreathe.org.uk>
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
20 #include <cassert>
21
22 #ifdef _WIN32
23 // Windows: Avoid boost/thread namespace pollution (which includes windows.h).
24 #define NOGDI
25 #define NORESOURCE
26 #endif
27 #include <boost/thread/locks.hpp>
28 #include <boost/thread/shared_mutex.hpp>
29
30 #include "storesession.hpp"
31
32 #include <pv/devicemanager.hpp>
33 #include <pv/session.hpp>
34 #include <pv/data/analog.hpp>
35 #include <pv/data/analogsegment.hpp>
36 #include <pv/data/logic.hpp>
37 #include <pv/data/logicsegment.hpp>
38 #include <pv/data/signalbase.hpp>
39 #include <pv/devices/device.hpp>
40
41 #include <libsigrokcxx/libsigrokcxx.hpp>
42
43 using boost::shared_lock;
44 using boost::shared_mutex;
45
46 using std::deque;
47 using std::dynamic_pointer_cast;
48 using std::ios_base;
49 using std::lock_guard;
50 using std::make_pair;
51 using std::map;
52 using std::min;
53 using std::mutex;
54 using std::pair;
55 using std::set;
56 using std::shared_ptr;
57 using std::string;
58 using std::unordered_set;
59 using std::vector;
60
61 using Glib::VariantBase;
62
63 using sigrok::ConfigKey;
64 using sigrok::Error;
65 using sigrok::OutputFormat;
66 using sigrok::OutputFlag;
67
68 namespace pv {
69
70 const size_t StoreSession::BlockSize = 10 * 1024 * 1024;
71
72 StoreSession::StoreSession(const string &file_name,
73         const shared_ptr<OutputFormat> &output_format,
74         const map<string, VariantBase> &options,
75         const pair<uint64_t, uint64_t> sample_range,
76         const Session &session) :
77         file_name_(file_name),
78         output_format_(output_format),
79         options_(options),
80         sample_range_(sample_range),
81         session_(session),
82         interrupt_(false),
83         units_stored_(0),
84         unit_count_(0)
85 {
86 }
87
88 StoreSession::~StoreSession()
89 {
90         wait();
91 }
92
93 pair<int, int> StoreSession::progress() const
94 {
95         return make_pair(units_stored_.load(), unit_count_.load());
96 }
97
98 const QString& StoreSession::error() const
99 {
100         lock_guard<mutex> lock(mutex_);
101         return error_;
102 }
103
104 bool StoreSession::start()
105 {
106         const unordered_set< shared_ptr<data::SignalBase> > sigs(session_.signalbases());
107
108         shared_ptr<data::Segment> any_segment;
109         shared_ptr<data::LogicSegment> lsegment;
110         vector< shared_ptr<data::SignalBase> > achannel_list;
111         vector< shared_ptr<data::AnalogSegment> > asegment_list;
112
113         for (shared_ptr<data::SignalBase> signal : sigs) {
114                 if (!signal->enabled())
115                         continue;
116
117                 if (signal->type() == data::SignalBase::LogicChannel) {
118                         // All logic channels share the same data segments
119                         shared_ptr<data::Logic> ldata = signal->logic_data();
120
121                         const deque< shared_ptr<data::LogicSegment> > &lsegments =
122                                 ldata->logic_segments();
123
124                         if (lsegments.empty()) {
125                                 error_ = tr("Can't save logic channel without data.");
126                                 return false;
127                         }
128
129                         lsegment = lsegments.front();
130                         any_segment = lsegment;
131                 }
132
133                 if (signal->type() == data::SignalBase::AnalogChannel) {
134                         // Each analog channel has its own segments
135                         shared_ptr<data::Analog> adata = signal->analog_data();
136
137                         const deque< shared_ptr<data::AnalogSegment> > &asegments =
138                                 adata->analog_segments();
139
140                         if (asegments.empty()) {
141                                 error_ = tr("Can't save analog channel without data.");
142                                 return false;
143                         }
144
145                         asegment_list.push_back(asegments.front());
146                         any_segment = asegments.front();
147
148                         achannel_list.push_back(signal);
149                 }
150         }
151
152         if (!any_segment) {
153                 error_ = tr("No channels enabled.");
154                 return false;
155         }
156
157         // Check whether the user wants to export a certain sample range
158         uint64_t end_sample;
159
160         if (sample_range_.first == sample_range_.second) {
161                 start_sample_ = 0;
162                 sample_count_ = any_segment->get_sample_count();
163         } else {
164                 if (sample_range_.first > sample_range_.second) {
165                         start_sample_ = sample_range_.second;
166                         end_sample = min(sample_range_.first, any_segment->get_sample_count());
167                         sample_count_ = end_sample - start_sample_;
168                 } else {
169                         start_sample_ = sample_range_.first;
170                         end_sample = min(sample_range_.second, any_segment->get_sample_count());
171                         sample_count_ = end_sample - start_sample_;
172                 }
173         }
174
175         // Begin storing
176         try {
177                 const auto context = session_.device_manager().context();
178                 auto device = session_.device()->device();
179
180                 map<string, Glib::VariantBase> options = options_;
181
182                 if (!output_format_->test_flag(OutputFlag::INTERNAL_IO_HANDLING))
183                         output_stream_.open(file_name_, ios_base::binary |
184                                         ios_base::trunc | ios_base::out);
185
186                 output_ = output_format_->create_output(file_name_, device, options);
187                 auto meta = context->create_meta_packet(
188                         {{ConfigKey::SAMPLERATE, Glib::Variant<guint64>::create(
189                                 any_segment->samplerate())}});
190                 output_->receive(meta);
191         } catch (Error error) {
192                 error_ = tr("Error while saving: ") + error.what();
193                 return false;
194         }
195
196         thread_ = std::thread(&StoreSession::store_proc, this,
197                 achannel_list, asegment_list, lsegment);
198         return true;
199 }
200
201 void StoreSession::wait()
202 {
203         if (thread_.joinable())
204                 thread_.join();
205 }
206
207 void StoreSession::cancel()
208 {
209         interrupt_ = true;
210 }
211
212 void StoreSession::store_proc(vector< shared_ptr<data::SignalBase> > achannel_list,
213         vector< shared_ptr<data::AnalogSegment> > asegment_list,
214         shared_ptr<data::LogicSegment> lsegment)
215 {
216         unsigned progress_scale = 0;
217
218         int aunit_size = 0;
219         int lunit_size = 0;
220         unsigned int lsamples_per_block = INT_MAX;
221         unsigned int asamples_per_block = INT_MAX;
222
223         if (!asegment_list.empty()) {
224                 // We assume all analog channels use the sample unit size
225                 aunit_size = asegment_list.front()->unit_size();
226                 asamples_per_block = BlockSize / aunit_size;
227         }
228         if (lsegment) {
229                 lunit_size = lsegment->unit_size();
230                 lsamples_per_block = BlockSize / lunit_size;
231         }
232
233         // Qt needs the progress values to fit inside an int. If they would
234         // not, scale the current and max values down until they do.
235         while ((sample_count_ >> progress_scale) > INT_MAX)
236                 progress_scale ++;
237
238         unit_count_ = sample_count_ >> progress_scale;
239
240         const unsigned int samples_per_block =
241                 min(asamples_per_block, lsamples_per_block);
242
243         while (!interrupt_ && sample_count_) {
244                 progress_updated();
245
246                 const uint64_t packet_len =
247                         min((uint64_t)samples_per_block, sample_count_);
248
249                 try {
250                         const auto context = session_.device_manager().context();
251
252                         for (unsigned int i = 0; i < achannel_list.size(); i++) {
253                                 shared_ptr<sigrok::Channel> achannel = (achannel_list.at(i))->channel();
254                                 shared_ptr<data::AnalogSegment> asegment = asegment_list.at(i);
255
256                                 const float *adata =
257                                         asegment->get_samples(start_sample_, start_sample_ + packet_len);
258
259                                 auto analog = context->create_analog_packet(
260                                         vector<shared_ptr<sigrok::Channel> >{achannel},
261                                         (float *)adata, packet_len,
262                                         sigrok::Quantity::VOLTAGE, sigrok::Unit::VOLT,
263                                         vector<const sigrok::QuantityFlag *>());
264                                 const string adata_str = output_->receive(analog);
265
266                                 if (output_stream_.is_open())
267                                         output_stream_ << adata_str;
268
269                                 delete[] adata;
270                         }
271
272                         if (lsegment) {
273                                 const uint8_t* ldata =
274                                         lsegment->get_samples(start_sample_, start_sample_ + packet_len);
275
276                                 const size_t length = packet_len * lunit_size;
277                                 auto logic = context->create_logic_packet((void*)ldata, length, lunit_size);
278                                 const string ldata_str = output_->receive(logic);
279
280                                 if (output_stream_.is_open())
281                                         output_stream_ << ldata_str;
282
283                                 delete[] ldata;
284                         }
285                 } catch (Error error) {
286                         error_ = tr("Error while saving: ") + error.what();
287                         break;
288                 }
289
290                 sample_count_ -= packet_len;
291                 start_sample_ += packet_len;
292                 units_stored_ = unit_count_ - (sample_count_ >> progress_scale);
293         }
294
295         // Zeroing the progress variables indicates completion
296         units_stored_ = unit_count_ = 0;
297
298         store_successful();
299         progress_updated();
300
301         output_.reset();
302         output_stream_.close();
303 }
304
305 } // pv