forked from mixxxdj/mixxx
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcachingreaderworker.cpp
More file actions
298 lines (262 loc) · 11.5 KB
/
Copy pathcachingreaderworker.cpp
File metadata and controls
298 lines (262 loc) · 11.5 KB
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
#include "engine/cachingreader/cachingreaderworker.h"
#include <QAtomicInt>
#include <QtDebug>
#include "analyzer/analyzersilence.h"
#include "moc_cachingreaderworker.cpp"
#include "sources/soundsourceproxy.h"
#include "track/track.h"
#include "util/compatibility/qmutex.h"
#include "util/event.h"
#include "util/fifo.h"
#include "util/logger.h"
#include "util/span.h"
namespace {
mixxx::Logger kLogger("CachingReaderWorker");
// we need the last silence frame and the first sound frame
constexpr SINT kNumSoundFrameToVerify = 2;
} // anonymous namespace
CachingReaderWorker::CachingReaderWorker(
const QString& group,
FIFO<CachingReaderChunkReadRequest>* pChunkReadRequestFIFO,
FIFO<ReaderStatusUpdate>* pReaderStatusFIFO)
: m_group(group),
m_tag(QString("CachingReaderWorker %1").arg(m_group)),
m_pChunkReadRequestFIFO(pChunkReadRequestFIFO),
m_pReaderStatusFIFO(pReaderStatusFIFO) {
}
ReaderStatusUpdate CachingReaderWorker::processReadRequest(
const CachingReaderChunkReadRequest& request) {
CachingReaderChunk* pChunk = request.chunk;
DEBUG_ASSERT(pChunk);
// Before trying to read any data we need to check if the audio source
// is available and if any audio data that is needed by the chunk is
// actually available.
auto chunkFrameIndexRange = pChunk->frameIndexRange(m_pAudioSource);
DEBUG_ASSERT(!m_pAudioSource ||
chunkFrameIndexRange.isSubrangeOf(m_pAudioSource->frameIndexRange()));
if (chunkFrameIndexRange.empty()) {
ReaderStatusUpdate result;
result.init(CHUNK_READ_INVALID, pChunk, m_pAudioSource ? m_pAudioSource->frameIndexRange() : mixxx::IndexRange());
return result;
}
// Try to read the data required for the chunk from the audio source
const mixxx::IndexRange bufferedFrameIndexRange = pChunk->bufferSampleFrames(
m_pAudioSource,
mixxx::SampleBuffer::WritableSlice(m_tempReadBuffer));
DEBUG_ASSERT(!m_pAudioSource ||
bufferedFrameIndexRange.isSubrangeOf(m_pAudioSource->frameIndexRange()));
// The readable frame range might have changed
chunkFrameIndexRange = intersect(chunkFrameIndexRange, m_pAudioSource->frameIndexRange());
DEBUG_ASSERT(bufferedFrameIndexRange.empty() ||
bufferedFrameIndexRange.isSubrangeOf(chunkFrameIndexRange));
ReaderStatus status = bufferedFrameIndexRange.empty() ? CHUNK_READ_EOF : CHUNK_READ_SUCCESS;
if (bufferedFrameIndexRange != chunkFrameIndexRange) {
kLogger.warning()
<< m_group
<< "Failed to read chunk samples for frame index range:"
<< "expected =" << chunkFrameIndexRange
<< ", actual =" << bufferedFrameIndexRange;
if (bufferedFrameIndexRange.empty()) {
status = CHUNK_READ_INVALID; // overwrite EOF (see above)
}
}
if (status == CHUNK_READ_SUCCESS) {
// This call here assumes that the caching reader will read the first sound cue at
// one of the first chunks. The check serves as a sanity check to ensure that the
// sample data has not changed since it has ben analyzed. This could happen because
// of a change in actual audio data or because the file was decoded using a different
// decoder
// This is part of a first prove of concept and needs to be replaces with a different
// solution which is still under discussion. This might be also extended
// to further checks whether a automatic offset adjustment is possible or a the
// sample position metadata shall be treated as outdated.
// Failures of the sanity check only result in an entry into the log at the moment.
verifyFirstSound(pChunk);
}
ReaderStatusUpdate result;
result.init(status, pChunk, m_pAudioSource ? m_pAudioSource->frameIndexRange() : mixxx::IndexRange());
return result;
}
// WARNING: Always called from a different thread (GUI)
void CachingReaderWorker::newTrack(TrackPointer pTrack) {
{
const auto locker = lockMutex(&m_newTrackMutex);
m_pNewTrack = pTrack;
m_newTrackAvailable.storeRelease(1);
}
workReady();
}
void CachingReaderWorker::run() {
// the id of this thread, for debugging purposes
static auto lastId = QAtomicInt(0);
const auto id = lastId.fetchAndAddRelaxed(1) + 1;
QThread::currentThread()->setObjectName(
QStringLiteral("CachingReaderWorker ") + QString::number(id));
Event::start(m_tag);
while (!m_stop.loadAcquire()) {
// Request is initialized by reading from FIFO
CachingReaderChunkReadRequest request;
if (m_newTrackAvailable.loadAcquire()) {
TrackPointer pLoadTrack;
{ // locking scope
const auto locker = lockMutex(&m_newTrackMutex);
pLoadTrack = m_pNewTrack;
m_pNewTrack.reset();
m_newTrackAvailable.storeRelease(0);
} // implicitly unlocks the mutex
if (pLoadTrack) {
// in this case the engine is still running with the old track
loadTrack(pLoadTrack);
} else {
// here, the engine is already stopped
unloadTrack();
}
} else if (m_pChunkReadRequestFIFO->read(&request, 1) == 1) {
// Read the requested chunk and send the result
const ReaderStatusUpdate update = processReadRequest(request);
m_pReaderStatusFIFO->writeBlocking(&update, 1);
} else {
Event::end(m_tag);
m_semaRun.acquire();
Event::start(m_tag);
}
}
}
void CachingReaderWorker::discardAllPendingRequests() {
CachingReaderChunkReadRequest request;
while (m_pChunkReadRequestFIFO->read(&request, 1) == 1) {
const auto update = ReaderStatusUpdate::readDiscarded(request.chunk);
m_pReaderStatusFIFO->writeBlocking(&update, 1);
}
}
void CachingReaderWorker::closeAudioSource() {
discardAllPendingRequests();
if (m_pAudioSource) {
// Closes open file handles of the old track.
m_pAudioSource->close();
m_pAudioSource.reset();
}
// This function has to be called with the engine stopped only
// to avoid collecting new requests for the old track
DEBUG_ASSERT(!m_pChunkReadRequestFIFO->readAvailable());
}
void CachingReaderWorker::unloadTrack() {
closeAudioSource();
const auto update = ReaderStatusUpdate::trackUnloaded();
m_pReaderStatusFIFO->writeBlocking(&update, 1);
}
void CachingReaderWorker::loadTrack(const TrackPointer& pTrack) {
// This emit is directly connected and returns synchronized
// after the engine has been stopped.
emit trackLoading();
closeAudioSource();
if (!pTrack->getFileInfo().checkFileExists()) {
kLogger.warning()
<< m_group
<< "File not found"
<< pTrack->getFileInfo();
const auto update = ReaderStatusUpdate::trackUnloaded();
m_pReaderStatusFIFO->writeBlocking(&update, 1);
emit trackLoadFailed(pTrack,
tr("The file '%1' could not be found.")
.arg(QDir::toNativeSeparators(pTrack->getLocation())));
return;
}
mixxx::AudioSource::OpenParams config;
config.setChannelCount(CachingReaderChunk::kChannels);
m_pAudioSource = SoundSourceProxy(pTrack).openAudioSource(config);
if (!m_pAudioSource) {
kLogger.warning()
<< m_group
<< "Failed to open file"
<< pTrack->getFileInfo();
const auto update = ReaderStatusUpdate::trackUnloaded();
m_pReaderStatusFIFO->writeBlocking(&update, 1);
emit trackLoadFailed(pTrack,
tr("The file '%1' could not be loaded.")
.arg(QDir::toNativeSeparators(pTrack->getLocation())));
return;
}
// Initially assume that the complete content offered by audio source
// is available for reading. Later if read errors occur this value will
// be decreased to avoid repeated reading of corrupt audio data.
if (m_pAudioSource->frameIndexRange().empty()) {
m_pAudioSource.reset(); // Close open file handles
kLogger.warning()
<< m_group
<< "Failed to open empty file"
<< pTrack->getFileInfo();
const auto update = ReaderStatusUpdate::trackUnloaded();
m_pReaderStatusFIFO->writeBlocking(&update, 1);
emit trackLoadFailed(pTrack,
tr("The file '%1' is empty and could not be loaded.")
.arg(QDir::toNativeSeparators(pTrack->getLocation())));
return;
}
// Adjust the internal buffer
const SINT tempReadBufferSize =
m_pAudioSource->getSignalInfo().frames2samples(
CachingReaderChunk::kFrames);
if (m_tempReadBuffer.size() != tempReadBufferSize) {
mixxx::SampleBuffer(tempReadBufferSize).swap(m_tempReadBuffer);
}
const auto update =
ReaderStatusUpdate::trackLoaded(
m_pAudioSource->frameIndexRange());
m_pReaderStatusFIFO->writeBlocking(&update, 1);
// Emit that the track is loaded.
const double sampleCount =
CachingReaderChunk::dFrames2samples(
m_pAudioSource->frameLength());
// This code is a workaround until we have found a better solution to
// verify and correct offsets.
CuePointer pN60dBSound =
pTrack->findCueByType(mixxx::CueType::N60dBSound);
if (pN60dBSound) {
m_firstSoundFrameToVerify = pN60dBSound->getPosition();
}
// The engine must not request any chunks before receiving the
// trackLoaded() signal
DEBUG_ASSERT(!m_pChunkReadRequestFIFO->readAvailable());
emit trackLoaded(
pTrack,
m_pAudioSource->getSignalInfo().getSampleRate(),
sampleCount);
}
void CachingReaderWorker::quitWait() {
m_stop = 1;
m_semaRun.release();
wait();
}
void CachingReaderWorker::verifyFirstSound(const CachingReaderChunk* pChunk) {
if (!m_firstSoundFrameToVerify.isValid()) {
return;
}
const int firstSoundIndex =
CachingReaderChunk::indexForFrame(static_cast<SINT>(
m_firstSoundFrameToVerify.toLowerFrameBoundary()
.value()));
if (pChunk->getIndex() == firstSoundIndex) {
CSAMPLE sampleBuffer[kNumSoundFrameToVerify * mixxx::kEngineChannelCount];
SINT end = static_cast<SINT>(m_firstSoundFrameToVerify.toLowerFrameBoundary().value()) + 1;
mixxx::IndexRange probeFrameIndexRange =
mixxx::IndexRange::between(end - kNumSoundFrameToVerify, end);
mixxx::IndexRange bufferedFrameIndexRange =
pChunk->readBufferedSampleFrames(
sampleBuffer, probeFrameIndexRange);
VERIFY_OR_DEBUG_ASSERT(bufferedFrameIndexRange == probeFrameIndexRange) {
return;
}
if (AnalyzerSilence::verifyFirstSound(std::span<const CSAMPLE>(sampleBuffer),
mixxx::audio::FramePos(1))) {
qDebug() << "First sound found at the previously stored position";
} else {
// This can happen in case of track edits or replacements, changed
// encoders or encoding issues.
qWarning() << "First sound has been moved! The beatgrid and "
"other annotations are no longer valid"
<< m_pAudioSource->getUrlString();
}
m_firstSoundFrameToVerify = mixxx::audio::FramePos();
}
}