diff --git a/Source/Processors/FileReader/FileReader.cpp b/Source/Processors/FileReader/FileReader.cpp index 0f720d53b..c9d61afc6 100644 --- a/Source/Processors/FileReader/FileReader.cpp +++ b/Source/Processors/FileReader/FileReader.cpp @@ -24,706 +24,630 @@ #include "FileReader.h" #include "FileReaderEditor.h" -#include #include "../../AccessClass.h" #include "../../Audio/AudioComponent.h" #include "../PluginManager/PluginManager.h" #include "BinaryFileSource/BinaryFileSource.h" +#include -#include "../Settings/DeviceInfo.h" #include "../Settings/DataStream.h" +#include "../Settings/DeviceInfo.h" #include "../Events/Event.h" -FileReader::FileReader() : GenericProcessor ("File Reader") - , Thread ("filereader_Async_Reader") - , totalSamplesAcquired (0) - , currentSampleRate (0) - , currentNumChannels (0) - , currentSample (0) - , currentNumTotalSamples (0) - , currentNumScrubbedSamples (0) - , startSample (0) - , stopSample (0) - , loopCount (0) - , bufferCacheWindow (0) - , m_shouldFillBackBuffer (false) - , m_bufferSize (1024) - , m_sysSampleRate (44100) - , playbackActive (true) - , gotNewFile (true) - , loopPlayback (true) -{ - - /* Load any plugin file sources */ - const int numFileSources = AccessClass::getPluginManager()->getNumFileSources(); - - LOGD("Found ", numFileSources, " File Source plugins."); - - for (int i = 0; i < numFileSources; ++i) - { - Plugin::FileSourceInfo info = AccessClass::getPluginManager()->getFileSourceInfo (i); +FileReader::FileReader() + : GenericProcessor("File Reader"), Thread("filereader_Async_Reader"), + totalSamplesAcquired(0), currentSampleRate(0), currentNumChannels(0), + currentSample(0), currentNumTotalSamples(0), currentNumScrubbedSamples(0), + startSample(0), stopSample(0), loopCount(0), bufferCacheWindow(0), + m_shouldFillBackBuffer(false), m_bufferSize(1024), m_sysSampleRate(44100), + playbackActive(true), gotNewFile(true), loopPlayback(true) { - LOGD("Plugin ", i + 1, ": ", info.name, " (", info.extensions, ")"); + /* Load any plugin file sources */ + const int numFileSources = + AccessClass::getPluginManager()->getNumFileSources(); - StringArray extensions; - extensions.addTokens (info.extensions, ";", "\""); + LOGD("Found ", numFileSources, " File Source plugins."); - const int numExtensions = extensions.size(); - - for (int j = 0; j < numExtensions; ++j) - { - supportedExtensions.set (extensions[j].toLowerCase(), i + 1); - } - } + for (int i = 0; i < numFileSources; ++i) { + Plugin::FileSourceInfo info = + AccessClass::getPluginManager()->getFileSourceInfo(i); - /* Load built-in file sources */ - const int numBuiltInFileSources = getNumBuiltInFileSources(); - for (int i = 0; i < numBuiltInFileSources; ++i) - { - StringArray extensions; - extensions.addTokens(getBuiltInFileSourceExtensions(i), ";", "\""); - - const int numExtensions = extensions.size(); - for (int j = 0; j < numExtensions; ++j) - { - supportedExtensions.set(extensions[j].toLowerCase(), i + numFileSources + 1); - } - } - - /* Create a File Reader device */ - DeviceInfo::Settings settings { - "File Reader", - "description", - "identifier", - "00000x003", - "Open Ephys" - }; - devices.add(new DeviceInfo(settings)); + LOGD("Plugin ", i + 1, ": ", info.name, " (", info.extensions, ")"); - isEnabled = false; + StringArray extensions; + extensions.addTokens(info.extensions, ";", "\""); + + const int numExtensions = extensions.size(); + + for (int j = 0; j < numExtensions; ++j) { + supportedExtensions.set(extensions[j].toLowerCase(), i + 1); + } + } + + /* Load built-in file sources */ + const int numBuiltInFileSources = getNumBuiltInFileSources(); + for (int i = 0; i < numBuiltInFileSources; ++i) { + StringArray extensions; + extensions.addTokens(getBuiltInFileSourceExtensions(i), ";", "\""); + + const int numExtensions = extensions.size(); + for (int j = 0; j < numExtensions; ++j) { + supportedExtensions.set(extensions[j].toLowerCase(), + i + numFileSources + 1); + } + } + /* Create a File Reader device */ + DeviceInfo::Settings settings{"File Reader", "description", "identifier", + "00000x003", "Open Ephys"}; + devices.add(new DeviceInfo(settings)); + + isEnabled = false; } -FileReader::~FileReader() -{ - signalThreadShouldExit(); - notify(); +FileReader::~FileReader() { + signalThreadShouldExit(); + notify(); } -AudioProcessorEditor* FileReader::createEditor() -{ - editor = std::make_unique(this); +AudioProcessorEditor *FileReader::createEditor() { + editor = std::make_unique(this); - return editor.get(); + return editor.get(); } -void FileReader::initialize(bool signalChainIsLoading) -{ +void FileReader::initialize(bool signalChainIsLoading) { - LOGD("INITIALIZING FILE READER"); + LOGD("INITIALIZING FILE READER"); - if (signalChainIsLoading) - return; + if (signalChainIsLoading) + return; - if (isEnabled) - return; + if (isEnabled) + return; - LOGD("SETTING FILE"); + LOGD("SETTING FILE"); - File executable = File::getSpecialLocation(File::currentApplicationFile); + File executable = File::getSpecialLocation(File::currentApplicationFile); #ifdef __APPLE__ - File defaultFile = executable.getChildFile("Contents/Resources/resources").getChildFile("structure.oebin"); + File defaultFile = executable.getChildFile("Contents/Resources/resources") + .getChildFile("structure.oebin"); #else - File defaultFile = executable.getParentDirectory().getChildFile("resources").getChildFile("structure.oebin"); + File defaultFile = executable.getParentDirectory() + .getChildFile("resources") + .getChildFile("structure.oebin"); #endif - if (defaultFile.exists()) - { - FileReaderEditor* ed = (FileReaderEditor*)editor.get(); - ed->setFile("default", false); - } + if (defaultFile.exists()) { + FileReaderEditor *ed = (FileReaderEditor *)editor.get(); + ed->setFile("default", false); + } } -void FileReader::togglePlayback() -{ - playbackActive = !playbackActive; -} +void FileReader::togglePlayback() { playbackActive = !playbackActive; } -bool FileReader::playbackIsActive() -{ - return playbackActive; -} +bool FileReader::playbackIsActive() { return playbackActive; } -int64 FileReader::getCurrentNumTotalSamples() -{ - return currentNumTotalSamples; -} +int64 FileReader::getCurrentNumTotalSamples() { return currentNumTotalSamples; } -float FileReader::getCurrentSampleRate() const -{ - return input->getActiveSampleRate(); +float FileReader::getCurrentSampleRate() const { + return input->getActiveSampleRate(); } -float FileReader::getDefaultSampleRate() const -{ - if (input) - return currentSampleRate; - else - return 44100.0; +float FileReader::getDefaultSampleRate() const { + if (input) + return currentSampleRate; + else + return 44100.0; } -bool FileReader::startAcquisition() -{ +bool FileReader::startAcquisition() { - if (!isEnabled) - return false; + if (!isEnabled) + return false; - static_cast (getEditor())->startTimer(100); + static_cast(getEditor())->startTimer(100); - /* Start asynchronous file reading thread */ - startThread(); + /* Start asynchronous file reading thread */ + startThread(); - return true; + return true; } -bool FileReader::stopAcquisition() -{ +bool FileReader::stopAcquisition() { - stopThread(500); - static_cast (getEditor())->stopTimer(); - return true; + stopThread(500); + static_cast(getEditor())->stopTimer(); + return true; } -bool FileReader::isFileSupported (const String& fileName) const -{ - const File file (fileName); - String ext = file.getFileExtension().toLowerCase().substring (1); +bool FileReader::isFileSupported(const String &fileName) const { + const File file(fileName); + String ext = file.getFileExtension().toLowerCase().substring(1); - return supportedExtensions[ext] - 1 >= 0; + return supportedExtensions[ext] - 1 >= 0; } -bool FileReader::setFile (String fullpath) -{ - File file (fullpath); +bool FileReader::setFile(String fullpath) { + File file(fullpath); - String ext = file.getFileExtension().toLowerCase().substring (1); - const int index = supportedExtensions[ext] - 1; - const bool isExtensionSupported = index >= 0; - - if (isExtensionSupported) - { - const int index = supportedExtensions[ext] -1 ; - const int numPluginFileSources = AccessClass::getPluginManager()->getNumFileSources(); - - if (index < numPluginFileSources) - { - Plugin::FileSourceInfo sourceInfo = AccessClass::getPluginManager()->getFileSourceInfo(index); - input = sourceInfo.creator(); - LOGD("Found input."); - } - else - { - input = createBuiltInFileSource(index - numPluginFileSources); - LOGD("Found input."); - } - if (!input) - { - LOGE("Error creating file source for extension ", ext); - return false; - } + String ext = file.getFileExtension().toLowerCase().substring(1); + const int index = supportedExtensions[ext] - 1; + const bool isExtensionSupported = index >= 0; + if (isExtensionSupported) { + const int index = supportedExtensions[ext] - 1; + const int numPluginFileSources = + AccessClass::getPluginManager()->getNumFileSources(); + + if (index < numPluginFileSources) { + Plugin::FileSourceInfo sourceInfo = + AccessClass::getPluginManager()->getFileSourceInfo(index); + input = sourceInfo.creator(); + LOGD("Found input."); + } else { + input = createBuiltInFileSource(index - numPluginFileSources); + LOGD("Found input."); } - else - { - CoreServices::sendStatusMessage ("File type not supported"); - return false; + if (!input) { + LOGE("Error creating file source for extension ", ext); + return false; } - if (! input->openFile (file)) - { - input = nullptr; - CoreServices::sendStatusMessage ("Invalid file"); + } else { + CoreServices::sendStatusMessage("File type not supported"); + return false; + } - return false; - } + if (!input->openFile(file)) { + input = nullptr; + CoreServices::sendStatusMessage("Invalid file"); - const bool isEmptyFile = input->getNumRecords() <= 0; - if (isEmptyFile) - { - input = nullptr; - CoreServices::sendStatusMessage ("Empty file. Ignoring open operation"); + return false; + } - return false; - } + const bool isEmptyFile = input->getNumRecords() <= 0; + if (isEmptyFile) { + input = nullptr; + CoreServices::sendStatusMessage("Empty file. Ignoring open operation"); + + return false; + } + + static_cast(getEditor())->populateRecordings(input); + setActiveRecording(0); - static_cast (getEditor())->populateRecordings (input); - setActiveRecording (0); - - gotNewFile = true; + gotNewFile = true; - return true; + return true; } -void FileReader::setActiveRecording (int index) -{ - if (!input) { return; } +void FileReader::setActiveRecording(int index) { + if (!input) { + return; + } - input->setActiveRecord (index); + input->setActiveRecord(index); - currentNumChannels = input->getActiveNumChannels(); - currentNumTotalSamples = input->getActiveNumSamples(); - currentSampleRate = input->getActiveSampleRate(); + currentNumChannels = input->getActiveNumChannels(); + currentNumTotalSamples = input->getActiveNumSamples(); + currentSampleRate = input->getActiveSampleRate(); - currentSample = 0; - startSample = 0; - stopSample = currentNumTotalSamples; - bufferCacheWindow = 0; - loopCount = 0; + currentSample = 0; + startSample = 0; + stopSample = currentNumTotalSamples; + bufferCacheWindow = 0; + loopCount = 0; - channelInfo.clear(); + channelInfo.clear(); - for (int i = 0; i < currentNumChannels; ++i) - { - channelInfo.add (input->getChannelInfo (index, i)); - } + for (int i = 0; i < currentNumChannels; ++i) { + channelInfo.add(input->getChannelInfo(index, i)); + } - static_cast (getEditor())->setTotalTime (samplesToMilliseconds (currentNumTotalSamples)); - input->seekTo(startSample); - - gotNewFile = true; + static_cast(getEditor()) + ->setTotalTime(samplesToMilliseconds(currentNumTotalSamples)); + input->seekTo(startSample); - + gotNewFile = true; } -int64 FileReader::getCurrentSample() -{ - return currentSample; -} +int64 FileReader::getCurrentSample() { return currentSample; } -void FileReader::setPlaybackStart(int64 startSample) -{ - this->startSample = startSample; - this->totalSamplesAcquired = startSample; +void FileReader::setPlaybackStart(int64 startSample) { + this->startSample = startSample; + this->totalSamplesAcquired = startSample; - input->seekTo(startSample); - currentSample = startSample; + input->seekTo(startSample); + currentSample = startSample; - switchBuffer(); + switchBuffer(); - if (CoreServices::getAcquisitionStatus() && !isThreadRunning()) - { - m_shouldFillBackBuffer.set(true); - startThread(); - } - + if (CoreServices::getAcquisitionStatus() && !isThreadRunning()) { + m_shouldFillBackBuffer.set(true); + startThread(); + } } -void FileReader::setPlaybackStop(int64 stopSample) -{ - this->stopSample = stopSample; - currentNumScrubbedSamples = stopSample - startSample; +void FileReader::setPlaybackStop(int64 stopSample) { + this->stopSample = stopSample; + currentNumScrubbedSamples = stopSample - startSample; } -String FileReader::getFile() const -{ - if (input) - return input->getFileName(); - else - return String(); +String FileReader::getFile() const { + if (input) + return input->getFileName(); + else + return String(); } -void FileReader::updateSettings() -{ +void FileReader::updateSettings() { - LOGD("File Reader updating custom settings."); - - if (!input) - { - LOGD("No input, returning."); - isEnabled = false; - return; - } + LOGD("File Reader updating custom settings."); - if (gotNewFile) - { + if (!input) { + LOGD("No input, returning."); + isEnabled = false; + return; + } - LOGD("File Reader got new file."); + if (gotNewFile) { - dataStreams.clear(); - continuousChannels.clear(); - eventChannels.clear(); + LOGD("File Reader got new file."); - String streamName = input->getRecordName(input->getActiveRecord()); + dataStreams.clear(); + continuousChannels.clear(); + eventChannels.clear(); - /* Only use the original stream name (FileReader-100.example_data -> example_data) */ - StringArray tokens; - tokens.addTokens (input->getRecordName(input->getActiveRecord()), "."); - if ( tokens.size() ) - streamName = tokens[tokens.size()-1]; + String streamName = input->getRecordName(input->getActiveRecord()); - DataStream::Settings streamSettings{ + /* Only use the original stream name (FileReader-100.example_data -> + * example_data) */ + StringArray tokens; + tokens.addTokens(input->getRecordName(input->getActiveRecord()), "."); + if (tokens.size()) + streamName = tokens[tokens.size() - 1]; - streamName, - "A description of the File Reader Stream", - "identifier", - getDefaultSampleRate() + DataStream::Settings streamSettings{ - }; + streamName, "A description of the File Reader Stream", "identifier", + getDefaultSampleRate() - LOGD("File Reader adding data stream."); + }; - dataStreams.add(new DataStream(streamSettings)); - dataStreams.getLast()->addProcessor(processorInfo.get()); + LOGD("File Reader adding data stream."); + + dataStreams.add(new DataStream(streamSettings)); + dataStreams.getLast()->addProcessor(processorInfo.get()); + + for (int i = 0; i < currentNumChannels; i++) { + String chan_name = channelInfo[i].name; + if (chan_name.contains("AUX")) { + ContinuousChannel::Settings channelSettings{ + ContinuousChannel::Type::AUX, channelInfo[i].name, "description", + "filereader.stream", + channelInfo[i].bitVolts, // BITVOLTS VALUE + dataStreams.getLast()}; + + continuousChannels.add(new ContinuousChannel(channelSettings)); + continuousChannels.getLast()->addProcessor(processorInfo.get()); + } else { + ContinuousChannel::Settings channelSettings{ + ContinuousChannel::Type::ELECTRODE, + channelInfo[i].name, + "description", + "filereader.stream", + channelInfo[i].bitVolts, // BITVOLTS VALUE + dataStreams.getLast()}; + + continuousChannels.add(new ContinuousChannel(channelSettings)); + continuousChannels.getLast()->addProcessor(processorInfo.get()); + } + } - for (int i = 0; i < currentNumChannels; i++) - { - ContinuousChannel::Settings channelSettings - { - ContinuousChannel::Type::ELECTRODE, - channelInfo[i].name, - "description", - "filereader.stream", - channelInfo[i].bitVolts, // BITVOLTS VALUE - dataStreams.getLast() - }; + EventChannel *events; - continuousChannels.add(new ContinuousChannel(channelSettings)); - continuousChannels.getLast()->addProcessor(processorInfo.get()); - } + EventChannel::Settings eventSettings{ + EventChannel::Type::TTL, "All TTL events", + "All TTL events loaded for the current input data source", + "filereader.events", dataStreams.getLast()}; - EventChannel* events; + // FIXME: Should add an event channel for each event channel detected in the + // current file source + events = new EventChannel(eventSettings); + String id = "sourceevent"; + events->setIdentifier(id); + events->addProcessor(processorInfo.get()); + eventChannels.add(events); - EventChannel::Settings eventSettings{ - EventChannel::Type::TTL, - "All TTL events", - "All TTL events loaded for the current input data source", - "filereader.events", - dataStreams.getLast() - }; + gotNewFile = false; - //FIXME: Should add an event channel for each event channel detected in the current file source - events = new EventChannel(eventSettings); - String id = "sourceevent"; - events->setIdentifier(id); - events->addProcessor(processorInfo.get()); - eventChannels.add(events); + } else { + LOGD("File Reader has no new file...not updating."); + } - gotNewFile = false; + isEnabled = true; - } - else { - LOGD("File Reader has no new file...not updating."); - } + /* Set the timestamp to start of playback and reset loop counter */ + totalSamplesAcquired = startSample; + loopCount = 0; - isEnabled = true; + /* Setup internal buffer based on audio device settings */ + AudioDeviceManager &adm = AccessClass::getAudioComponent()->deviceManager; + AudioDeviceManager::AudioDeviceSetup ads; + adm.getAudioDeviceSetup(ads); + m_sysSampleRate = ads.sampleRate; + m_bufferSize = ads.bufferSize; + if (m_bufferSize == 0) + m_bufferSize = 1024; + m_samplesPerBuffer.set(m_bufferSize * + (getDefaultSampleRate() / m_sysSampleRate)); - /* Set the timestamp to start of playback and reset loop counter */ - totalSamplesAcquired = startSample; - loopCount = 0; + bufferA.malloc(currentNumChannels * m_bufferSize * BUFFER_WINDOW_CACHE_SIZE); + bufferB.malloc(currentNumChannels * m_bufferSize * BUFFER_WINDOW_CACHE_SIZE); - /* Setup internal buffer based on audio device settings */ - AudioDeviceManager& adm = AccessClass::getAudioComponent()->deviceManager; - AudioDeviceManager::AudioDeviceSetup ads; - adm.getAudioDeviceSetup(ads); - m_sysSampleRate = ads.sampleRate; - m_bufferSize = ads.bufferSize; - if (m_bufferSize == 0) m_bufferSize = 1024; - m_samplesPerBuffer.set(m_bufferSize * (getDefaultSampleRate() / m_sysSampleRate)); + /* Reset stream to start of playback */ + input->seekTo(startSample); + currentSample = startSample; - bufferA.malloc(currentNumChannels * m_bufferSize * BUFFER_WINDOW_CACHE_SIZE); - bufferB.malloc(currentNumChannels * m_bufferSize * BUFFER_WINDOW_CACHE_SIZE); + /* Pre-fills the front buffer with a blocking read */ + readAndFillBufferCache(bufferA); - /* Reset stream to start of playback */ - input->seekTo(startSample); - currentSample = startSample; + readBuffer = &bufferB; + bufferCacheWindow = 0; + m_shouldFillBackBuffer.set(false); +} - /* Pre-fills the front buffer with a blocking read */ - readAndFillBufferCache(bufferA); +int FileReader::getPlaybackStart() { return startSample; } - readBuffer = &bufferB; - bufferCacheWindow = 0; - m_shouldFillBackBuffer.set(false); +int FileReader::getPlaybackStop() { return stopSample; } +Array FileReader::getActiveEventInfo() { + return input->getEventInfo(); } -int FileReader::getPlaybackStart() -{ - return startSample; -} +String FileReader::handleConfigMessage(String msg) { -int FileReader::getPlaybackStop() -{ - return stopSample; -} + const MessageManagerLock mml; -Array FileReader::getActiveEventInfo() -{ - return input->getEventInfo(); -} + StringArray tokens; + tokens.addTokens(msg, "=", "\""); -String FileReader::handleConfigMessage(String msg) -{ + if (tokens.size() != 2) + return "Invalid msg"; - const MessageManagerLock mml; + if (tokens[0] == "file") + static_cast(getEditor())->setFile(tokens[1]); + else if (tokens[0] == "index") + static_cast(getEditor()) + ->setRecording(std::stoi(tokens[1].toStdString())); + else if (tokens[0] == "start") + static_cast(getEditor()) + ->setPlaybackStartTime(std::stoi(tokens[1].toStdString())); + else if (tokens[0] == "stop") + static_cast(getEditor()) + ->setPlaybackStartTime(std::stoi(tokens[1].toStdString())); + else + LOGD("Invalid key"); - StringArray tokens; - tokens.addTokens (msg, "=", "\""); - - if (tokens.size() != 2) return "Invalid msg"; - - if (tokens[0] == "file") - static_cast (getEditor())->setFile(tokens[1]); - else if (tokens[0] == "index") - static_cast (getEditor())->setRecording(std::stoi(tokens[1].toStdString())); - else if (tokens[0] == "start") - static_cast (getEditor())->setPlaybackStartTime(std::stoi(tokens[1].toStdString())); - else if (tokens[0] == "stop") - static_cast (getEditor())->setPlaybackStartTime(std::stoi(tokens[1].toStdString())); - else - LOGD("Invalid key"); - - return "File Reader received config: " + msg; + return "File Reader received config: " + msg; } -void FileReader::process(AudioBuffer& buffer) -{ +void FileReader::process(AudioBuffer &buffer) { - bool switchNeeded = false; + bool switchNeeded = false; - int samplesNeededPerBuffer = int (float (buffer.getNumSamples()) * (getDefaultSampleRate() / m_sysSampleRate)); + int samplesNeededPerBuffer = int(float(buffer.getNumSamples()) * + (getDefaultSampleRate() / m_sysSampleRate)); - if (!playbackActive && totalSamplesAcquired + samplesNeededPerBuffer > stopSample) - { - samplesNeededPerBuffer = stopSample - totalSamplesAcquired; - switchNeeded = true; - } - else - m_samplesPerBuffer.set(samplesNeededPerBuffer); - // FIXME: needs to account for the fact that the ratio might not be an exact - // integer value - - // if cache window id == 0, we need to read and cache BUFFER_WINDOW_CACHE_SIZE more buffer windows - if (bufferCacheWindow == 0) - { - switchBuffer(); - } + if (!playbackActive && + totalSamplesAcquired + samplesNeededPerBuffer > stopSample) { + samplesNeededPerBuffer = stopSample - totalSamplesAcquired; + switchNeeded = true; + } else + m_samplesPerBuffer.set(samplesNeededPerBuffer); + // FIXME: needs to account for the fact that the ratio might not be an exact + // integer value - //std::cout << "Reading " << samplesNeededPerBuffer << " samples. " << std::endl; - - for (int i = 0; i < currentNumChannels; ++i) - { - // offset readBuffer index by current cache window count * buffer window size * num channels - input->processChannelData (*readBuffer + (samplesNeededPerBuffer * currentNumChannels * bufferCacheWindow), - buffer.getWritePointer (i, 0), - i, - samplesNeededPerBuffer); - } + // if cache window id == 0, we need to read and cache BUFFER_WINDOW_CACHE_SIZE + // more buffer windows + if (bufferCacheWindow == 0) { + switchBuffer(); + } - setTimestampAndSamples(totalSamplesAcquired, -1.0, samplesNeededPerBuffer, dataStreams[0]->getStreamId()); //TODO: Look at this + // std::cout << "Reading " << samplesNeededPerBuffer << " samples. " << + // std::endl; - int64 start = totalSamplesAcquired; + for (int i = 0; i < currentNumChannels; ++i) { + // offset readBuffer index by current cache window count * buffer window + // size * num channels + input->processChannelData( + *readBuffer + + (samplesNeededPerBuffer * currentNumChannels * bufferCacheWindow), + buffer.getWritePointer(i, 0), i, samplesNeededPerBuffer); + } - totalSamplesAcquired += samplesNeededPerBuffer; + setTimestampAndSamples(totalSamplesAcquired, -1.0, samplesNeededPerBuffer, + dataStreams[0]->getStreamId()); // TODO: Look at this - //LOGD("Total samples acquired: ", totalSamplesAcquired); + int64 start = totalSamplesAcquired; - int64 stop = totalSamplesAcquired; + totalSamplesAcquired += samplesNeededPerBuffer; - addEventsInRange(start, stop); + // LOGD("Total samples acquired: ", totalSamplesAcquired); - bufferCacheWindow += 1; - bufferCacheWindow %= BUFFER_WINDOW_CACHE_SIZE; + int64 stop = totalSamplesAcquired; - if (switchNeeded) - { - bufferCacheWindow = 0; - this->stopThread(100); - } + addEventsInRange(start, stop); -} + bufferCacheWindow += 1; + bufferCacheWindow %= BUFFER_WINDOW_CACHE_SIZE; -void FileReader::addEventsInRange(int64 start, int64 stop) -{ - - EventInfo events; - input->processEventData(events, start, stop); - - for (int i = 0; i < events.channels.size(); i++) - { - - juce::int64 absoluteCurrentTimestamp = events.timestamps[i] + loopCount * (stopSample - startSample); - if (events.text.size() && !events.text[i].isEmpty()) - { - String msg = events.text[i]; - LOGD("Broadcasting message: ", msg, " at timestamp: ", absoluteCurrentTimestamp, " channel: ", events.channels[i]); - broadcastMessage(msg); - } - else - { - uint8 ttlBit = events.channels[i]; - bool state = events.channelStates[i] > 0; - TTLEventPtr event = TTLEvent::createTTLEvent(eventChannels[0], events.timestamps[i], ttlBit, state); - addEvent(event, absoluteCurrentTimestamp); - } + if (switchNeeded) { + bufferCacheWindow = 0; + this->stopThread(100); + } +} + +void FileReader::addEventsInRange(int64 start, int64 stop) { + + EventInfo events; + input->processEventData(events, start, stop); + + for (int i = 0; i < events.channels.size(); i++) { + + juce::int64 absoluteCurrentTimestamp = + events.timestamps[i] + loopCount * (stopSample - startSample); + if (events.text.size() && !events.text[i].isEmpty()) { + String msg = events.text[i]; + LOGD("Broadcasting message: ", msg, + " at timestamp: ", absoluteCurrentTimestamp, + " channel: ", events.channels[i]); + broadcastMessage(msg); + } else { + uint8 ttlBit = events.channels[i]; + bool state = events.channelStates[i] > 0; + TTLEventPtr event = TTLEvent::createTTLEvent( + eventChannels[0], events.timestamps[i], ttlBit, state); + addEvent(event, absoluteCurrentTimestamp); } + } } -void FileReader::setParameter (int parameterIndex, float newValue) -{ - switch (parameterIndex) - { - //Change selected recording - case 0: - setActiveRecording (newValue); - break; - - //set startTime - case 1: - startSample = millisecondsToSamples (newValue); - currentSample = startSample; - - static_cast (getEditor())->setCurrentTime (samplesToMilliseconds (currentSample)); - break; - - //set stop time - case 2: - stopSample = millisecondsToSamples(newValue); - currentSample = startSample; - - static_cast (getEditor())->setCurrentTime (samplesToMilliseconds (currentSample)); - break; - } -} +void FileReader::setParameter(int parameterIndex, float newValue) { + switch (parameterIndex) { + // Change selected recording + case 0: + setActiveRecording(newValue); + break; + + // set startTime + case 1: + startSample = millisecondsToSamples(newValue); + currentSample = startSample; + + static_cast(getEditor()) + ->setCurrentTime(samplesToMilliseconds(currentSample)); + break; + + // set stop time + case 2: + stopSample = millisecondsToSamples(newValue); + currentSample = startSample; -unsigned int FileReader::samplesToMilliseconds (int64 samples) const -{ - return (unsigned int) (1000.f * float (samples) / currentSampleRate); + static_cast(getEditor()) + ->setCurrentTime(samplesToMilliseconds(currentSample)); + break; + } } -int64 FileReader::millisecondsToSamples (unsigned int ms) const -{ - return (int64) (currentSampleRate * float (ms) / 1000.f); +unsigned int FileReader::samplesToMilliseconds(int64 samples) const { + return (unsigned int)(1000.f * float(samples) / currentSampleRate); } -void FileReader::switchBuffer() -{ - if (readBuffer == &bufferA) - readBuffer = &bufferB; - else - readBuffer = &bufferA; - - m_shouldFillBackBuffer.set(true); - notify(); +int64 FileReader::millisecondsToSamples(unsigned int ms) const { + return (int64)(currentSampleRate * float(ms) / 1000.f); } -HeapBlock* FileReader::getFrontBuffer() -{ - return readBuffer; +void FileReader::switchBuffer() { + if (readBuffer == &bufferA) + readBuffer = &bufferB; + else + readBuffer = &bufferA; + + m_shouldFillBackBuffer.set(true); + notify(); } -HeapBlock* FileReader::getBackBuffer() -{ - if (readBuffer == &bufferA) return &bufferB; - - return &bufferA; +HeapBlock *FileReader::getFrontBuffer() { return readBuffer; } + +HeapBlock *FileReader::getBackBuffer() { + if (readBuffer == &bufferA) + return &bufferB; + + return &bufferA; } -void FileReader::run() -{ - while (!threadShouldExit()) - { - if (m_shouldFillBackBuffer.compareAndSetBool(false, true)) - { - readAndFillBufferCache(*getBackBuffer()); - } - - wait(30); +void FileReader::run() { + while (!threadShouldExit()) { + if (m_shouldFillBackBuffer.compareAndSetBool(false, true)) { + readAndFillBufferCache(*getBackBuffer()); } + + wait(30); + } } -void FileReader::readAndFillBufferCache(HeapBlock &cacheBuffer) -{ +void FileReader::readAndFillBufferCache(HeapBlock &cacheBuffer) { + + const int samplesNeededPerBuffer = m_samplesPerBuffer.get(); + const int samplesNeeded = samplesNeededPerBuffer * BUFFER_WINDOW_CACHE_SIZE; + + int samplesRead = 0; + + // should only loop if reached end of file and resuming from start + while (samplesRead < samplesNeeded) { + + if (samplesRead < 0) + return; + + int samplesToRead = samplesNeeded - samplesRead; - const int samplesNeededPerBuffer = m_samplesPerBuffer.get(); - const int samplesNeeded = samplesNeededPerBuffer * BUFFER_WINDOW_CACHE_SIZE; - - int samplesRead = 0; - - // should only loop if reached end of file and resuming from start - while (samplesRead < samplesNeeded) + // if reached end of file stream + if ((currentSample + samplesToRead) > stopSample) { + samplesToRead = stopSample - currentSample; + if (samplesToRead > 0) + input->readData(cacheBuffer + samplesRead * currentNumChannels, + samplesToRead); + + if (startSample != 0) { + startSample = 0; + } + + // reset stream to beginning + input->seekTo(startSample); + currentSample = startSample; + + } else // else read the block needed { - - if (samplesRead < 0) - return; - - int samplesToRead = samplesNeeded - samplesRead; - - // if reached end of file stream - if ( (currentSample + samplesToRead) > stopSample) - { - samplesToRead = stopSample - currentSample; - if (samplesToRead > 0) - input->readData (cacheBuffer + samplesRead * currentNumChannels, samplesToRead); - - if (startSample != 0) - { - startSample = 0; - } - - // reset stream to beginning - input->seekTo (startSample); - currentSample = startSample; - - } - else // else read the block needed - { - input->readData (cacheBuffer + samplesRead * currentNumChannels, samplesToRead); - - currentSample += samplesToRead; - } - - samplesRead += samplesToRead; + input->readData(cacheBuffer + samplesRead * currentNumChannels, + samplesToRead); + currentSample += samplesToRead; } + + samplesRead += samplesToRead; + } } -StringArray FileReader::getSupportedExtensions() const -{ - StringArray extensions; - HashMap::Iterator i(supportedExtensions); - while (i.next()) - { - extensions.add(i.getKey()); - } - return extensions; +StringArray FileReader::getSupportedExtensions() const { + StringArray extensions; + HashMap::Iterator i(supportedExtensions); + while (i.next()) { + extensions.add(i.getKey()); + } + return extensions; } -//Built-In +// Built-In -int FileReader::getNumBuiltInFileSources() const -{ - return 1; -} +int FileReader::getNumBuiltInFileSources() const { return 1; } -String FileReader::getBuiltInFileSourceExtensions(int index) const -{ - switch (index) - { - case 0: //Binary - return "oebin"; - default: - return ""; - } +String FileReader::getBuiltInFileSourceExtensions(int index) const { + switch (index) { + case 0: // Binary + return "oebin"; + default: + return ""; + } } -FileSource* FileReader::createBuiltInFileSource(int index) const -{ - switch (index) - { - case 0: - return new BinarySource::BinaryFileSource(); - default: - return nullptr; - } +FileSource *FileReader::createBuiltInFileSource(int index) const { + switch (index) { + case 0: + return new BinarySource::BinaryFileSource(); + default: + return nullptr; + } }