//==============================================================================
double PitchDetector::detectPitch (float* samples, int numSamples) noexcept
{
    Array<double> pitches;
    pitches.ensureStorageAllocated (int (numSamples / numSamplesNeededForDetection));
    
    while (numSamples >= numSamplesNeededForDetection)
    {
        double pitch = detectPitchForBlock (samples, numSamplesNeededForDetection);//0.0;
        
        if (pitch > 0.0)
            pitches.add (pitch);
        
        numSamples -= numSamplesNeededForDetection;
        samples += numSamplesNeededForDetection;
    }
    
    if (pitches.size() == 1)
    {
        return pitches[0];
    }
    else if (pitches.size() > 1)
    {
        DefaultElementComparator<double> sorter;
        pitches.sort (sorter);
        
        const double stdDev = findStandardDeviation (pitches.getRawDataPointer(), pitches.size());
        const double medianSample = findMedian (pitches.getRawDataPointer(), pitches.size());
        const double lowerLimit = medianSample - stdDev;
        const double upperLimit = medianSample + stdDev;
        
        Array<double> correctedPitches;
        correctedPitches.ensureStorageAllocated (pitches.size());
        
        for (int i = 0; i < pitches.size(); ++i)
        {
            const double pitch = pitches.getUnchecked (i);
            
            if (pitch >= lowerLimit && pitch <= upperLimit)
                correctedPitches.add (pitch);
        }
        
        const double finalPitch = findMean (correctedPitches.getRawDataPointer(), correctedPitches.size());
        
        return finalPitch;
    }
    
    return 0.0;
}
Example #2
0
    MinMaxValue* getData (const int channelNum, const int cacheIndex) noexcept
    {
        jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));

        return data.getRawDataPointer() + channelNum * numSamplesCached
                                        + cacheIndex;
    }
                void run()
                {
                    Array<int> randomValues;
                    int lastRandomValue = 0;

                    for (int i=1; i<=400; i++)
                    {
                        if ((Desktop::getMousePosition().x * Desktop::getMousePosition().y) != lastRandomValue)
                        {
                            randomValues.add (Desktop::getMousePosition().x * Desktop::getMousePosition().y);
                        }

                        lastRandomValue = Desktop::getMousePosition().x * Desktop::getMousePosition().y;

                        setStatusMessage ("Random seed (move the mouse around to generate more): "+ STR(randomValues.size()));
                        sleep (20);

                        setProgress ((i / (double) 400));
                        if (threadShouldExit())
                            return;
                    }

                    setProgress (-1);
                    setStatusMessage ("Generating 512 bit RSA key pair, this might take a moment");
                    sleep (5);
                    RSAKey::createKeyPair (publicKey, privateKey, 512, randomValues.getRawDataPointer(), randomValues.size());
                }
Example #4
0
    void getLevels (int64 startSample, int numSamples, Array<Range<float> >& levels)
    {
        const ScopedLock sl (readerLock);

        if (reader == nullptr)
        {
            createReader();

            if (reader != nullptr)
            {
                lastReaderUseTime = Time::getMillisecondCounter();
                owner.cache.getTimeSliceThread().addTimeSliceClient (this);
            }
        }

        if (reader != nullptr)
        {
            if (levels.size() < (int) reader->numChannels)
                levels.insertMultiple (0, Range<float>(), (int) reader->numChannels - levels.size());

            reader->readMaxLevels (startSample, numSamples, levels.getRawDataPointer(), (int) reader->numChannels);

            lastReaderUseTime = Time::getMillisecondCounter();
        }
    }
Example #5
0
void Font::getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets) const
{
    // This call isn't thread-safe when there's a message thread running
    jassert (MessageManager::getInstanceWithoutCreating() == nullptr
               || MessageManager::getInstanceWithoutCreating()->currentThreadHasLockedMessageManager());

    getTypeface()->getGlyphPositions (text, glyphs, xOffsets);

    if (auto num = xOffsets.size())
    {
        auto scale = font->height * font->horizontalScale;
        auto* x = xOffsets.getRawDataPointer();

        if (font->kerning != 0.0f)
        {
            for (int i = 0; i < num; ++i)
                x[i] = (x[i] + i * font->kerning) * scale;
        }
        else
        {
            for (int i = 0; i < num; ++i)
                x[i] *= scale;
        }
    }
}
Example #6
0
void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
{
    if (text.isNotEmpty())
    {
        if (undoable)
        {
            undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
        }
        else
        {
            Position pos (*this, insertPos);
            const int firstAffectedLine = pos.getLineNumber();

            CodeDocumentLine* const firstLine = lines [firstAffectedLine];
            String textInsideOriginalLine (text);

            if (firstLine != nullptr)
            {
                const int index = pos.getIndexInLine();
                textInsideOriginalLine = firstLine->line.substring (0, index)
                                         + textInsideOriginalLine
                                         + firstLine->line.substring (index);
            }

            maximumLineLength = -1;
            Array <CodeDocumentLine*> newLines;
            CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
            jassert (newLines.size() > 0);

            CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
            newFirstLine->lineStartInFile = firstLine != nullptr ? firstLine->lineStartInFile : 0;
            lines.set (firstAffectedLine, newFirstLine);

            if (newLines.size() > 1)
                lines.insertArray (firstAffectedLine + 1, newLines.getRawDataPointer() + 1, newLines.size() - 1);

            int lineStart = newFirstLine->lineStartInFile;
            for (int i = firstAffectedLine; i < lines.size(); ++i)
            {
                CodeDocumentLine& l = *lines.getUnchecked (i);
                l.lineStartInFile = lineStart;
                lineStart += l.lineLength;
            }

            checkLastLineStatus();

            const int newTextLength = text.length();
            for (int i = 0; i < positionsToMaintain.size(); ++i)
            {
                CodeDocument::Position& p = *positionsToMaintain.getUnchecked(i);

                if (p.getPosition() >= insertPos)
                    p.setPosition (p.getPosition() + newTextLength);
            }

            listeners.call (&CodeDocument::Listener::codeDocumentTextInserted, text, insertPos);
        }
    }
}
    HRESULT doInvoke (const var& v,
                      DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pDispParams,
                      VARIANT* pVarResult, EXCEPINFO* pExcepInfo, UINT* puArgErr)
    {
        const Identifier memberId (getStringFromDISPID (dispIdMember));

        DynamicObject* const object = v.getDynamicObject();

        if (memberId.toString().isEmpty() || object == nullptr)
            return DISP_E_MEMBERNOTFOUND;

        if ((wFlags & DISPATCH_METHOD) != 0)
        {
            if (! object->hasMethod (memberId))
                return DISP_E_MEMBERNOTFOUND;

            const int numArgs = pDispParams == nullptr ? 0 : pDispParams->cArgs;
            var result;

            if (numArgs == 0)
            {
                result = v.call (memberId);
            }
            else
            {
                Array<var> args;
                for (int j = numArgs; --j >= 0;)
                    args.add (variantTojuceVar (pDispParams->rgvarg[j]));

                result = v.invoke (memberId, numArgs == 0 ? 0 : args.getRawDataPointer(), numArgs);
            }

            if (pVarResult != nullptr)
                juceVarToVariant (result, *pVarResult);

            return S_OK;
        }
        else if ((wFlags & DISPATCH_PROPERTYGET) != 0)
        {
            if (! object->hasProperty (memberId))
                return DISP_E_MEMBERNOTFOUND;

            if (pVarResult != nullptr)
            {
                juceVarToVariant (object->getProperty (memberId), *pVarResult);
                return S_OK;
            }
        }
        else if ((wFlags & DISPATCH_PROPERTYPUT) != 0)
        {
            if (pDispParams != nullptr && pDispParams->cArgs > 0)
            {
                object->setProperty (memberId, variantTojuceVar (pDispParams->rgvarg[0]));
                return S_OK;
            }
        }

        return DISP_E_MEMBERNOTFOUND;
    }
void KWDFile::stopRecording()
{
    Array<uint32> samples;
    String path = String("/recordings/")+String(recordingNumber)+String("/data");
    recdata->getRowXPositions(samples);

    CHECK_ERROR(setAttributeArray(U32,samples.getRawDataPointer(),samples.size(),path,"valid_samples"));
    //ScopedPointer does the deletion and destructors the closings
    recdata = nullptr;
}
Example #9
0
            VertexBuffer (OpenGLContext& context, WavefrontObjFile::Shape& shape) : openGLContext (context)
            {
                numIndices = shape.mesh.indices.size();

                openGLContext.extensions.glGenBuffers (1, &vertexBuffer);
                openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);

                Array<Vertex> vertices;
                createVertexListFromMesh (shape.mesh, vertices, Colours::green);

                openGLContext.extensions.glBufferData (GL_ARRAY_BUFFER, vertices.size() * sizeof (Vertex),
                                                       vertices.getRawDataPointer(), GL_STATIC_DRAW);

                openGLContext.extensions.glGenBuffers (1, &indexBuffer);
                openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
                openGLContext.extensions.glBufferData (GL_ELEMENT_ARRAY_BUFFER, numIndices * sizeof (juce::uint32),
                                                       shape.mesh.indices.getRawDataPointer(), GL_STATIC_DRAW);
            }
Example #10
0
void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
{
    getTypeface()->getGlyphPositions (text, glyphs, xOffsets);

    const int num = xOffsets.size();

    if (num > 0)
    {
        const float scale = font->height * font->horizontalScale;
        float* const x = xOffsets.getRawDataPointer();

        if (font->kerning != 0)
        {
            for (int i = 0; i < num; ++i)
                x[i] = (x[i] + i * font->kerning) * scale;
        }
        else
        {
            for (int i = 0; i < num; ++i)
                x[i] *= scale;
        }
    }
}
Example #11
0
void ArfFile::startNewRecording(int recordingNumber, int nChannels, ArfRecordingInfo* info, Array<int> recordedChanToKWDChan, Array<int> procMap)
{
    this->recordingNumber = recordingNumber;
    this->nChannels = nChannels;
    this->multiSample = info->multiSample;
    uint8 mSample = info->multiSample ? 1 : 0;

	ScopedPointer<ArfRecordingData> bitVoltsSet;
	ScopedPointer<ArfRecordingData> sampleRateSet;

    String recordPath = String("/rec_")+String(recordingNumber);
    CHECK_ERROR(createGroup(recordPath));
    CHECK_ERROR(setAttributeStr(info->name,recordPath,String("name")));
    CHECK_ERROR(setAttribute(U32,&(info->bit_depth),recordPath,String("bit_depth")));

    CHECK_ERROR(setAttribute(U8,&mSample,recordPath,String("is_multiSampleRate_data")));

    int64 timeMilli = Time::currentTimeMillis();
    int64 times[2] = {timeMilli/1000, (timeMilli%1000)*1000};
    setAttributeAsArray(I64, times, 2, recordPath, "timestamp");
    
    String uuid = Uuid().toDashedString();
    CHECK_ERROR(setAttributeStr(uuid, recordPath, String("uuid")));
        
    for (int i = 0; i<nChannels; i++) {        
        //separate Dataset for each channel
        String channelPath = recordPath+"/channel"+String(i);
        
        recarr.add(createDataSet(I16, 0, CHUNK_XSIZE, channelPath));
        CHECK_ERROR(setAttribute(F32, info->channelSampleRates.getRawDataPointer()+i, channelPath, String("sampling_rate")));
        CHECK_ERROR(setAttribute(F32, info->bitVolts.getRawDataPointer()+i, channelPath, String("bit_volts")));
        CHECK_ERROR(setAttributeStr(String("V"), channelPath, String("units")));
        int64 datatype = 0;
        CHECK_ERROR(setAttribute(I64,&datatype,channelPath, String("datatype")));
        CHECK_ERROR(setAttribute(I32, procMap.getRawDataPointer()+i, channelPath, String("nodeID")));
        CHECK_ERROR(setAttribute(I32, recordedChanToKWDChan.getRawDataPointer()+i, channelPath, String("node_channel_no")));
    }
    
    //Creating hierarchy for events
    for (int i=0; i < eventNames.size(); i++)
    {
        ScopedPointer<ArfRecordingData> dSet;
        // e.g /rec_0/Messages
        String path = recordPath + "/";

        int max_dims[3] = {0, 0, 0};
        int chunk_dims[3] = {EVENT_CHUNK_SIZE, 0, 0};
        dSet = createCompoundDataSet(eventCompTypes[i],path + eventNames[i], 1, max_dims, chunk_dims);
        CHECK_ERROR(setAttributeStr(String("samples"), path + eventNames[i], String("units")));
        
    }
    this->sample_rate = info->sample_rate;
    kwdIndex=0;
    for (int i = 0; i < eventNames.size(); i++)
    {
        ArfRecordingData* dSet;
        
        String path = recordPath + "/" + eventNames[i];
        
        dSet = getDataSet(path);
        eventFullData.add(dSet);
    }    
    
    //For spikes
    transformVector.malloc(MAX_TRANSFORM_SIZE);
    
    for (int i=0; i < channelArray.size(); i++)
    {
        createChannelGroup(i);
    }
    for (int i=0; i < channelArray.size(); i++)
    {
        ArfRecordingData* dSet;
        String path = recordPath + "/spike_group"+String(i);
        
        dSet = getDataSet(path);
        spikeFullDataArray.add(dSet);
    }
    
    
    curChan = nChannels;
}
int HDF5FileBase::setAttributeStrArray(Array<const char*>& data, int maxSize, String path, String name)
{
	H5Location* loc;
	Group gloc;
	DataSet dloc;
	Attribute attr;
	hsize_t dims[1];

	if (!opened) return -1;

	StrType type(PredType::C_S1, maxSize + 1);
	type.setSize(H5T_VARIABLE);

	try
	{
		try
		{
			gloc = file->openGroup(path.toUTF8());
			loc = &gloc;
		}
		catch (FileIException error) //If there is no group with that path, try a dataset
		{
			dloc = file->openDataSet(path.toUTF8());
			loc = &dloc;
		}

		if (loc->attrExists(name.toUTF8()))
		{
			//attr = loc.openAttribute(name.toUTF8());
			return -1; //string attributes cannot change size easily, better not allow overwritting.
		}
		else
		{
			DataSpace attr_dataspace;
			int nStrings = data.size();
			if (nStrings > 1)
			{
				dims[0] = nStrings;
				attr_dataspace = DataSpace(1, dims);
			}
			else
				attr_dataspace = DataSpace(H5S_SCALAR);
			attr = loc->createAttribute(name.toUTF8(), type, attr_dataspace);
		}
		attr.write(type, data.getRawDataPointer());

	}
	catch (GroupIException error)
	{
		PROCESS_ERROR;
	}
	catch (AttributeIException error)
	{
		PROCESS_ERROR;
	}
	catch (FileIException error)
	{
		PROCESS_ERROR;
	}
	catch (DataSetIException error)
	{
		PROCESS_ERROR;
	}


	return 0;

}