1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
|
/*
* Copyright 2024 ailurux <ailuruxx@gmail.com>
*
* SPDX-License-Identifier: GPL-3.0-only
*/
#include "playlist.hpp"
#include <stdint.h>
#include <string>
#include "cppbor.h"
#include "cppbor_parse.h"
#include "esp_log.h"
#include "ff.h"
#include "audio/playlist.hpp"
#include "database/database.hpp"
namespace audio {
[[maybe_unused]] static constexpr char kTag[] = "playlist";
Playlist::Playlist(const std::string& playlistFilepath)
: filepath_(playlistFilepath),
mutex_(),
total_size_(0),
pos_(-1),
file_open_(false),
file_error_(false),
offset_cache_(&memory::kSpiRamResource),
sample_size_(50) {}
auto Playlist::open() -> bool {
std::unique_lock<std::mutex> lock(mutex_);
if (file_open_) {
return true;
}
FRESULT res =
f_open(&file_, filepath_.c_str(), FA_READ | FA_WRITE | FA_OPEN_ALWAYS);
if (res != FR_OK) {
ESP_LOGE(kTag, "failed to open file! res: %i", res);
return false;
}
file_open_ = true;
file_error_ = false;
if (!deserialiseCache()) {
// Count the playlist size and build our offset cache.
countItems();
// Advance to the first item.
skipToWithoutCache(0);
}
return !file_error_;
}
Playlist::~Playlist() {
if (file_open_) {
f_close(&file_);
}
}
auto Playlist::filepath() const -> std::string {
return filepath_;
}
auto Playlist::currentPosition() const -> size_t {
std::unique_lock<std::mutex> lock(mutex_);
return pos_ < 0 ? 0 : pos_;
}
auto Playlist::size() const -> size_t {
std::unique_lock<std::mutex> lock(mutex_);
return total_size_;
}
auto Playlist::value() const -> std::string {
std::unique_lock<std::mutex> lock(mutex_);
return current_value_;
}
auto Playlist::atEnd() const -> bool {
std::unique_lock<std::mutex> lock(mutex_);
return pos_ + 1 >= total_size_;
}
auto Playlist::next() -> void {
std::unique_lock<std::mutex> lock(mutex_);
if (pos_ + 1 < total_size_ && !file_error_) {
advanceBy(1);
}
}
auto Playlist::prev() -> void {
std::unique_lock<std::mutex> lock(mutex_);
if (!file_error_) {
// Naive approach to see how that goes for now
skipToLocked(pos_ - 1);
}
}
auto Playlist::skipTo(size_t position) -> void {
std::unique_lock<std::mutex> lock(mutex_);
skipToLocked(position);
}
// Serialise the cache to a file to avoid having to rescan
// the entire queue when resuming
auto Playlist::serialiseCache() -> bool {
std::unique_lock<std::mutex> lock(mutex_);
if (!file_open_) {
return false;
}
FIL file;
// Open the cache file
std::string cache_file = filepath_ + ".cache";
FRESULT res =
f_open(&file, cache_file.c_str(), FA_READ | FA_WRITE | FA_CREATE_ALWAYS);
if (res != FR_OK) {
ESP_LOGE(kTag, "failed to open cache file! res: %i", res);
return false;
}
cppbor::Array data;
// First item = file size of queue file (for checking this file matches)
data.add(f_size(&file_));
// Next item = number of tracks in this queue
data.add(total_size_);
// Next, write out every cached offset
for (uint64_t offset : offset_cache_) {
data.add(offset);
}
auto encoded = data.encode();
UINT bytes_written = 0;
f_write(&file, encoded.data(), encoded.size(), &bytes_written);
if (bytes_written != encoded.size()) {
return false;
}
f_close(&file);
return true;
}
auto Playlist::deserialiseCache() -> bool {
if (!file_open_) {
return false;
}
FIL file;
// Open the cache file
std::string cache_file = filepath_ + ".cache";
FRESULT res =
f_open(&file, cache_file.c_str(), FA_READ | FA_WRITE | FA_OPEN_EXISTING);
if (res != FR_OK) {
return false;
}
std::vector<uint8_t> encoded;
encoded.resize(f_size(&file));
UINT bytes_read;
f_read(&file, encoded.data(), encoded.size(), &bytes_read);
if (bytes_read != encoded.size()) {
return false;
}
auto [data, unused, err] = cppbor::parse(encoded);
if (!data || data->type() != cppbor::ARRAY) {
return false;
}
auto entries = data->asArray();
// Double check the expected file size matches.
if (entries->get(0)->asUint()->unsignedValue() != f_size(&file_)) {
return false;
}
total_size_ = entries->get(1)->asUint()->unsignedValue();
// In case we have existing entries
offset_cache_.clear();
// Read in the cache
for (size_t i = 2; i < entries->size(); i++) {
offset_cache_.push_back(entries->get(i)->asUint()->unsignedValue());
}
f_close(&file);
return true;
}
auto Playlist::close() -> void {
if (file_open_) {
f_close(&file_);
file_open_ = false;
file_error_ = false;
}
}
auto Playlist::skipToLocked(size_t position) -> void {
if (!file_open_ || file_error_) {
return;
}
// Check our cache and go to nearest entry
auto remainder = position % sample_size_;
auto quotient = (position - remainder) / sample_size_;
if (offset_cache_.size() <= quotient) {
skipToWithoutCache(position);
return;
}
// Go to byte offset
auto entry = offset_cache_.at(quotient);
auto res = f_lseek(&file_, entry);
if (res != FR_OK) {
ESP_LOGW(kTag, "error seeking %u", res);
file_error_ = true;
return;
}
// Count ahead entries.
advanceBy(remainder + 1);
}
auto Playlist::skipToWithoutCache(size_t position) -> void {
if (position >= pos_) {
advanceBy(position - pos_);
} else {
pos_ = -1;
FRESULT res = f_rewind(&file_);
if (res != FR_OK) {
ESP_LOGW(kTag, "error rewinding %u", res);
file_error_ = true;
return;
}
advanceBy(position + 1);
}
}
auto Playlist::countItems() -> void {
TCHAR buff[512];
for (;;) {
auto offset = f_tell(&file_);
auto next_item = nextItem(buff);
if (!next_item) {
break;
}
if (total_size_ % sample_size_ == 0) {
offset_cache_.push_back(offset);
}
total_size_++;
}
f_rewind(&file_);
}
auto Playlist::advanceBy(ssize_t amt) -> bool {
TCHAR buff[512];
std::optional<std::string_view> item;
while (amt > 0) {
item = nextItem(buff);
if (!item) {
break;
}
pos_++;
amt--;
}
if (item) {
current_value_ = *item;
}
return amt == 0;
}
auto Playlist::nextItem(std::span<TCHAR> buf)
-> std::optional<std::string_view> {
while (file_open_ && !file_error_ && !f_eof(&file_)) {
// FIXME: f_gets is quite slow (it does several very small reads instead of
// grabbing a whole sector at a time), and it doesn't work well for very
// long lines. We should do something smarter here.
TCHAR* str = f_gets(buf.data(), buf.size(), &file_);
if (str == NULL) {
ESP_LOGW(kTag, "Error consuming playlist file at offset %llu",
f_tell(&file_));
file_error_ = true;
return {};
}
std::string_view line{str};
if (line.starts_with("#")) {
continue;
}
if (line.ends_with('\n')) {
line = line.substr(0, line.size() - 1);
}
if (line.ends_with('\r')) {
line = line.substr(0, line.size() - 1);
}
return line;
}
// Got to EOF without reading a valid line.
return {};
}
MutablePlaylist::MutablePlaylist(const std::string& playlistFilepath)
: Playlist(playlistFilepath) {}
auto MutablePlaylist::open() -> bool {
std::unique_lock<std::mutex> lock(mutex_);
if (file_open_) {
return true;
}
FRESULT res =
f_open(&file_, filepath_.c_str(), FA_READ | FA_WRITE | FA_OPEN_ALWAYS);
if (res != FR_OK) {
ESP_LOGE(kTag, "failed to open file! res: %i", res);
return false;
}
file_open_ = true;
file_error_ = false;
auto queue_filesize = f_size(&file_);
if (!deserialiseCache()) {
// If there's no cache (or deserialising failed) and the queue is
// sufficiently large, abort and clear the queue
if (queue_filesize > 50000) {
clearLocked();
} else {
// Otherwise, read in the existing entries
countItems();
// Advance to the first item.
skipToWithoutCache(0);
}
}
return !file_error_;
}
auto MutablePlaylist::clear() -> bool {
std::unique_lock<std::mutex> lock(mutex_);
return clearLocked();
}
auto MutablePlaylist::clearLocked() -> bool {
// Try to recover from any IO errors.
if (file_error_ && file_open_) {
file_error_ = false;
file_open_ = false;
f_close(&file_);
}
FRESULT res;
if (file_open_) {
res = f_rewind(&file_);
if (res != FR_OK) {
ESP_LOGE(kTag, "error rewinding %u", res);
file_error_ = true;
return false;
}
res = f_truncate(&file_);
if (res != FR_OK) {
ESP_LOGE(kTag, "error truncating %u", res);
file_error_ = true;
return false;
}
} else {
res = f_open(&file_, filepath_.c_str(),
FA_READ | FA_WRITE | FA_CREATE_ALWAYS);
if (res != FR_OK) {
ESP_LOGE(kTag, "error opening file %u", res);
file_error_ = true;
return false;
}
file_open_ = true;
}
total_size_ = 0;
current_value_.clear();
offset_cache_.clear();
pos_ = -1;
return true;
}
auto MutablePlaylist::append(Item i) -> void {
std::unique_lock<std::mutex> lock(mutex_);
if (!file_open_ || file_error_) {
return;
}
auto offset = f_tell(&file_);
bool first_entry = current_value_.empty();
// Seek to end and append
auto end = f_size(&file_);
auto res = f_lseek(&file_, end);
if (res != FR_OK) {
ESP_LOGE(kTag, "Seek to end of file failed? Error %d", res);
file_error_ = true;
return;
}
// TODO: Resolve paths for track id, etc
std::string path;
if (std::holds_alternative<std::string>(i)) {
path = std::get<std::string>(i);
f_printf(&file_, "%s\n", path.c_str());
if (total_size_ % sample_size_ == 0) {
offset_cache_.push_back(end);
}
if (first_entry) {
current_value_ = path;
}
total_size_++;
}
// Restore position
res = f_lseek(&file_, offset);
if (res != FR_OK) {
ESP_LOGE(kTag, "Failed to restore file position after append?");
file_error_ = true;
return;
}
res = f_sync(&file_);
if (res != FR_OK) {
ESP_LOGE(kTag, "Failed to sync playlist file after append");
file_error_ = true;
return;
}
}
} // namespace audio
|