Exemplo n.º 1
0
void JuceBoxAudioProcessor::loadSound()
{
	Logger::writeToLog("- loadSound().");
	synth.clearSounds();

	if (!sampleFile.existsAsFile()) {
		Logger::writeToLog("\"" + sampleFile.getFullPathName() + "\" doesn't exist.");
		return;
		}
	AudioFormatReader* reader = formatManager.createReaderFor(sampleFile);
	if (reader == NULL) {
		Logger::writeToLog("No reader for \"" + sampleFile.getFullPathName() + "\".");
		return;
		}
	Logger::writeToLog("Format: " + reader->getFormatName());
	Logger::writeToLog("Sample rate: " + String(reader->sampleRate));
	Logger::writeToLog("length: " + String(reader->lengthInSamples));
	Logger::writeToLog("numChannels: " + String(reader->numChannels));
	BigInteger notes;
	notes.setRange(0, 127, true);
	SamplerSound* sound =
		new SamplerSound(
			sampleFile.getFileNameWithoutExtension(),
			*reader,
			notes,
			72 /* C5 == middle C above A-440 */,
			0.0, 0.01,
			20.0 /* max time, hopefully 20s is enough for any sound */);
	synth.addSound(sound);
	delete reader;
}
Exemplo n.º 2
0
SampleItem::SampleItem(const String &filename)
{
	this->filename = filename;

	File file(filename);
	if (file.exists())
	{
		shortname = file.getFileNameWithoutExtension();
		FileInputStream *stream = new FileInputStream(file);
		WavAudioFormat format;
		AudioFormatReader *reader = format.createReaderFor(stream, false);
		if (reader)
		{
			formatName = reader->getFormatName();
			sampleRate = (int)reader->sampleRate;
			size = (int)reader->lengthInSamples;
			bits = reader->bitsPerSample;
			delete reader;
		}
		else
		{
			sampleRate = 0;
			size = 0;
			bits = 0;
		}
	}

	playing = false;
}
Exemplo n.º 3
0
//==============================================================================
MainContentComponent::MainContentComponent():readAheadThread("read Ahead thread"){
    // Format manager
    audioFormatManager.registerBasicFormats();
    
    // Device manager
    audioDeviceManager = new AudioDeviceManager();
    audioDeviceManager->initialise(0, 2, 0, true);
    readAheadThread.startThread(3);
    
    // Read file
    File sfile (File::getSpecialLocation (File::userDocumentsDirectory).getChildFile("lyd3_000_ortf_48k.wav"));
    AudioFormatReader* audioFormatReader = audioFormatManager.createReaderFor(sfile);
    ScopedPointer<AudioSampleBuffer> audioBuffer = new AudioSampleBuffer(1, audioFormatReader->lengthInSamples); //audioBuffer para leer archivo wav
    audioFormatReader->read(audioBuffer, 0, audioFormatReader->lengthInSamples, 0, true, false);
    
    // Cambiar Fs del AudioDevice segun sea la del archivo wav
    juce::AudioDeviceManager::AudioDeviceSetup newAudioSetup;
    audioDeviceManager->getAudioDeviceSetup(newAudioSetup);
    newAudioSetup.sampleRate=audioFormatReader->sampleRate;
    audioDeviceManager->setAudioDeviceSetup(newAudioSetup, true);
    
    //Playback preparation
    audioFormatReaderSource = new AudioFormatReaderSource(audioFormatReader, true);
    audioTransportSource.setSource(audioFormatReaderSource, 32768, &readAheadThread, 0, 2);  //el 0 es para que no haga resamplig....
    audioSourcePlayer.setSource(&audioTransportSource);                                      //..depende de haber cambiado Fs en AudioDevice
    audioDeviceManager->addAudioCallback(&audioSourcePlayer);
    //Playback start
    audioTransportSource.start();
    
    Logger::writeToLog ("Total length: --> " + String(audioFormatReader->lengthInSamples));
    
    int bandas=10;
    for (int i=0;i<bandas;i++) {
        Buffer* buffer = new Buffer(audioFormatReader->lengthInSamples);
        filteredAudioArray.add(buffer);         //filteredAudioArray es un OwnedArray y debe ser declarado como una variable de la clase para que
    }                                           //le pertenezca y sea la clase la que lo borre.
    
    filterBank = new FilterBank(bandas);        //La clase filterBank necesita un WritePointer a un canal de un AudioSampleBuffer donde esta la entrada...
    filterBank->setCoeficientes();              //y un puntero a un OwnedArray<Buffer> del tamaño del filterBank donde quedan diferentes salidas filtradas
    filterBank->processSamples(audioBuffer->getWritePointer(0),&filteredAudioArray, audioFormatReader->lengthInSamples);
    
    const int N = 1;                                                        //downsamplig rate
    const int M = 1;                                                        //length fraction
    bufferWaveform = new Buffer(audioFormatReader->lengthInSamples/(M*N));  //buffer para downSamplig con el que se pinta waveForm
    audioDownSamplig(audioBuffer,bufferWaveform,N,M);
    
    addAndMakeVisible(tabsComponent = new TabbedComponent(TabbedButtonBar::TabsAtTop));
    tabsComponent->addTab("Respuesta al Impulso", Colour(0xff2f2f2f), new AudioWaveForm(bufferWaveform,true), true);
    for(int i=0;i<bandas;i++){
        tabsComponent->addTab("Filtered IR", Colour(0xff2f2f2f), new AudioWaveForm(filteredAudioArray.getUnchecked(i),true), true);
    }

    setSize (1200, 400);
}
void CtrlrPanelResourceEditor::showResourceInfo(const int resourceIndex)
{
	CtrlrPanelResource *res = resources[resourceIndex];
	if (res == nullptr)
		return;

	String message;
	message << "Load time: " + res->getLoadedTime().toString(true, true, true, true) + "\n";
	message << "Data file: " + res->getFile().getFullPathName() + "\n";
	message << "Source file: " + res->getSourceFile().getFullPathName() + "\n";
	message << "Source hash: " + STR(res->getHashCode()) + "\n";
	AudioFormatReader *afr = res->asAudioFormat();
	if (afr)
	{
		message << "Type: Audio\n";
		message << "Format name: " << afr->getFormatName() << "\n";
		message << "Sample rate: " << afr->sampleRate << "\n";
		message << "Bits per sample: " << ((int)afr->bitsPerSample) << "\n";
		message << "Length in samples: " << afr->lengthInSamples << "\n";
		message << "Number of channels: " << ((int)afr->numChannels) << "\n";
		message << "Metadata:\n";
		message << "\t" << afr->metadataValues.getDescription();
	}


	if (!res->asImage().isNull())
	{
		Image i = res->asImage();
		message << "Type: Image\n";
		message << "Width: " + STR(i.getWidth()) + "\n";
		message << "Height: " + STR(i.getHeight()) + "\n";
		message << "Has alpha: " + STR(i.hasAlphaChannel()) + "\n";
	}

	DialogWindow::LaunchOptions lo;
	Label *l = new Label ("", message);
	l->setSize (400, 150);
	l->setJustificationType (Justification::centred);
	l->setFont (Font(12.0f));
	lo.content.set(l, true);
	lo.componentToCentreAround		= this;
	lo.dialogBackgroundColour		= Colours::whitesmoke;
	lo.dialogTitle					= "Resource information";
	lo.resizable					= true;
	lo.useBottomRightCornerResizer	= false;
	lo.useNativeTitleBar			= true;
	lo.launchAsync();
}
Exemplo n.º 5
0
SamplerSound::SamplerSound (const String& name_,
                            AudioFormatReader& source,
                            const BigInteger& midiNotes_,
                            const int midiNoteForNormalPitch,
                            const double attackTimeSecs,
                            const double releaseTimeSecs,
                            const double maxSampleLengthSeconds)
    : name (name_),
      midiNotes (midiNotes_),
      midiRootNote (midiNoteForNormalPitch)
{
    sourceSampleRate = source.sampleRate;

    if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
    {
        length = 0;
        attackSamples = 0;
        releaseSamples = 0;
    }
    else
    {
        length = jmin ((int) source.lengthInSamples,
                       (int) (maxSampleLengthSeconds * sourceSampleRate));

        data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);

        source.read (data, 0, length + 4, 0, true, true);

        attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
        releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
    }
}
Exemplo n.º 6
0
SamplerSound::SamplerSound (const String& soundName,
                            AudioFormatReader& source,
                            const BigInteger& notes,
                            int midiNoteForNormalPitch,
                            double attackTimeSecs,
                            double releaseTimeSecs,
                            double maxSampleLengthSeconds)
    : name (soundName),
      sourceSampleRate (source.sampleRate),
      midiNotes (notes),
      midiRootNote (midiNoteForNormalPitch)
{
    if (sourceSampleRate > 0 && source.lengthInSamples > 0)
    {
        length = jmin ((int) source.lengthInSamples,
                       (int) (maxSampleLengthSeconds * sourceSampleRate));

        data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);

        source.read (data, 0, length + 4, 0, true, true);

        attackSamples  = roundToInt (attackTimeSecs  * sourceSampleRate);
        releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
    }
}
Exemplo n.º 7
0
static void readChannels (AudioFormatReader& reader, int** chans, AudioBuffer<float>* buffer,
                          int startSample, int numSamples, int64 readerStartSample, int numTargetChannels)
{
    for (int j = 0; j < numTargetChannels; ++j)
        chans[j] = reinterpret_cast<int*> (buffer->getWritePointer (j, startSample));

    chans[numTargetChannels] = nullptr;
    reader.read (chans, numTargetChannels, readerStartSample, numSamples, true);
}
Exemplo n.º 8
0
bool SFZSample::load(AudioFormatManager* formatManager)
{
	AudioFormatReader* reader = formatManager->createReaderFor(file);
	if (reader == NULL)
		return false;
	sampleRate = reader->sampleRate;
	sampleLength = reader->lengthInSamples;
	// Read some extra samples, which will be filled with zeros, so interpolation
	// can be done without having to check for the edge all the time.
	buffer = new AudioSampleBuffer(reader->numChannels, sampleLength + 4);
	reader->read(buffer, 0, sampleLength + 4, 0, true, true);
	StringPairArray* metadata = &reader->metadataValues;
	int numLoops = metadata->getValue("NumSampleLoops", "0").getIntValue();
	if (numLoops > 0) {
		loopStart = metadata->getValue("Loop0Start", "0").getLargeIntValue();
		loopEnd = metadata->getValue("Loop0End", "0").getLargeIntValue();
		}
	delete reader;
	return true;
}
Exemplo n.º 9
0
static void readChannels (AudioFormatReader& reader,
                          int** const chans, AudioSampleBuffer* const buffer,
                          const int startSample, const int numSamples,
                          const int64 readerStartSample, const int numTargetChannels)
{
    for (int j = 0; j < numTargetChannels; ++j)
        chans[j] = reinterpret_cast<int*> (buffer->getSampleData (j, startSample));

    chans[numTargetChannels] = nullptr;
    reader.read (chans, numTargetChannels, readerStartSample, numSamples, true);
}
Exemplo n.º 10
0
void Sample::update(const String& path, WavAudioFormat& wavAudioFormat)
{
	// Don't load a subsequent sample if a new sample is already loaded (but not yet played).
	if (_readyToSwap)
		return;

	// Find audio file.
	String fileName(path);
	fileName = File::addTrailingSeparator(fileName);
	fileName += _name;
	fileName += EXT;
	File file(fileName);

	Time modification = file.getLastModificationTime();
	if (modification <= _lastModification)
		return;

	// Read audio file. We only read the left channel, mono is good enough.
	AudioFormatReader* reader = wavAudioFormat.createReaderFor(file.createInputStream(), true);
	if (reader == nullptr)
		return;
	_lastModification = modification;

	int64 start = reader->searchForLevel(0, reader->lengthInSamples, SAMPLE_START_THRESHOLD, 1.0, 0);
	if (start == -1)
		start = 0;
	int count = (int)(reader->lengthInSamples - start);

	_processor->writeTrace(String() << "Loading " << _name << " from disk (skip=" << start << ")");

	int newIndex = !_bufferIndex;
	AudioSampleBuffer* buffer = &(_buffers[newIndex]);
	buffer->setSize(1, count);

	reader->read(buffer, 0, count, start, true, false);

	delete reader;

	// Done.
	_readyToSwap = true;
}
Exemplo n.º 11
0
//==============================================================================
MemoryMappedAudioFormatReader::MemoryMappedAudioFormatReader (const File& f, const AudioFormatReader& reader,
                                                              int64 start, int64 length, int frameSize)
    : AudioFormatReader (nullptr, reader.getFormatName()), file (f),
      dataChunkStart (start), dataLength (length), bytesPerFrame (frameSize)
{
    sampleRate      = reader.sampleRate;
    bitsPerSample   = reader.bitsPerSample;
    lengthInSamples = reader.lengthInSamples;
    numChannels     = reader.numChannels;
    metadataValues  = reader.metadataValues;
    usesFloatingPointData = reader.usesFloatingPointData;
}
Exemplo n.º 12
0
MelodicSamplerSound::MelodicSamplerSound (String& filePath,
                            const int midiNote,
                            const int beginSamples,
                            const int numSamples) : note(midiNote) {
    File *file = new File(filePath);
    FileInputSource *source = new FileInputSource(*file, false);
    InputStream *stream = source->createInputStream();
    AudioFormatReader *reader = mp3Format->createReaderFor(stream, true);
    sourceSampleRate = reader->sampleRate;

    attackSamples = 0, releaseSamples = 0;
    // attackSamples = roundToInt (attackTimeSec * sourceSampleRate);
    // releaseSamples = roundToInt (releaseTimeSec * sourceSampleRate);
    if (sourceSampleRate <= 0 || reader->lengthInSamples <= 0) {
        length = 0;
    } else {
        int begin = jmin((int) reader->lengthInSamples - 1, beginSamples);
        length = jmin ((int) reader->lengthInSamples - begin, numSamples);
        data = new AudioSampleBuffer (jmin (2, (int) reader->numChannels), length + 4);
        reader->read (data, 0, length + 4, begin, true, true);
    }
}
Exemplo n.º 13
0
bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
                                              int64 startSample,
                                              int64 numSamplesToRead)
{
    const int bufferSize = 16384;
    AudioSampleBuffer tempBuffer ((int) numChannels, bufferSize);

    int* buffers [128] = { 0 };

    for (int i = tempBuffer.getNumChannels(); --i >= 0;)
        buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));

    if (numSamplesToRead < 0)
        numSamplesToRead = reader.lengthInSamples;

    while (numSamplesToRead > 0)
    {
        const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);

        if (! reader.read (buffers, (int) numChannels, startSample, numToDo, false))
            return false;

        if (reader.usesFloatingPointData != isFloatingPoint())
        {
            int** bufferChan = buffers;

            while (*bufferChan != nullptr)
            {
                void* const b = *bufferChan++;

                if (isFloatingPoint())
                    FloatVectorOperations::convertFixedToFloat ((float*) b, (int*) b, 1.0f / 0x7fffffff, numToDo);
                else
                    convertFloatsToInts ((int*) b, (float*) b, numToDo);
            }
        }

        if (! write (const_cast <const int**> (buffers), numToDo))
            return false;

        numSamplesToRead -= numToDo;
        startSample += numToDo;
    }

    return true;
}
Exemplo n.º 14
0
bool Mcfx_convolverAudioProcessor::loadIr(AudioSampleBuffer* IRBuffer, const File& audioFile, int channel, double &samplerate, float gain, int offset, int length)
{
    if (!audioFile.existsAsFile())
    {
        std::cout << "ERROR: file does not exist!!" << std::endl;
        return false;
    }
    
    AudioFormatManager formatManager;
    
    // this can read .wav and .aiff
    formatManager.registerBasicFormats();
    
    AudioFormatReader* reader = formatManager.createReaderFor(audioFile);
    
    if (!reader) {
        std::cout << "ERROR: could not read impulse response file!" << std::endl;
        return false;
    }
    
	//AudioFormatReader* reader = wavFormat.createMemoryMappedReader(audioFile);
    
    int64 ir_length = (int)reader->lengthInSamples-offset;
    
    if (ir_length <= 0) {
        std::cout << "wav file has zero samples" << std::endl;
        return false;
    }
    
    if (reader->numChannels <= channel) {
        std::cout << "wav file doesn't have enough channels: " << reader->numChannels << std::endl;
        return false;
    }
    
    
    AudioSampleBuffer ReadBuffer(reader->numChannels, ir_length); // create buffer
    
    
    reader->read(&ReadBuffer, 0, ir_length, offset, true, true);
    
    // set the samplerate -> maybe we have to resample later...
    samplerate = reader->sampleRate;
    
    //std::cout << "ReadRMS: " << ReadBuffer.getRMSLevel(channel, 0, ir_length) << std::endl;
    
    // check if we want a shorter impulse response
    
    if (ir_length > length && length != 0)
        ir_length = length;
    
    // copy the wanted channel into our IR Buffer
    
    IRBuffer->setSize(1, ir_length);
    IRBuffer->copyFrom(0, 0, ReadBuffer, channel, 0, ir_length);
    
        
    // scale ir with gain
    IRBuffer->applyGain(gain);
    
    // std::cout << "ReadRMS: " << IRBuffer->getRMSLevel(0, 0, ir_length) << std::endl;
    
    delete reader;
    
    
    return true;
}
BufferingAudioReader::BufferedBlock::BufferedBlock (AudioFormatReader& reader, int64 pos, int numSamples)
    : range (pos, pos + numSamples),
      buffer ((int) reader.numChannels, numSamples)
{
    reader.read (&buffer, 0, numSamples, pos, true, true);
}
Exemplo n.º 16
0
bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
                                              int64 startSample,
                                              int64 numSamplesToRead)
{
    const int bufferSize = 16384;
    const int maxChans = 128;
    AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
    int* buffers [maxChans];

    for (int i = maxChans; --i >= 0;)
        buffers[i] = 0;

    if (numSamplesToRead < 0)
        numSamplesToRead = reader.lengthInSamples;

    while (numSamplesToRead > 0)
    {
        const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);

        for (int i = tempBuffer.getNumChannels(); --i >= 0;)
            buffers[i] = (int*) tempBuffer.getSampleData (i, 0);

        if (! reader.read (buffers, maxChans, startSample, numToDo, false))
            return false;

        if (reader.usesFloatingPointData != isFloatingPoint())
        {
            int** bufferChan = buffers;

            while (*bufferChan != 0)
            {
                int* b = *bufferChan++;

                if (isFloatingPoint())
                {
                    // int -> float
                    const double factor = 1.0 / INT_MAX;

                    for (int i = 0; i < numToDo; ++i)
                        ((float*)b)[i] = (float) (factor * b[i]);
                }
                else
                {
                    // float -> int
                    for (int i = 0; i < numToDo; ++i)
                    {
                        const double samp = *(const float*) b;

                        if (samp <= -1.0)
                            *b++ = INT_MIN;
                        else if (samp >= 1.0)
                            *b++ = INT_MAX;
                        else
                            *b++ = roundToInt (INT_MAX * samp);
                    }
                }
            }
        }

        if (! write ((const int**) buffers, numToDo))
            return false;

        numSamplesToRead -= numToDo;
        startSample += numToDo;
    }

    return true;
}
Exemplo n.º 17
0
void Dictionary::createDictionary(std::string outputDir)
{
    //open output file
    std::fstream outputFile;
    outputFile.open(outputDir+"W.txt", std::ios::out);
    if (!outputFile.is_open()) {
        std::cout << "Text file open error!";
        return;
    }
    
    //prepare to read file
    AudioFormatManager formatManager;
    formatManager.registerBasicFormats();
    
    kiss_fft_cfg fwd= kiss_fft_alloc(FFT_SIZE,0,NULL,NULL);
    
    // HARD CODING HERE. REQUIRES MODIFICATION
    float fs = 44100;
    int nChannels = 2;
    numSamplesToRead = round(fs*SECS_PER_BLOCK);
    numSamplesPerBlock = numSamplesToRead/DOWNSAMPLE_RATE;
    
    AudioSampleBuffer buffer(nChannels, numSamplesToRead);
    float* audioBuffer = new float[numSamplesToRead];
    
    for (int track = 21; track<=108; track++) {
        
        // ANY BETTER WAYS TO DEAL WITH FILENAMES??
        std::string strFileDir = sampleFileFolder + "MAPS_ISOL_NO_M_S0_M"+std::to_string(track)+"_AkPnBcht.wav";
        File audioFileS0(strFileDir);
        
        AudioFormatReader* reader;
        
        if (audioFileS0.exists()) {
            reader = formatManager.createReaderFor(audioFileS0);
        }
        else {
            strFileDir = sampleFileFolder + "MAPS_ISOL_NO_M_S1_M"+std::to_string(track)+"_AkPnBcht.wav";
            File audioFileS1(strFileDir);
            reader = formatManager.createReaderFor(audioFileS1);
        }
        
        reader->read(&buffer, 0, numSamplesToRead, fs, true, true);
        
        float* leftBuffer = buffer.getSampleData(0);
        float* rightBuffer = buffer.getSampleData(1);
        
        for (int i=0; i<numSamplesToRead; i++) {
            audioBuffer[i] = (leftBuffer[i]+rightBuffer[i])/2;
        }
        
        antiAlias(audioBuffer, numSamplesToRead);
        
        
        for (int i=0; i<numSamplesPerBlock; i++) {
            audio[i].real( audioBuffer[i*DOWNSAMPLE_RATE]*hammWin(i, numSamplesPerBlock) );
            audio[i].imag(0);
        }
        for (int i = numSamplesPerBlock; i<FFT_SIZE; i++) {
            audio[i].real(0);
            audio[i].imag(0);
        }
        
        kiss_fft(fwd, (kiss_fft_cpx*) audio, (kiss_fft_cpx*)spectrum);
        for (int i = 0; i<FFT_SIZE/2; i++) {
            W[i][track-21] = abs(spectrum[i]);       //HARD CODING HERE!
        }
        
        delete reader;
        
    }
    delete [] audioBuffer;
    
    for(int i = 0; i< FFT_SIZE/2; i++){
        for (int j = 0; j<N_NOTES; j++) {
//            fwrite(&W[i][j], sizeof(float), 1, file);
            outputFile << W[i][j] << "\t";
        }
        outputFile<<std::endl;
    }
    
    outputFile.close();
    
}
bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
                                              int64 startSample,
                                              int64 numSamplesToRead)
{
    const int bufferSize = 16384;
    AudioSampleBuffer tempBuffer ((int) numChannels, bufferSize);

    int* buffers [128] = { 0 };

    for (int i = tempBuffer.getNumChannels(); --i >= 0;)
        buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));

    if (numSamplesToRead < 0)
        numSamplesToRead = reader.lengthInSamples;

    while (numSamplesToRead > 0)
    {
        const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);

        if (! reader.read (buffers, (int) numChannels, startSample, numToDo, false))
            return false;

        if (reader.usesFloatingPointData != isFloatingPoint())
        {
            int** bufferChan = buffers;

            while (*bufferChan != nullptr)
            {
                int* b = *bufferChan++;

                if (isFloatingPoint())
                {
                    // int -> float
                    const double factor = 1.0 / std::numeric_limits<int>::max();

                    for (int i = 0; i < numToDo; ++i)
                        reinterpret_cast<float*> (b)[i] = (float) (factor * b[i]);
                }
                else
                {
                    // float -> int
                    for (int i = 0; i < numToDo; ++i)
                    {
                        const double samp = *(const float*) b;

                        if (samp <= -1.0)
                            *b++ = std::numeric_limits<int>::min();
                        else if (samp >= 1.0)
                            *b++ = std::numeric_limits<int>::max();
                        else
                            *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
                    }
                }
            }
        }

        if (! write (const_cast <const int**> (buffers), numToDo))
            return false;

        numSamplesToRead -= numToDo;
        startSample += numToDo;
    }

    return true;
}
Exemplo n.º 19
0
static void readMaxLevelsFilteringWithColour (AudioFormatReader &reader,
											  BiquadFilter &filterLow, BiquadFilter &filterLowMid, BiquadFilter &filterHighMid, BiquadFilter &filterHigh,
											  int64 startSampleInFile,
											  int64 numSamples,
											  float& lowestLeft, float& highestLeft,
											  float& lowestRight, float& highestRight,
											  Colour &colourLeft, Colour &colourRight)
{
    if (numSamples <= 0)
    {
        lowestLeft = 0;
        lowestRight = 0;
        highestLeft = 0;
        highestRight = 0;
        
        colourLeft = Colours::white;
        colourRight = Colours::white;
        
        return;
    }
	
    const int bufferSize = (int) jmin (numSamples, (int64) 4096);
    HeapBlock<int> tempSpace (bufferSize * 2 + 64);
//    const int heapBlockSize = bufferSize * 2 + 64;
//	int tempSpace[heapBlockSize];
    
    int* tempBuffer[3];
    tempBuffer[0] = &tempSpace[0];//tempSpace.getData();
    tempBuffer[1] = &tempSpace[bufferSize];//tempSpace.getData() + bufferSize;
    tempBuffer[2] = 0;
	
//	HeapBlock<int> filteredBlock (bufferSize * 4);
//	int* filteredArray[4] = {filteredBlock.getData(),
//							 filteredBlock.getData()+bufferSize,
//							 filteredBlock.getData()+(bufferSize*2),
//							 filteredBlock.getData()+(bufferSize*3)};
    const int filteredBlockSize = bufferSize * 4;
    HeapBlock<int> filteredBlock (filteredBlockSize);
    //int filteredBlock[filteredBlockSize];
	int* filteredArray[4] = {&filteredBlock[0],
							 &filteredBlock[bufferSize],
							 &filteredBlock[bufferSize * 2],
							 &filteredBlock[bufferSize * 3]};
    
    float avgLow = 0.0f, avgMid = 0.0f, avgHigh = 0.0f;

    if (reader.usesFloatingPointData)
    {
        float lmin = 1.0e6f;
        float lmax = -lmin;
        float rmin = lmin;
        float rmax = lmax;
		
        while (numSamples > 0)
        {
            const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
            reader.read (tempBuffer, 2, startSampleInFile, numToDo, false);
			
			// copy samples to buffers ready to be filtered
			memcpy(filteredArray[0], tempBuffer[0], sizeof(int)*numToDo);
			memcpy(filteredArray[1], tempBuffer[0], sizeof(int)*numToDo);
			memcpy(filteredArray[2], tempBuffer[0], sizeof(int)*numToDo);
			memcpy(filteredArray[3], tempBuffer[0], sizeof(int)*numToDo);
			
			// filter buffers
			filterLow.processSamples (reinterpret_cast<float*> (filteredArray[0]), numToDo);
			filterLowMid.processSamples (reinterpret_cast<float*> (filteredArray[1]), numToDo);
			filterHighMid.processSamples (reinterpret_cast<float*> (filteredArray[2]), numToDo);
			filterHigh.processSamples (reinterpret_cast<float*> (filteredArray[3]), numToDo);
			
			// calculate colour
			for (int i = 0; i < numToDo; i++)
			{
//				avgLow += fabsf((reinterpret_cast<float*>(filteredArray[0]))[i]);
//				avgMid += fabsf((reinterpret_cast<float*>(filteredArray[1]))[i]);
//				avgHigh += fabsf((reinterpret_cast<float*>(filteredArray[2]))[i]);
			
				float low = fabsf((reinterpret_cast<float*> (filteredArray[0]))[i]);
				float mid = (fabsf((reinterpret_cast<float*> (filteredArray[1]))[i]) + fabsf((reinterpret_cast<float*>(filteredArray[2]))[i]));
				float high = fabsf((reinterpret_cast<float*> (filteredArray[3]))[i]);
				
				if (low > avgLow) {
					avgLow = low;
				}
				if (mid > avgMid) {
					avgMid = mid;
				}
				if (high > avgHigh) {
					avgHigh = high;
				}
			}
			
            numSamples -= numToDo;
            startSampleInFile += numToDo;
			
            float bufMin, bufMax;
            findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);

            lmin = jmin (lmin, bufMin);
            lmax = jmax (lmax, bufMax);
			
            if (reader.numChannels > 1)
            {
                findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
                rmin = jmin (rmin, bufMin);
                rmax = jmax (rmax, bufMax);
            }
        }
		
        if (reader.numChannels <= 1)
        {
            rmax = lmax;
            rmin = lmin;
        }
		
        lowestLeft = lmin;
        highestLeft = lmax;
        lowestRight = rmin;
        highestRight = rmax;
        
//        avgLow = (avgLow / numToAverage);
//        avgMid = (avgMid / numToAverage);
//        avgHigh = (avgHigh / numToAverage);
    }
    else
    {
        int lmax = std::numeric_limits<int>::min();
        int lmin = std::numeric_limits<int>::max();
        int rmax = std::numeric_limits<int>::min();
        int rmin = std::numeric_limits<int>::max();
		
        while (numSamples > 0)
        {
            const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
            if (! reader.read (tempBuffer, 2, startSampleInFile, numToDo, false))
                break;
			
            // copy samples to buffers ready to be filtered
			memcpy (filteredArray[0], tempBuffer[0], sizeof (int) * numToDo);
			memcpy (filteredArray[1], tempBuffer[0], sizeof (int) * numToDo);
			memcpy (filteredArray[2], tempBuffer[0], sizeof (int) * numToDo);
			memcpy (filteredArray[3], tempBuffer[0], sizeof (int) * numToDo);
			
			// filter buffers
			filterLow.processSamples((filteredArray[0]), numToDo);
			filterLowMid.processSamples((filteredArray[1]), numToDo);
			filterHighMid.processSamples((filteredArray[2]), numToDo);
			filterHigh.processSamples((filteredArray[3]), numToDo);
			
			// calculate colour
			for (int i = 0; i < numToDo; i++)
			{
//				avgLow += abs(((filteredArray[0]))[i]);
//				avgMid += abs(((filteredArray[1]))[i]);
//				avgHigh += abs(((filteredArray[2]))[i]);
				
				int low = abs(filteredArray[0][i]);
				int mid = (abs(filteredArray[1][i]) + abs(filteredArray[2][i]));
				int high = abs(filteredArray[3][i]);
				
				if (low > avgLow) {
					avgLow = (float) low;
				}
				if (mid > avgMid) {
					avgMid = (float) mid;
				}
				if (high > avgHigh) {
					avgHigh = (float) high;
				}
				
			}

            numSamples -= numToDo;
            startSampleInFile += numToDo;
			
            for (int j = reader.numChannels; --j >= 0;)
            {
                int bufMin, bufMax;
                findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
				
                if (j == 0)
                {
                    lmax = jmax (lmax, bufMax);
                    lmin = jmin (lmin, bufMin);
                }
                else
                {
                    rmax = jmax (rmax, bufMax);
                    rmin = jmin (rmin, bufMin);
                }
            }
        }
		
        if (reader.numChannels <= 1)
        {
            rmax = lmax;
            rmin = lmin;
        }
		
        lowestLeft = lmin / (float) std::numeric_limits<int>::max();
        highestLeft = lmax / (float) std::numeric_limits<int>::max();
        lowestRight = rmin / (float) std::numeric_limits<int>::max();
        highestRight = rmax / (float) std::numeric_limits<int>::max();

//        avgLow = (avgLow / numToAverage) / (float) std::numeric_limits<int>::max();
//        avgMid = (avgMid / numToAverage) / (float) std::numeric_limits<int>::max();
//        avgHigh = (avgHigh / numToAverage) / (float) std::numeric_limits<int>::max();
        avgLow = avgLow / (float) ::std::numeric_limits<int>::max();
        avgMid = avgMid / (float) ::std::numeric_limits<int>::max();
        avgHigh = avgHigh / (float) ::std::numeric_limits<int>::max();
    }
    
    uint8 maxSize = ::std::numeric_limits<uint8>::max();
    colourLeft = Colour::fromRGB((uint8) (avgLow * maxSize), (uint8) (avgMid * maxSize * 0.66f), (uint8) (avgHigh * maxSize * 0.33f));
    colourRight = colourLeft;
}