Chris@148: /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ Chris@148: Chris@148: /* Chris@148: Sonic Visualiser Chris@148: An audio file viewer and annotation editor. Chris@148: Centre for Digital Music, Queen Mary, University of London. Chris@202: This file copyright 2006 Chris Cannam and QMUL. Chris@148: Chris@148: This program is free software; you can redistribute it and/or Chris@148: modify it under the terms of the GNU General Public License as Chris@148: published by the Free Software Foundation; either version 2 of the Chris@148: License, or (at your option) any later version. See the file Chris@148: COPYING included with this distribution for more information. Chris@148: */ Chris@148: Chris@148: #include "FFTDataServer.h" Chris@148: Chris@148: #include "FFTFileCache.h" Chris@159: #include "FFTMemoryCache.h" Chris@148: Chris@148: #include "model/DenseTimeValueModel.h" Chris@148: Chris@150: #include "system/System.h" Chris@148: Chris@168: #include "base/StorageAdviser.h" Chris@200: #include "base/Exceptions.h" Chris@183: #include "base/Profiler.h" Chris@168: Chris@200: #include Chris@200: #include Chris@200: Chris@168: Chris@223: #define DEBUG_FFT_SERVER 1 Chris@194: //#define DEBUG_FFT_SERVER_FILL 1 Chris@148: Chris@148: #ifdef DEBUG_FFT_SERVER_FILL Chris@153: #ifndef DEBUG_FFT_SERVER Chris@153: #define DEBUG_FFT_SERVER 1 Chris@153: #endif Chris@148: #endif Chris@148: Chris@148: FFTDataServer::ServerMap FFTDataServer::m_servers; Chris@215: FFTDataServer::ServerQueue FFTDataServer::m_releasedServers; Chris@148: QMutex FFTDataServer::m_serverMapMutex; Chris@148: Chris@148: FFTDataServer * Chris@148: FFTDataServer::getInstance(const DenseTimeValueModel *model, Chris@148: int channel, Chris@148: WindowType windowType, Chris@148: size_t windowSize, Chris@148: size_t windowIncrement, Chris@148: size_t fftSize, Chris@148: bool polar, Chris@148: size_t fillFromColumn) Chris@148: { Chris@148: QString n = generateFileBasename(model, Chris@148: channel, Chris@148: windowType, Chris@148: windowSize, Chris@148: windowIncrement, Chris@148: fftSize, Chris@148: polar); Chris@148: Chris@148: FFTDataServer *server = 0; Chris@148: Chris@148: QMutexLocker locker(&m_serverMapMutex); Chris@148: Chris@148: if ((server = findServer(n))) { Chris@148: return server; Chris@148: } Chris@148: Chris@148: QString npn = generateFileBasename(model, Chris@148: channel, Chris@148: windowType, Chris@148: windowSize, Chris@148: windowIncrement, Chris@148: fftSize, Chris@148: !polar); Chris@148: Chris@148: if ((server = findServer(npn))) { Chris@148: return server; Chris@148: } Chris@148: Chris@200: try { Chris@200: server = new FFTDataServer(n, Chris@200: model, Chris@200: channel, Chris@200: windowType, Chris@200: windowSize, Chris@200: windowIncrement, Chris@200: fftSize, Chris@200: polar, Chris@200: fillFromColumn); Chris@200: } catch (InsufficientDiscSpace) { Chris@200: delete server; Chris@200: server = 0; Chris@200: } Chris@148: Chris@200: if (server) { Chris@200: m_servers[n] = ServerCountPair(server, 1); Chris@200: } Chris@200: Chris@200: return server; Chris@148: } Chris@148: Chris@148: FFTDataServer * Chris@148: FFTDataServer::getFuzzyInstance(const DenseTimeValueModel *model, Chris@148: int channel, Chris@148: WindowType windowType, Chris@148: size_t windowSize, Chris@148: size_t windowIncrement, Chris@148: size_t fftSize, Chris@148: bool polar, Chris@148: size_t fillFromColumn) Chris@148: { Chris@148: // Fuzzy matching: Chris@148: // Chris@148: // -- if we're asked for polar and have non-polar, use it (and Chris@148: // vice versa). This one is vital, and we do it for non-fuzzy as Chris@148: // well (above). Chris@148: // Chris@148: // -- if we're asked for an instance with a given fft size and we Chris@148: // have one already with a multiple of that fft size but the same Chris@148: // window size and type (and model), we can draw the results from Chris@148: // it (e.g. the 1st, 2nd, 3rd etc bins of a 512-sample FFT are the Chris@148: // same as the the 1st, 5th, 9th etc of a 2048-sample FFT of the Chris@148: // same window plus zero padding). Chris@148: // Chris@148: // -- if we're asked for an instance with a given window type and Chris@148: // size and fft size and we have one already the same but with a Chris@148: // smaller increment, we can draw the results from it (provided Chris@148: // our increment is a multiple of its) Chris@148: // Chris@152: // The FFTModel knows how to interpret these things. In Chris@148: // both cases we require that the larger one is a power-of-two Chris@148: // multiple of the smaller (e.g. even though in principle you can Chris@148: // draw the results at increment 256 from those at increment 768 Chris@152: // or 1536, the model doesn't support this). Chris@148: Chris@148: { Chris@148: QMutexLocker locker(&m_serverMapMutex); Chris@148: Chris@148: ServerMap::iterator best = m_servers.end(); Chris@148: int bestdist = -1; Chris@148: Chris@148: for (ServerMap::iterator i = m_servers.begin(); i != m_servers.end(); ++i) { Chris@148: Chris@148: FFTDataServer *server = i->second.first; Chris@148: Chris@148: if (server->getModel() == model && Chris@148: (server->getChannel() == channel || model->getChannelCount() == 1) && Chris@148: server->getWindowType() == windowType && Chris@148: server->getWindowSize() == windowSize && Chris@148: server->getWindowIncrement() <= windowIncrement && Chris@148: server->getFFTSize() >= fftSize) { Chris@148: Chris@148: if ((windowIncrement % server->getWindowIncrement()) != 0) continue; Chris@148: int ratio = windowIncrement / server->getWindowIncrement(); Chris@148: bool poweroftwo = true; Chris@148: while (ratio > 1) { Chris@148: if (ratio & 0x1) { Chris@148: poweroftwo = false; Chris@148: break; Chris@148: } Chris@148: ratio >>= 1; Chris@148: } Chris@148: if (!poweroftwo) continue; Chris@148: Chris@148: if ((server->getFFTSize() % fftSize) != 0) continue; Chris@148: ratio = server->getFFTSize() / fftSize; Chris@148: while (ratio > 1) { Chris@148: if (ratio & 0x1) { Chris@148: poweroftwo = false; Chris@148: break; Chris@148: } Chris@148: ratio >>= 1; Chris@148: } Chris@148: if (!poweroftwo) continue; Chris@148: Chris@148: int distance = 0; Chris@148: Chris@148: if (server->getPolar() != polar) distance += 1; Chris@148: Chris@148: distance += ((windowIncrement / server->getWindowIncrement()) - 1) * 15; Chris@148: distance += ((server->getFFTSize() / fftSize) - 1) * 10; Chris@148: Chris@148: if (server->getFillCompletion() < 50) distance += 100; Chris@148: Chris@148: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::getFuzzyInstance: Distance for server " << server << " is " << distance << ", best is " << bestdist << std::endl; Chris@148: #endif Chris@148: Chris@148: if (bestdist == -1 || distance < bestdist) { Chris@148: bestdist = distance; Chris@148: best = i; Chris@148: } Chris@148: } Chris@148: } Chris@148: Chris@148: if (bestdist >= 0) { Chris@216: FFTDataServer *server = best->second.first; Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::getFuzzyInstance: We like server " << server << " (with distance " << bestdist << ")" << std::endl; Chris@216: #endif Chris@216: claimInstance(server, false); Chris@216: return server; Chris@148: } Chris@148: } Chris@148: Chris@148: // Nothing found, make a new one Chris@148: Chris@148: return getInstance(model, Chris@148: channel, Chris@148: windowType, Chris@148: windowSize, Chris@148: windowIncrement, Chris@148: fftSize, Chris@148: polar, Chris@148: fillFromColumn); Chris@148: } Chris@148: Chris@148: FFTDataServer * Chris@148: FFTDataServer::findServer(QString n) Chris@148: { Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::findServer(\"" << n.toStdString() << "\")" << std::endl; Chris@216: #endif Chris@216: Chris@148: if (m_servers.find(n) != m_servers.end()) { Chris@216: Chris@216: FFTDataServer *server = m_servers[n].first; Chris@216: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::findServer(\"" << n.toStdString() << "\"): found " << server << std::endl; Chris@216: #endif Chris@216: Chris@216: claimInstance(server, false); Chris@216: Chris@216: return server; Chris@148: } Chris@148: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::findServer(\"" << n.toStdString() << "\"): not found" << std::endl; Chris@216: #endif Chris@216: Chris@148: return 0; Chris@148: } Chris@148: Chris@148: void Chris@152: FFTDataServer::claimInstance(FFTDataServer *server) Chris@152: { Chris@216: claimInstance(server, true); Chris@216: } Chris@216: Chris@216: void Chris@216: FFTDataServer::claimInstance(FFTDataServer *server, bool needLock) Chris@216: { Chris@216: QMutexLocker locker(needLock ? &m_serverMapMutex : 0); Chris@216: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::claimInstance(" << server << ")" << std::endl; Chris@216: #endif Chris@152: Chris@152: for (ServerMap::iterator i = m_servers.begin(); i != m_servers.end(); ++i) { Chris@152: if (i->second.first == server) { Chris@215: Chris@215: for (ServerQueue::iterator j = m_releasedServers.begin(); Chris@215: j != m_releasedServers.end(); ++j) { Chris@216: Chris@215: if (*j == server) { Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::claimInstance: found in released server list, removing from it" << std::endl; Chris@216: #endif Chris@215: m_releasedServers.erase(j); Chris@215: break; Chris@215: } Chris@215: } Chris@215: Chris@152: ++i->second.second; Chris@216: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::claimInstance: new refcount is " << i->second.second << std::endl; Chris@216: #endif Chris@216: Chris@152: return; Chris@152: } Chris@152: } Chris@152: Chris@152: std::cerr << "ERROR: FFTDataServer::claimInstance: instance " Chris@152: << server << " unknown!" << std::endl; Chris@152: } Chris@152: Chris@152: void Chris@148: FFTDataServer::releaseInstance(FFTDataServer *server) Chris@148: { Chris@216: releaseInstance(server, true); Chris@216: } Chris@216: Chris@216: void Chris@216: FFTDataServer::releaseInstance(FFTDataServer *server, bool needLock) Chris@216: { Chris@216: QMutexLocker locker(needLock ? &m_serverMapMutex : 0); Chris@216: Chris@148: #ifdef DEBUG_FFT_SERVER Chris@148: std::cerr << "FFTDataServer::releaseInstance(" << server << ")" << std::endl; Chris@148: #endif Chris@148: Chris@148: // -- if ref count > 0, decrement and return Chris@148: // -- if the instance hasn't been used at all, delete it immediately Chris@148: // -- if fewer than N instances (N = e.g. 3) remain with zero refcounts, Chris@148: // leave them hanging around Chris@148: // -- if N instances with zero refcounts remain, delete the one that Chris@148: // was last released first Chris@148: // -- if we run out of disk space when allocating an instance, go back Chris@148: // and delete the spare N instances before trying again Chris@148: // -- have an additional method to indicate that a model has been Chris@148: // destroyed, so that we can delete all of its fft server instances Chris@148: Chris@148: for (ServerMap::iterator i = m_servers.begin(); i != m_servers.end(); ++i) { Chris@148: if (i->second.first == server) { Chris@148: if (i->second.second == 0) { Chris@148: std::cerr << "ERROR: FFTDataServer::releaseInstance(" Chris@148: << server << "): instance not allocated" << std::endl; Chris@148: } else if (--i->second.second == 0) { Chris@148: if (server->m_lastUsedCache == -1) { // never used Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::releaseInstance: instance " Chris@216: << server << " has never been used, erasing" Chris@216: << std::endl; Chris@216: #endif Chris@148: delete server; Chris@148: m_servers.erase(i); Chris@148: } else { Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::releaseInstance: instance " Chris@216: << server << " no longer in use, marking for possible collection" Chris@216: << std::endl; Chris@216: #endif Chris@216: bool found = false; Chris@216: for (ServerQueue::iterator j = m_releasedServers.begin(); Chris@216: j != m_releasedServers.end(); ++j) { Chris@216: if (*j == server) { Chris@216: std::cerr << "ERROR: FFTDataServer::releaseInstance(" Chris@216: << server << "): server is already in " Chris@216: << "released servers list" << std::endl; Chris@216: found = true; Chris@216: } Chris@216: } Chris@216: if (!found) m_releasedServers.push_back(server); Chris@148: server->suspend(); Chris@148: purgeLimbo(); Chris@148: } Chris@216: } else { Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::releaseInstance: instance " Chris@216: << server << " now has refcount " << i->second.second Chris@216: << std::endl; Chris@216: #endif Chris@148: } Chris@148: return; Chris@148: } Chris@148: } Chris@148: Chris@148: std::cerr << "ERROR: FFTDataServer::releaseInstance(" << server << "): " Chris@148: << "instance not found" << std::endl; Chris@148: } Chris@148: Chris@148: void Chris@148: FFTDataServer::purgeLimbo(int maxSize) Chris@148: { Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::purgeLimbo(" << maxSize << "): " Chris@216: << m_releasedServers.size() << " candidates" << std::endl; Chris@216: #endif Chris@216: Chris@215: while (m_releasedServers.size() > maxSize) { Chris@148: Chris@215: FFTDataServer *server = *m_releasedServers.begin(); Chris@148: Chris@215: bool found = false; Chris@215: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::purgeLimbo: considering candidate " Chris@216: << server << std::endl; Chris@216: #endif Chris@216: Chris@215: for (ServerMap::iterator i = m_servers.begin(); i != m_servers.end(); ++i) { Chris@215: Chris@215: if (i->second.first == server) { Chris@215: found = true; Chris@215: if (i->second.second > 0) { Chris@215: std::cerr << "ERROR: FFTDataServer::purgeLimbo: Server " Chris@215: << server << " is in released queue, but still has non-zero refcount " Chris@215: << i->second.second << std::endl; Chris@215: // ... so don't delete it Chris@215: break; Chris@215: } Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::purgeLimbo: looks OK, erasing it" Chris@216: << std::endl; Chris@216: #endif Chris@216: Chris@148: m_servers.erase(i); Chris@215: delete server; Chris@215: break; Chris@148: } Chris@148: } Chris@215: Chris@215: if (!found) { Chris@215: std::cerr << "ERROR: FFTDataServer::purgeLimbo: Server " Chris@215: << server << " is in released queue, but not in server map!" Chris@215: << std::endl; Chris@215: delete server; Chris@215: } Chris@215: Chris@215: m_releasedServers.pop_front(); Chris@215: } Chris@216: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::purgeLimbo(" << maxSize << "): " Chris@216: << m_releasedServers.size() << " remain" << std::endl; Chris@216: #endif Chris@216: Chris@215: } Chris@215: Chris@215: void Chris@215: FFTDataServer::modelAboutToBeDeleted(Model *model) Chris@215: { Chris@215: QMutexLocker locker(&m_serverMapMutex); Chris@215: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::modelAboutToBeDeleted(" << model << ")" Chris@216: << std::endl; Chris@216: #endif Chris@216: Chris@215: for (ServerMap::iterator i = m_servers.begin(); i != m_servers.end(); ++i) { Chris@215: Chris@215: FFTDataServer *server = i->second.first; Chris@215: Chris@215: if (server->getModel() == model) { Chris@216: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::modelAboutToBeDeleted: server is " Chris@216: << server << std::endl; Chris@216: #endif Chris@216: Chris@215: if (i->second.second > 0) { Chris@215: std::cerr << "ERROR: FFTDataServer::modelAboutToBeDeleted: Model " << model << " (\"" << model->objectName().toStdString() << "\") is about to be deleted, but is still being referred to by FFT server " << server << " with non-zero refcount " << i->second.second << std::endl; Chris@215: } Chris@215: for (ServerQueue::iterator j = m_releasedServers.begin(); Chris@215: j != m_releasedServers.end(); ++j) { Chris@215: if (*j == server) { Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::modelAboutToBeDeleted: erasing from released servers" << std::endl; Chris@216: #endif Chris@215: m_releasedServers.erase(j); Chris@215: break; Chris@215: } Chris@215: } Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer::modelAboutToBeDeleted: erasing server" << std::endl; Chris@216: #endif Chris@215: m_servers.erase(i); Chris@215: delete server; Chris@215: return; Chris@215: } Chris@148: } Chris@148: } Chris@148: Chris@148: FFTDataServer::FFTDataServer(QString fileBaseName, Chris@148: const DenseTimeValueModel *model, Chris@148: int channel, Chris@148: WindowType windowType, Chris@148: size_t windowSize, Chris@148: size_t windowIncrement, Chris@148: size_t fftSize, Chris@148: bool polar, Chris@148: size_t fillFromColumn) : Chris@148: m_fileBaseName(fileBaseName), Chris@148: m_model(model), Chris@148: m_channel(channel), Chris@148: m_windower(windowType, windowSize), Chris@148: m_windowSize(windowSize), Chris@148: m_windowIncrement(windowIncrement), Chris@148: m_fftSize(fftSize), Chris@148: m_polar(polar), Chris@183: m_width(0), Chris@183: m_height(0), Chris@183: m_cacheWidth(0), Chris@172: m_memoryCache(false), Chris@172: m_compactCache(false), Chris@148: m_lastUsedCache(-1), Chris@148: m_fftInput(0), Chris@148: m_exiting(false), Chris@153: m_suspended(true), //!!! or false? Chris@148: m_fillThread(0) Chris@148: { Chris@193: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "])::FFTDataServer" << std::endl; Chris@193: #endif Chris@193: Chris@148: size_t start = m_model->getStartFrame(); Chris@148: size_t end = m_model->getEndFrame(); Chris@148: Chris@148: m_width = (end - start) / m_windowIncrement + 1; Chris@203: m_height = m_fftSize / 2 + 1; // DC == 0, Nyquist == fftsize/2 Chris@148: Chris@216: #ifdef DEBUG_FFT_SERVER Chris@216: std::cerr << "FFTDataServer(" << this << "): dimensions are " Chris@216: << m_width << "x" << m_height << std::endl; Chris@216: #endif Chris@216: Chris@148: size_t maxCacheSize = 20 * 1024 * 1024; Chris@148: size_t columnSize = m_height * sizeof(fftsample) * 2 + sizeof(fftsample); Chris@148: if (m_width * columnSize < maxCacheSize * 2) m_cacheWidth = m_width; Chris@148: else m_cacheWidth = maxCacheSize / columnSize; Chris@148: Chris@148: int bits = 0; Chris@148: while (m_cacheWidth) { m_cacheWidth >>= 1; ++bits; } Chris@148: m_cacheWidth = 2; Chris@148: while (bits) { m_cacheWidth <<= 1; --bits; } Chris@172: Chris@172: //!!! Need to pass in what this server is intended for Chris@172: // (e.g. playback processing, spectrogram, feature extraction), Chris@172: // or pass in something akin to the storage adviser criteria. Chris@172: // That probably goes alongside the polar argument. Chris@172: // For now we'll assume "spectrogram" criteria for polar ffts, Chris@172: // and "feature extraction" criteria for rectangular ones. Chris@172: Chris@172: StorageAdviser::Criteria criteria; Chris@172: if (m_polar) { Chris@172: criteria = StorageAdviser::Criteria Chris@172: (StorageAdviser::SpeedCritical | StorageAdviser::LongRetentionLikely); Chris@172: } else { Chris@172: criteria = StorageAdviser::Criteria(StorageAdviser::PrecisionCritical); Chris@172: } Chris@172: Chris@172: int cells = m_width * m_height; Chris@172: int minimumSize = (cells / 1024) * sizeof(uint16_t); // kb Chris@172: int maximumSize = (cells / 1024) * sizeof(float); // kb Chris@215: Chris@215: StorageAdviser::Recommendation recommendation; Chris@172: Chris@215: try { Chris@215: Chris@215: recommendation = Chris@215: StorageAdviser::recommend(criteria, minimumSize, maximumSize); Chris@215: Chris@215: } catch (InsufficientDiscSpace s) { Chris@215: Chris@215: // Delete any unused servers we may have been leaving around Chris@215: // in case we wanted them again Chris@215: Chris@215: purgeLimbo(0); Chris@215: Chris@215: // This time we don't catch InsufficientDiscSpace -- we Chris@215: // haven't allocated anything yet and can safely let the Chris@215: // exception out to indicate to the caller that we can't Chris@215: // handle it. Chris@215: Chris@215: recommendation = Chris@215: StorageAdviser::recommend(criteria, minimumSize, maximumSize); Chris@215: } Chris@172: Chris@172: std::cerr << "Recommendation was: " << recommendation << std::endl; Chris@172: Chris@172: m_memoryCache = ((recommendation & StorageAdviser::UseMemory) || Chris@172: (recommendation & StorageAdviser::PreferMemory)); Chris@172: Chris@172: m_compactCache = (recommendation & StorageAdviser::ConserveSpace); Chris@148: Chris@148: #ifdef DEBUG_FFT_SERVER Chris@148: std::cerr << "Width " << m_width << ", cache width " << m_cacheWidth << " (size " << m_cacheWidth * columnSize << ")" << std::endl; Chris@148: #endif Chris@148: Chris@205: StorageAdviser::notifyPlannedAllocation Chris@205: (m_memoryCache ? StorageAdviser::MemoryAllocation : Chris@205: StorageAdviser::DiscAllocation, Chris@205: m_compactCache ? minimumSize : maximumSize); Chris@205: Chris@148: for (size_t i = 0; i <= m_width / m_cacheWidth; ++i) { Chris@148: m_caches.push_back(0); Chris@148: } Chris@148: Chris@148: m_fftInput = (fftsample *) Chris@148: fftwf_malloc(fftSize * sizeof(fftsample)); Chris@148: Chris@148: m_fftOutput = (fftwf_complex *) Chris@203: fftwf_malloc((fftSize/2 + 1) * sizeof(fftwf_complex)); Chris@148: Chris@148: m_workbuffer = (float *) Chris@203: fftwf_malloc((fftSize+2) * sizeof(float)); Chris@148: Chris@148: m_fftPlan = fftwf_plan_dft_r2c_1d(m_fftSize, Chris@148: m_fftInput, Chris@148: m_fftOutput, Chris@148: FFTW_ESTIMATE); Chris@148: Chris@148: if (!m_fftPlan) { Chris@148: std::cerr << "ERROR: fftwf_plan_dft_r2c_1d(" << m_windowSize << ") failed!" << std::endl; Chris@148: throw(0); Chris@148: } Chris@148: Chris@148: m_fillThread = new FillThread(*this, fillFromColumn); Chris@148: } Chris@148: Chris@148: FFTDataServer::~FFTDataServer() Chris@148: { Chris@148: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "])::~FFTDataServer()" << std::endl; Chris@148: #endif Chris@148: Chris@155: m_suspended = false; Chris@148: m_exiting = true; Chris@148: m_condition.wakeAll(); Chris@148: if (m_fillThread) { Chris@148: m_fillThread->wait(); Chris@148: delete m_fillThread; Chris@148: } Chris@148: Chris@148: QMutexLocker locker(&m_writeMutex); Chris@148: Chris@148: for (CacheVector::iterator i = m_caches.begin(); i != m_caches.end(); ++i) { Chris@205: if (*i) { Chris@205: delete *i; Chris@205: } else { Chris@205: StorageAdviser::notifyDoneAllocation Chris@205: (m_memoryCache ? StorageAdviser::MemoryAllocation : Chris@205: StorageAdviser::DiscAllocation, Chris@205: m_cacheWidth * m_height * Chris@205: (m_compactCache ? sizeof(uint16_t) : sizeof(float)) / 1024 + 1); Chris@205: } Chris@148: } Chris@148: Chris@148: deleteProcessingData(); Chris@148: } Chris@148: Chris@148: void Chris@148: FFTDataServer::deleteProcessingData() Chris@148: { Chris@193: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "]): deleteProcessingData" << std::endl; Chris@193: #endif Chris@148: if (m_fftInput) { Chris@148: fftwf_destroy_plan(m_fftPlan); Chris@148: fftwf_free(m_fftInput); Chris@148: fftwf_free(m_fftOutput); Chris@148: fftwf_free(m_workbuffer); Chris@148: } Chris@148: m_fftInput = 0; Chris@148: } Chris@148: Chris@148: void Chris@148: FFTDataServer::suspend() Chris@148: { Chris@148: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "]): suspend" << std::endl; Chris@148: #endif Chris@183: Profiler profiler("FFTDataServer::suspend", false); Chris@183: Chris@148: QMutexLocker locker(&m_writeMutex); Chris@148: m_suspended = true; Chris@148: for (CacheVector::iterator i = m_caches.begin(); i != m_caches.end(); ++i) { Chris@148: if (*i) (*i)->suspend(); Chris@148: } Chris@148: } Chris@148: Chris@148: void Chris@155: FFTDataServer::suspendWrites() Chris@155: { Chris@155: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "]): suspendWrites" << std::endl; Chris@155: #endif Chris@183: Profiler profiler("FFTDataServer::suspendWrites", false); Chris@183: Chris@155: m_suspended = true; Chris@155: } Chris@155: Chris@155: void Chris@148: FFTDataServer::resume() Chris@148: { Chris@154: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "]): resume" << std::endl; Chris@154: #endif Chris@183: Profiler profiler("FFTDataServer::resume", false); Chris@183: Chris@148: m_suspended = false; Chris@157: if (m_fillThread) { Chris@157: if (m_fillThread->isFinished()) { Chris@157: delete m_fillThread; Chris@157: m_fillThread = 0; Chris@157: deleteProcessingData(); Chris@157: } else { Chris@157: m_condition.wakeAll(); Chris@157: } Chris@157: } Chris@148: } Chris@148: Chris@148: FFTCache * Chris@148: FFTDataServer::getCacheAux(size_t c) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::getCacheAux", false); Chris@193: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "])::getCacheAux" << std::endl; Chris@193: #endif Chris@183: Chris@148: QMutexLocker locker(&m_writeMutex); Chris@148: Chris@148: if (m_lastUsedCache == -1) { Chris@148: m_fillThread->start(); Chris@148: } Chris@148: Chris@148: if (int(c) != m_lastUsedCache) { Chris@148: Chris@148: // std::cerr << "switch from " << m_lastUsedCache << " to " << c << std::endl; Chris@148: Chris@148: for (IntQueue::iterator i = m_dormantCaches.begin(); Chris@148: i != m_dormantCaches.end(); ++i) { Chris@148: if (*i == c) { Chris@148: m_dormantCaches.erase(i); Chris@148: break; Chris@148: } Chris@148: } Chris@148: Chris@148: if (m_lastUsedCache >= 0) { Chris@148: bool inDormant = false; Chris@148: for (size_t i = 0; i < m_dormantCaches.size(); ++i) { Chris@148: if (m_dormantCaches[i] == m_lastUsedCache) { Chris@148: inDormant = true; Chris@148: break; Chris@148: } Chris@148: } Chris@148: if (!inDormant) { Chris@148: m_dormantCaches.push_back(m_lastUsedCache); Chris@148: } Chris@148: while (m_dormantCaches.size() > 4) { Chris@148: int dc = m_dormantCaches.front(); Chris@148: m_dormantCaches.pop_front(); Chris@148: m_caches[dc]->suspend(); Chris@148: } Chris@148: } Chris@148: } Chris@148: Chris@148: if (m_caches[c]) { Chris@148: m_lastUsedCache = c; Chris@148: return m_caches[c]; Chris@148: } Chris@148: Chris@148: QString name = QString("%1-%2").arg(m_fileBaseName).arg(c); Chris@148: Chris@172: FFTCache *cache = 0; Chris@172: Chris@213: size_t width = m_cacheWidth; Chris@213: if (c * m_cacheWidth + width > m_width) { Chris@213: width = m_width - c * m_cacheWidth; Chris@213: } Chris@213: Chris@200: try { Chris@200: Chris@200: if (m_memoryCache) { Chris@172: Chris@200: cache = new FFTMemoryCache(); Chris@172: Chris@200: } else if (m_compactCache) { Chris@172: Chris@200: cache = new FFTFileCache(name, MatrixFile::ReadWrite, Chris@200: FFTFileCache::Compact); Chris@172: Chris@200: } else { Chris@172: Chris@200: cache = new FFTFileCache(name, MatrixFile::ReadWrite, Chris@200: m_polar ? FFTFileCache::Polar : Chris@200: FFTFileCache::Rectangular); Chris@200: } Chris@200: Chris@200: cache->resize(width, m_height); Chris@200: cache->reset(); Chris@200: Chris@213: } catch (std::bad_alloc) { Chris@205: Chris@213: delete cache; Chris@213: cache = 0; Chris@213: Chris@213: if (m_memoryCache) { Chris@213: Chris@213: std::cerr << "WARNING: Memory allocation failed when resizing" Chris@213: << " FFT memory cache no. " << c << " to " << width Chris@213: << "x" << m_height << " (of total width " << m_width Chris@213: << "): falling back to disc cache" << std::endl; Chris@213: Chris@213: try { Chris@213: Chris@213: cache = new FFTFileCache(name, MatrixFile::ReadWrite, Chris@213: FFTFileCache::Compact); Chris@213: Chris@213: cache->resize(width, m_height); Chris@213: cache->reset(); Chris@213: Chris@213: } catch (std::bad_alloc) { Chris@213: Chris@213: delete cache; Chris@213: cache = 0; Chris@213: } Chris@213: } Chris@213: Chris@213: if (cache) { Chris@213: std::cerr << "ERROR: Memory allocation failed when resizing" Chris@213: << " FFT file cache no. " << c << " to " << width Chris@213: << "x" << m_height << " (of total width " << m_width Chris@213: << "): abandoning this cache" << std::endl; Chris@213: } Chris@213: Chris@200: //!!! Shouldn't be using QtGui here. Need a better way to report this. Chris@200: QMessageBox::critical Chris@200: (0, QApplication::tr("FFT cache resize failed"), Chris@200: QApplication::tr Chris@200: ("Failed to create or resize an FFT model slice.\n" Chris@200: "There may be insufficient memory or disc space to continue.")); Chris@172: } Chris@148: Chris@213: StorageAdviser::notifyDoneAllocation Chris@213: (m_memoryCache ? StorageAdviser::MemoryAllocation : Chris@213: StorageAdviser::DiscAllocation, Chris@213: width * m_height * Chris@213: (m_compactCache ? sizeof(uint16_t) : sizeof(float)) / 1024 + 1); Chris@213: Chris@148: m_caches[c] = cache; Chris@148: m_lastUsedCache = c; Chris@148: return cache; Chris@148: } Chris@148: Chris@148: float Chris@148: FFTDataServer::getMagnitudeAt(size_t x, size_t y) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::getMagnitudeAt", false); Chris@183: Chris@217: if (x >= m_width || y >= m_height) return 0; Chris@217: Chris@148: size_t col; Chris@148: FFTCache *cache = getCache(x, col); Chris@200: if (!cache) return 0; Chris@148: Chris@148: if (!cache->haveSetColumnAt(col)) { Chris@183: std::cerr << "FFTDataServer::getMagnitudeAt: calling fillColumn(" Chris@183: << x << ")" << std::endl; Chris@148: fillColumn(x); Chris@148: } Chris@148: return cache->getMagnitudeAt(col, y); Chris@148: } Chris@148: Chris@148: float Chris@148: FFTDataServer::getNormalizedMagnitudeAt(size_t x, size_t y) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::getNormalizedMagnitudeAt", false); Chris@183: Chris@217: if (x >= m_width || y >= m_height) return 0; Chris@217: Chris@148: size_t col; Chris@148: FFTCache *cache = getCache(x, col); Chris@200: if (!cache) return 0; Chris@148: Chris@148: if (!cache->haveSetColumnAt(col)) { Chris@148: fillColumn(x); Chris@148: } Chris@148: return cache->getNormalizedMagnitudeAt(col, y); Chris@148: } Chris@148: Chris@148: float Chris@148: FFTDataServer::getMaximumMagnitudeAt(size_t x) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::getMaximumMagnitudeAt", false); Chris@183: Chris@217: if (x >= m_width) return 0; Chris@217: Chris@148: size_t col; Chris@148: FFTCache *cache = getCache(x, col); Chris@200: if (!cache) return 0; Chris@148: Chris@148: if (!cache->haveSetColumnAt(col)) { Chris@148: fillColumn(x); Chris@148: } Chris@148: return cache->getMaximumMagnitudeAt(col); Chris@148: } Chris@148: Chris@148: float Chris@148: FFTDataServer::getPhaseAt(size_t x, size_t y) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::getPhaseAt", false); Chris@183: Chris@217: if (x >= m_width || y >= m_height) return 0; Chris@217: Chris@148: size_t col; Chris@148: FFTCache *cache = getCache(x, col); Chris@200: if (!cache) return 0; Chris@148: Chris@148: if (!cache->haveSetColumnAt(col)) { Chris@148: fillColumn(x); Chris@148: } Chris@148: return cache->getPhaseAt(col, y); Chris@148: } Chris@148: Chris@148: void Chris@148: FFTDataServer::getValuesAt(size_t x, size_t y, float &real, float &imaginary) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::getValuesAt", false); Chris@183: Chris@216: if (x >= m_width || y >= m_height) { Chris@216: real = 0; Chris@216: imaginary = 0; Chris@216: return; Chris@216: } Chris@216: Chris@148: size_t col; Chris@148: FFTCache *cache = getCache(x, col); Chris@216: Chris@216: if (!cache) { Chris@216: real = 0; Chris@216: imaginary = 0; Chris@216: return; Chris@216: } Chris@148: Chris@148: if (!cache->haveSetColumnAt(col)) { Chris@148: #ifdef DEBUG_FFT_SERVER Chris@148: std::cerr << "FFTDataServer::getValuesAt(" << x << ", " << y << "): filling" << std::endl; Chris@148: #endif Chris@148: fillColumn(x); Chris@148: } Chris@148: float magnitude = cache->getMagnitudeAt(col, y); Chris@148: float phase = cache->getPhaseAt(col, y); Chris@148: real = magnitude * cosf(phase); Chris@148: imaginary = magnitude * sinf(phase); Chris@148: } Chris@148: Chris@148: bool Chris@148: FFTDataServer::isColumnReady(size_t x) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::isColumnReady", false); Chris@183: Chris@217: if (x >= m_width) return true; Chris@217: Chris@148: if (!haveCache(x)) { Chris@148: if (m_lastUsedCache == -1) { Chris@183: if (m_suspended) { Chris@183: std::cerr << "FFTDataServer::isColumnReady(" << x << "): no cache, calling resume" << std::endl; Chris@183: resume(); Chris@183: } Chris@148: m_fillThread->start(); Chris@148: } Chris@148: return false; Chris@148: } Chris@148: Chris@148: size_t col; Chris@148: FFTCache *cache = getCache(x, col); Chris@200: if (!cache) return true; Chris@148: Chris@148: return cache->haveSetColumnAt(col); Chris@148: } Chris@148: Chris@148: void Chris@148: FFTDataServer::fillColumn(size_t x) Chris@148: { Chris@183: Profiler profiler("FFTDataServer::fillColumn", false); Chris@183: Chris@217: if (!m_fftInput) { Chris@217: std::cerr << "WARNING: FFTDataServer::fillColumn(" << x << "): " Chris@217: << "input has already been completed and discarded?" Chris@217: << std::endl; Chris@217: return; Chris@217: } Chris@217: Chris@217: if (x >= m_width) { Chris@217: std::cerr << "WARNING: FFTDataServer::fillColumn(" << x << "): " Chris@217: << "x > width (" << x << " > " << m_width << ")" Chris@217: << std::endl; Chris@217: return; Chris@217: } Chris@217: Chris@148: size_t col; Chris@148: #ifdef DEBUG_FFT_SERVER_FILL Chris@148: std::cout << "FFTDataServer::fillColumn(" << x << ")" << std::endl; Chris@148: #endif Chris@148: FFTCache *cache = getCache(x, col); Chris@200: if (!cache) return; Chris@148: Chris@148: QMutexLocker locker(&m_writeMutex); Chris@148: Chris@148: if (cache->haveSetColumnAt(col)) return; Chris@148: Chris@148: int startFrame = m_windowIncrement * x; Chris@148: int endFrame = startFrame + m_windowSize; Chris@148: Chris@148: startFrame -= int(m_windowSize - m_windowIncrement) / 2; Chris@148: endFrame -= int(m_windowSize - m_windowIncrement) / 2; Chris@148: size_t pfx = 0; Chris@148: Chris@148: size_t off = (m_fftSize - m_windowSize) / 2; Chris@148: Chris@148: for (size_t i = 0; i < off; ++i) { Chris@148: m_fftInput[i] = 0.0; Chris@148: m_fftInput[m_fftSize - i - 1] = 0.0; Chris@148: } Chris@148: Chris@148: if (startFrame < 0) { Chris@148: pfx = size_t(-startFrame); Chris@148: for (size_t i = 0; i < pfx; ++i) { Chris@148: m_fftInput[off + i] = 0.0; Chris@148: } Chris@148: } Chris@148: Chris@195: #ifdef DEBUG_FFT_SERVER_FILL Chris@193: std::cerr << "FFTDataServer::fillColumn: requesting frames " Chris@193: << startFrame + pfx << " -> " << endFrame << " ( = " Chris@193: << endFrame - (startFrame + pfx) << ") at index " Chris@193: << off + pfx << " in buffer of size " << m_fftSize Chris@193: << " with window size " << m_windowSize Chris@193: << " from channel " << m_channel << std::endl; Chris@195: #endif Chris@193: Chris@148: size_t got = m_model->getValues(m_channel, startFrame + pfx, Chris@148: endFrame, m_fftInput + off + pfx); Chris@148: Chris@148: while (got + pfx < m_windowSize) { Chris@148: m_fftInput[off + got + pfx] = 0.0; Chris@148: ++got; Chris@148: } Chris@148: Chris@148: if (m_channel == -1) { Chris@148: int channels = m_model->getChannelCount(); Chris@148: if (channels > 1) { Chris@148: for (size_t i = 0; i < m_windowSize; ++i) { Chris@148: m_fftInput[off + i] /= channels; Chris@148: } Chris@148: } Chris@148: } Chris@148: Chris@148: m_windower.cut(m_fftInput + off); Chris@148: Chris@148: for (size_t i = 0; i < m_fftSize/2; ++i) { Chris@148: fftsample temp = m_fftInput[i]; Chris@148: m_fftInput[i] = m_fftInput[i + m_fftSize/2]; Chris@148: m_fftInput[i + m_fftSize/2] = temp; Chris@148: } Chris@148: Chris@148: fftwf_execute(m_fftPlan); Chris@148: Chris@148: fftsample factor = 0.0; Chris@148: Chris@203: for (size_t i = 0; i <= m_fftSize/2; ++i) { Chris@148: Chris@148: fftsample mag = sqrtf(m_fftOutput[i][0] * m_fftOutput[i][0] + Chris@148: m_fftOutput[i][1] * m_fftOutput[i][1]); Chris@148: mag /= m_windowSize / 2; Chris@148: Chris@148: if (mag > factor) factor = mag; Chris@148: Chris@148: fftsample phase = atan2f(m_fftOutput[i][1], m_fftOutput[i][0]); Chris@148: phase = princargf(phase); Chris@148: Chris@148: m_workbuffer[i] = mag; Chris@203: m_workbuffer[i + m_fftSize/2+1] = phase; Chris@148: } Chris@148: Chris@148: cache->setColumnAt(col, Chris@148: m_workbuffer, Chris@203: m_workbuffer + m_fftSize/2+1, Chris@148: factor); Chris@154: Chris@183: if (m_suspended) { Chris@183: // std::cerr << "FFTDataServer::fillColumn(" << x << "): calling resume" << std::endl; Chris@183: // resume(); Chris@183: } Chris@148: } Chris@148: Chris@148: size_t Chris@148: FFTDataServer::getFillCompletion() const Chris@148: { Chris@148: if (m_fillThread) return m_fillThread->getCompletion(); Chris@148: else return 100; Chris@148: } Chris@148: Chris@148: size_t Chris@148: FFTDataServer::getFillExtent() const Chris@148: { Chris@148: if (m_fillThread) return m_fillThread->getExtent(); Chris@148: else return m_model->getEndFrame(); Chris@148: } Chris@148: Chris@148: QString Chris@148: FFTDataServer::generateFileBasename() const Chris@148: { Chris@148: return generateFileBasename(m_model, m_channel, m_windower.getType(), Chris@148: m_windowSize, m_windowIncrement, m_fftSize, Chris@148: m_polar); Chris@148: } Chris@148: Chris@148: QString Chris@148: FFTDataServer::generateFileBasename(const DenseTimeValueModel *model, Chris@148: int channel, Chris@148: WindowType windowType, Chris@148: size_t windowSize, Chris@148: size_t windowIncrement, Chris@148: size_t fftSize, Chris@148: bool polar) Chris@148: { Chris@148: char buffer[200]; Chris@148: Chris@148: sprintf(buffer, "%u-%u-%u-%u-%u-%u%s", Chris@148: (unsigned int)XmlExportable::getObjectExportId(model), Chris@148: (unsigned int)(channel + 1), Chris@148: (unsigned int)windowType, Chris@148: (unsigned int)windowSize, Chris@148: (unsigned int)windowIncrement, Chris@148: (unsigned int)fftSize, Chris@148: polar ? "-p" : "-r"); Chris@148: Chris@148: return buffer; Chris@148: } Chris@148: Chris@148: void Chris@148: FFTDataServer::FillThread::run() Chris@148: { Chris@148: m_extent = 0; Chris@148: m_completion = 0; Chris@148: Chris@148: size_t start = m_server.m_model->getStartFrame(); Chris@148: size_t end = m_server.m_model->getEndFrame(); Chris@148: size_t remainingEnd = end; Chris@148: Chris@148: int counter = 0; Chris@148: int updateAt = (end / m_server.m_windowIncrement) / 20; Chris@148: if (updateAt < 100) updateAt = 100; Chris@148: Chris@148: if (m_fillFrom > start) { Chris@148: Chris@148: for (size_t f = m_fillFrom; f < end; f += m_server.m_windowIncrement) { Chris@148: Chris@148: m_server.fillColumn(int((f - start) / m_server.m_windowIncrement)); Chris@148: Chris@148: if (m_server.m_exiting) return; Chris@148: Chris@148: while (m_server.m_suspended) { Chris@148: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "]): suspended, waiting..." << std::endl; Chris@148: #endif Chris@148: m_server.m_writeMutex.lock(); Chris@148: m_server.m_condition.wait(&m_server.m_writeMutex, 10000); Chris@148: m_server.m_writeMutex.unlock(); Chris@159: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "]): waited" << std::endl; Chris@159: #endif Chris@148: if (m_server.m_exiting) return; Chris@148: } Chris@148: Chris@148: if (++counter == updateAt) { Chris@148: m_extent = f; Chris@148: m_completion = size_t(100 * fabsf(float(f - m_fillFrom) / Chris@148: float(end - start))); Chris@148: counter = 0; Chris@148: } Chris@148: } Chris@148: Chris@148: remainingEnd = m_fillFrom; Chris@148: if (remainingEnd > start) --remainingEnd; Chris@148: else remainingEnd = start; Chris@148: } Chris@148: Chris@148: size_t baseCompletion = m_completion; Chris@148: Chris@148: for (size_t f = start; f < remainingEnd; f += m_server.m_windowIncrement) { Chris@148: Chris@148: m_server.fillColumn(int((f - start) / m_server.m_windowIncrement)); Chris@148: Chris@148: if (m_server.m_exiting) return; Chris@148: Chris@148: while (m_server.m_suspended) { Chris@148: #ifdef DEBUG_FFT_SERVER Chris@193: std::cerr << "FFTDataServer(" << this << " [" << (void *)QThread::currentThreadId() << "]): suspended, waiting..." << std::endl; Chris@148: #endif Chris@148: m_server.m_writeMutex.lock(); Chris@148: m_server.m_condition.wait(&m_server.m_writeMutex, 10000); Chris@148: m_server.m_writeMutex.unlock(); Chris@148: if (m_server.m_exiting) return; Chris@148: } Chris@148: Chris@148: if (++counter == updateAt) { Chris@148: m_extent = f; Chris@148: m_completion = baseCompletion + Chris@148: size_t(100 * fabsf(float(f - start) / Chris@148: float(end - start))); Chris@148: counter = 0; Chris@148: } Chris@148: } Chris@148: Chris@148: m_completion = 100; Chris@148: m_extent = end; Chris@148: } Chris@148: