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