sfizz/sources/FilePool.cpp

73 lines
2.7 KiB
C++
Raw Normal View History

2019-08-05 00:38:24 +02:00
#include "FilePool.h"
2019-08-21 01:00:07 +02:00
#include "gsl/gsl-lite.hpp"
2019-08-07 23:39:35 +02:00
#include <chrono>
using namespace std::chrono_literals;
2019-08-05 00:38:24 +02:00
std::optional<sfz::FilePool::FileInformation> sfz::FilePool::getFileInformation(std::string_view filename)
{
std::filesystem::path file { rootDirectory / filename };
if (!std::filesystem::exists(file))
return {};
SndfileHandle sndFile ( reinterpret_cast<const char*>(file.c_str()) );
FileInformation returnedValue;
returnedValue.end = static_cast<uint32_t>(sndFile.frames());
returnedValue.sampleRate = static_cast<double>(sndFile.samplerate());
2019-08-05 00:38:24 +02:00
SF_INSTRUMENT instrumentInfo;
sndFile.command(SFC_GET_INSTRUMENT, &instrumentInfo, sizeof(instrumentInfo));
if (instrumentInfo.loop_count == 1)
{
returnedValue.loopBegin = instrumentInfo.loops[0].start;
returnedValue.loopEnd = instrumentInfo.loops[0].end;
}
auto preloadedSize = std::min(returnedValue.end, static_cast<uint32_t>(config::preloadSize));
returnedValue.preloadedData = std::make_shared<StereoBuffer<float>>(preloadedSize);
sndFile.readf(tempReadBuffer.data(), preloadedSize);
2019-08-21 01:00:07 +02:00
returnedValue.preloadedData->readInterleaved(gsl::make_span(tempReadBuffer).first(preloadedSize));
2019-08-05 00:38:24 +02:00
preloadedData[filename] = returnedValue.preloadedData;
// char buffer [2048] ;
// sndFile.command(SFC_GET_LOG_INFO, buffer, sizeof(buffer)) ;
// DBG(buffer);
return returnedValue;
}
void sfz::FilePool::enqueueLoading(Voice* voice, std::string_view sample, int numFrames)
{
if (!loadingQueue.try_enqueue({ voice, sample, numFrames }))
2019-08-11 11:10:04 +02:00
{
DBG("Problem enqueuing a file read for file " << sample);
2019-08-11 11:10:04 +02:00
}
}
void sfz::FilePool::loadingThread()
{
2019-08-11 11:10:04 +02:00
FileLoadingInformation fileToLoad {};
2019-08-07 23:39:35 +02:00
while (!quitThread)
{
2019-08-07 23:39:35 +02:00
if (!loadingQueue.wait_dequeue_timed(fileToLoad, 1ms))
continue;
if (fileToLoad.voice == nullptr)
{
DBG("Background thread error: voice is null.");
continue;
}
DBG("Background loading of: " << fileToLoad.sample);
std::filesystem::path file { rootDirectory / fileToLoad.sample };
if (!std::filesystem::exists(file))
{
DBG("Background thread: no file " << fileToLoad.sample << " exists.");
continue;
}
SndfileHandle sndFile ( reinterpret_cast<const char*>(file.c_str()) );
auto fileLoaded = std::make_unique<StereoBuffer<float>>(fileToLoad.numFrames);
auto readBuffer = std::make_unique<Buffer<float>>(fileToLoad.numFrames * 2);
sndFile.readf(readBuffer->data(), fileToLoad.numFrames);
2019-08-21 01:00:07 +02:00
fileLoaded->readInterleaved(*readBuffer);
fileToLoad.voice->setFileData(std::move(fileLoaded));
}
2019-08-05 00:38:24 +02:00
}