Ejemplo n.º 1
0
/*
	Start recording to a specified file
	*/
void Audio::AudioRecorder::startRecording (const File& file)
{
    // make sure recorder is stopped first
    stop();
    if (sampleRate > 0)
    {
        // delete file contents first
        file.deleteFile();
        // create file stream for file
        ScopedPointer<FileOutputStream> fileStream (file.createOutputStream());
        
        if (fileStream != nullptr)
        {
            // create a wav format writer
            WavAudioFormat wavFormat;
            AudioFormatWriter* writer = wavFormat.createWriterFor (fileStream, sampleRate, 1, 16, StringPairArray(), 0);
            
            if (writer != nullptr)
            {
                fileStream.release();
                
                // create a thread for the writer.
                threadedWriter = new AudioFormatWriter::ThreadedWriter (writer, backgroundThread, 32768);
                
                // set the next sample number to start
                nextSampleNum = 0;
                
                // scoped lock for writer
                const ScopedLock sl (writerLock);
                activeWriter = threadedWriter;
            }
        }
    }
}
Ejemplo n.º 2
0
bool MainWindow::openFile (const File& file)
{
    createProjectContentCompIfNeeded();

    if (file.hasFileExtension (Project::projectFileExtension))
    {
        ScopedPointer<Project> newDoc (new Project (file));

        Result result (newDoc->loadFrom (file, true));

        if (result.wasOk() && closeCurrentProject())
        {
            setProject (newDoc);
            newDoc.release()->setChangedFlag (false);

            jassert (getProjectContentComponent() != nullptr);
            getProjectContentComponent()->reloadLastOpenDocuments();

            if (Project* p = getProject())
                p->updateDeprecatedProjectSettingsInteractively();

            return true;
        }
    }
    else if (file.exists())
    {
        return getProjectContentComponent()->showEditorForFile (file, true);
    }

    return false;
}
Ejemplo n.º 3
0
//Creates a dataset: an array of HDF5 CompoundType 
//If you want a dimension i to be unlimited, pass chunk_dims[i]=NCHUNK and max_dims[i]=0. If limited, pass max_dims[i]=N and chunk_dims[i]=N.
ArfRecordingData* ArfFileBase::createCompoundDataSet(CompType type, String path, int dimension, int* max_dims, int* chunk_dims)
{
    ScopedPointer<DataSet> data;
    DSetCreatPropList prop;
    
    hsize_t Hdims[3];
    hsize_t Hmax_dims [3];
    hsize_t Hchunk_dims[3];

    for (int i=0; i < dimension; i++)
    {
        Hchunk_dims[i] = chunk_dims[i];
        if (chunk_dims[i] > 0 && chunk_dims[i] != max_dims[i])
        {
            Hmax_dims[i] = H5S_UNLIMITED;
            Hdims[i] = 0;
        }
        else
        {
            Hmax_dims[i] = max_dims[i];
            Hdims[i] = max_dims[i];
        }
    }   
    
    DataSpace dSpace(dimension, Hdims, Hmax_dims);
    prop.setChunk(dimension, Hchunk_dims);
    data = new DataSet(file->createDataSet(path.toUTF8(),type,dSpace,prop));
    return new ArfRecordingData(data.release());  
}
Ejemplo n.º 4
0
XmlElement* XmlDocument::parseDocumentElement (String::CharPointerType textToParse,
                                               const bool onlyReadOuterDocumentElement)
{
    input = textToParse;
    errorOccurred = false;
    outOfData = false;
    needToLoadDTD = true;

    if (textToParse.isEmpty())
    {
        lastError = "not enough input";
    }
    else if (! parseHeader())
    {
        lastError = "malformed header";
    }
    else if (! parseDTD())
    {
        lastError = "malformed DTD";
    }
    else
    {
        lastError.clear();

        ScopedPointer<XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));

        if (! errorOccurred)
            return result.release();
    }

    return nullptr;
}
Ejemplo n.º 5
0
HDF5RecordingData* HDF5FileBase::getDataSet(String path)
{
    ScopedPointer<DataSet> data;

    if (!opened) return nullptr;

    try
    {
        data = new DataSet(file->openDataSet(path.toUTF8()));
        return new HDF5RecordingData(data.release());
    }
    catch (DataSetIException error)
    {
        error.printError();
        return nullptr;
    }
    catch (FileIException error)
    {
        error.printError();
        return nullptr;
    }
    catch (DataSpaceIException error)
    {
        error.printError();
        return nullptr;
    }
}
AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
{
    // you need to actually register some formats before the manager can
    // use them to open a file!
    jassert (getNumKnownFormats() > 0);

    ScopedPointer <InputStream> in (audioFileStream);

    if (in != nullptr)
    {
        const int64 originalStreamPos = in->getPosition();

        for (int i = 0; i < getNumKnownFormats(); ++i)
        {
            AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);

            if (r != nullptr)
            {
                in.release();
                return r;
            }

            in->setPosition (originalStreamPos);

            // the stream that is passed-in must be capable of being repositioned so
            // that all the formats can have a go at opening it.
            jassert (in->getPosition() == originalStreamPos);
        }
    }

    return nullptr;
}
Ejemplo n.º 7
0
    //==============================================================================
    void startRecording (const File& file)
    {
        stop();

        if (sampleRate > 0)
        {
            // Create an OutputStream to write to our destination file...
            file.deleteFile();
            ScopedPointer<FileOutputStream> fileStream (file.createOutputStream());

            if (fileStream != 0)
            {
                // Now create a WAV writer object that writes to our output stream...
                WavAudioFormat wavFormat;
                AudioFormatWriter* writer = wavFormat.createWriterFor (fileStream, sampleRate, 1, 16, StringPairArray(), 0);

                if (writer != 0)
                {
                    fileStream.release(); // (passes responsibility for deleting the stream to the writer object that is now using it)

                    // Now we'll create one of these helper objects which will act as a FIFO buffer, and will
                    // write the data to disk on our background thread.
                    threadedWriter = new AudioFormatWriter::ThreadedWriter (writer, backgroundThread, 32768);

                    // And now, swap over our active writer pointer so that the audio callback will start using it..
                    const ScopedLock sl (writerLock);
                    activeWriter = threadedWriter;
                }
            }
        }
    }
Ejemplo n.º 8
0
bool DirectoryContentsList::addFile (const File& file, const bool isDir,
                                     const int64 fileSize,
                                     Time modTime, Time creationTime,
                                     const bool isReadOnly)
{
    if (fileFilter == nullptr
         || ((! isDir) && fileFilter->isFileSuitable (file))
         || (isDir && fileFilter->isDirectorySuitable (file)))
    {
        ScopedPointer<FileInfo> info (new FileInfo());

        info->filename = file.getFileName();
        info->fileSize = fileSize;
        info->modificationTime = modTime;
        info->creationTime = creationTime;
        info->isDirectory = isDir;
        info->isReadOnly = isReadOnly;

        const ScopedLock sl (fileListLock);

        for (int i = files.size(); --i >= 0;)
            if (files.getUnchecked(i)->filename == info->filename)
                return false;

        FileInfoComparator comp;
        files.addSorted (comp, info.release());
        return true;
    }

    return false;
}
Ejemplo n.º 9
0
MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
{
    jassert (callback != 0);

    using namespace CoreMidiHelpers;
    MidiInput* mi = 0;
    MIDIClientRef client = getGlobalMidiClient();

    if (client != 0)
    {
        ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
        mpc->active = false;

        MIDIEndpointRef endPoint;
        CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
        if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
        {
            mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);

            mi = new MidiInput (deviceName);
            mpc->input = mi;
            mi->internal = mpc;

            const ScopedLock sl (callbackLock);
            activeCallbacks.add (mpc.release());
        }

        CFRelease (name);
    }

    return mi;
}
Ejemplo n.º 10
0
Component* TaskContextListBoxModel::refreshComponentForRow (int rowNumber, bool , Component* existingComponentToUpdate)
{
	ScopedPointer<Component> comp (existingComponentToUpdate);

	if (rowNumber < getNumRows())
	{
		if (comp != nullptr)
		{
			TaskContextViewComponent* viewComp = dynamic_cast< TaskContextViewComponent* >(existingComponentToUpdate);
			if (viewComp != nullptr)
			{
				comp.release ();
				viewComp->setTaskContext (getTaskForRow (rowNumber));
				return viewComp;
			}
		}

		TaskContextViewComponent* viewComp = createViewForTaskContext (getTaskForRow (rowNumber));
		if (viewComp != nullptr)
		{
			viewComp->triggerRefresh ();
			return viewComp;
		}
	}

	return nullptr;
}
Ejemplo n.º 11
0
bool SAMApplication::openFile(const File& file)
{
    for (int j = mainWindows.size(); --j >= 0;)
    {
        if (mainWindows.getUnchecked(j)->getMDLFile() != nullptr
             && mainWindows.getUnchecked(j)->getMDLFile()->getFile() == file)
        {
            mainWindows.getUnchecked(j)->toFront (true);
            return true;
        }
    }
    if (file.hasFileExtension (MDLFile::mdlFileExtension))
    {
        ScopedPointer <MDLFile> newMDL (new MDLFile());

        if (newMDL->loadFrom (file, true))
        {
            MainAppWindow* w = getOrCreateEmptyWindow();
            w->setMDLFile(newMDL.release());
            w->makeVisible();
            avoidSuperimposedWindows (w);
            addToFileList(w->getMDLFile()->getFile());
            w->updateTitle();
            return true;
        }
    }
    else if (file.exists())
    {
    	Alerts::wrongFileType();
    }
    return false;
}
Ejemplo n.º 12
0
MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
{
    jassert (callback != nullptr);

    using namespace CoreMidiHelpers;
    MidiInput* mi = nullptr;

    if (MIDIClientRef client = getGlobalMidiClient())
    {
        ScopedPointer<MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
        mpc->active = false;

        MIDIEndpointRef endPoint;
        ScopedCFString name;
        name.cfString = deviceName.toCFString();

        if (CHECK_ERROR (MIDIDestinationCreate (client, name.cfString, midiInputProc, mpc, &endPoint)))
        {
            mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);

            mi = new MidiInput (deviceName);
            mpc->input = mi;
            mi->internal = mpc;

            const ScopedLock sl (callbackLock);
            activeCallbacks.add (mpc.release());
        }
    }

    return mi;
}
Ejemplo n.º 13
0
  void setTickSample (void const* audioData, int dataBytes)
  {
    ScopedPointer <MemoryInputStream> mis (new MemoryInputStream (audioData, dataBytes, false));

    m_synth.clearVoices ();
    m_synth.clearSounds ();

    AudioFormatManager afm;
    afm.registerBasicFormats ();
    
    {
      ScopedPointer <AudioFormatReader> afr (afm.createReaderFor (mis));

      if (afr != nullptr)
      {
        mis.release ();

        BigInteger midiNotes;
        midiNotes.setRange (0, 127, true);

        SynthesiserSound::Ptr sound = new SamplerSound (
          "Tick",
          *afr,
          midiNotes,
          60,
          0,
          0,
          60./40.);

        m_synth.addSound (sound);
        m_synth.addVoice (new SamplerVoice);
      }
    }

  }
Ejemplo n.º 14
0
        Recorder* createRecorder (const int numChannels, const int sampleRate)
        {
            if (numChannels <= 0)
                return nullptr;

            ScopedPointer<Recorder> recorder (new Recorder (numChannels, sampleRate, *this));
            return recorder->openedOk() ? recorder.release() : nullptr;
        }
Ejemplo n.º 15
0
        Player* createPlayer (const int numChannels, const int sampleRate)
        {
            if (numChannels <= 0)
                return nullptr;

            ScopedPointer<Player> player (new Player (numChannels, sampleRate, *this));
            return player->openedOk() ? player.release() : nullptr;
        }
Ejemplo n.º 16
0
SourceURL* SourceURL::New (
    URL const& url)
{
    ScopedPointer <SourceURL> object (
        new SourceURLImp (url));

    return object.release ();
}
Ejemplo n.º 17
0
MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
{
    if (callback == nullptr)
        return nullptr;

    UINT deviceId = MIDI_MAPPER;
    int n = 0;
    String name;

    const int num = midiInGetNumDevs();

    for (int i = 0; i < num; ++i)
    {
        MIDIINCAPS mc = { 0 };

        if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
        {
            if (index == n)
            {
                deviceId = i;
                name = String (mc.szPname, numElementsInArray (mc.szPname));
                break;
            }

            ++n;
        }
    }

    ScopedPointer <MidiInput> in (new MidiInput (name));
    ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));

    HMIDIIN h;
    HRESULT err = midiInOpen (&h, deviceId,
                              (DWORD_PTR) &MidiInCollector::midiInCallback,
                              (DWORD_PTR) (MidiInCollector*) collector,
                              CALLBACK_FUNCTION);

    if (err == MMSYSERR_NOERROR)
    {
        collector->deviceHandle = h;
        in->internal = collector.release();
        return in.release();
    }

    return nullptr;
}
Ejemplo n.º 18
0
void PaintElementPath::restorePathFromString (const String& s)
{
    points.clear();

    StringArray tokens;
    tokens.addTokens (s, false);
    tokens.trim();
    tokens.removeEmptyStrings();

    for (int i = 0; i < tokens.size(); ++i)
    {
        ScopedPointer<PathPoint> p (new PathPoint (this));

        if (tokens[i] == "s")
        {
            p->type = Path::Iterator::startNewSubPath;
            p->pos [0] = RelativePositionedRectangle();
            p->pos [0].rect = PositionedRectangle (tokens [i + 1] + " " + tokens [i + 2]);
            i += 2;
        }
        else if (tokens[i] == "l")
        {
            p->type = Path::Iterator::lineTo;
            p->pos [0] = RelativePositionedRectangle();
            p->pos [0].rect = PositionedRectangle (tokens [i + 1] + " " + tokens [i + 2]);
            i += 2;
        }
        else if (tokens[i] == "q")
        {
            p->type = Path::Iterator::quadraticTo;
            p->pos [0] = RelativePositionedRectangle();
            p->pos [0].rect = PositionedRectangle (tokens [i + 1] + " " + tokens [i + 2]);
            p->pos [1] = RelativePositionedRectangle();
            p->pos [1].rect = PositionedRectangle (tokens [i + 3] + " " + tokens [i + 4]);
            i += 4;
        }
        else if (tokens[i] == "c")
        {
            p->type = Path::Iterator::cubicTo;
            p->pos [0] = RelativePositionedRectangle();
            p->pos [0].rect = PositionedRectangle (tokens [i + 1] + " " + tokens [i + 2]);
            p->pos [1] = RelativePositionedRectangle();
            p->pos [1].rect = PositionedRectangle (tokens [i + 3] + " " + tokens [i + 4]);
            p->pos [2] = RelativePositionedRectangle();
            p->pos [2].rect = PositionedRectangle (tokens [i + 5] + " " + tokens [i + 6]);
            i += 6;
        }
        else if (tokens[i] == "x")
        {
            p->type = Path::Iterator::closePath;
        }
        else
            continue;

        points.add (p.release());
    }
}
AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
{
    ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));

    if (b->pimpl == 0)
        b = nullptr;

    return b.release();
}
Ejemplo n.º 20
0
    Component* createEditor() override
    {
        ScopedPointer<JucerDocument> jucerDoc (JucerDocument::createForCppFile (getProject(), getFile()));

        if (jucerDoc != nullptr)
            return new JucerDocumentEditor (jucerDoc.release());

        return SourceCodeDocument::createEditor();
    }
Ejemplo n.º 21
0
InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
                                      OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
                                      const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
{
    ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
                                                           progressCallback, progressCallbackContext,
                                                           headers, timeOutMs, responseHeaders));

    return wi->isError() ? nullptr : wi.release();
}
Ejemplo n.º 22
0
HDF5RecordingData* HDF5FileBase::createDataSet(DataTypes type, int dimension, int* size, int* chunking, String path)
{
    ScopedPointer<DataSet> data;
    DSetCreatPropList prop;
    if (!opened) return nullptr;

    //Right now this classes don't support datasets with rank > 3.
    //If it's needed in the future we can extend them to be of generic rank
    if ((dimension > 3) || (dimension < 1)) return nullptr;

    DataType H5type = getH5Type(type);

    hsize_t dims[3], chunk_dims[3], max_dims[3];

    for (int i=0; i < dimension; i++)
    {
        dims[i] = size[i];
        if (chunking[i] > 0)
        {
            chunk_dims[i] = chunking[i];
            max_dims[i] = H5S_UNLIMITED;
        }
        else
        {
            chunk_dims[i] = size[i];
            max_dims[i] = size[i];
        }
    }

    try
    {
        DataSpace dSpace(dimension,dims,max_dims);
        prop.setChunk(dimension,chunk_dims);

        data = new DataSet(file->createDataSet(path.toUTF8(),H5type,dSpace,prop));
        return new HDF5RecordingData(data.release());
    }
    catch (DataSetIException error)
    {
        error.printError();
        return nullptr;
    }
    catch (FileIException error)
    {
        error.printError();
        return nullptr;
    }
    catch (DataSpaceIException error)
    {
        error.printError();
        return nullptr;
    }


}
void InterprocessConnectionServer::run()
{
    while ((! threadShouldExit()) && socket != nullptr)
    {
        ScopedPointer<StreamingSocket> clientSocket (socket->waitForNextConnection());

        if (clientSocket != nullptr)
            if (InterprocessConnection* newConnection = createConnectionObject())
                newConnection->initialiseWithSocket (clientSocket.release());
    }
}
Ejemplo n.º 24
0
AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in, const bool deleteStreamIfOpeningFails)
{
    ScopedPointer<OggReader> r (new OggReader (in));

    if (r->sampleRate > 0)
        return r.release();

    if (! deleteStreamIfOpeningFails)
        r->input = nullptr;

    return nullptr;
}
Ejemplo n.º 25
0
AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
                                                          double sampleRate,
                                                          unsigned int numChannels,
                                                          int bitsPerSample,
                                                          const StringPairArray& metadataValues,
                                                          int qualityOptionIndex)
{
    ScopedPointer <OggWriter> w (new OggWriter (out, sampleRate, numChannels,
                                                (unsigned int) bitsPerSample, qualityOptionIndex, metadataValues));

    return w->ok ? w.release() : nullptr;
}
Ejemplo n.º 26
0
//==============================================================================
Project* NewProjectWizard::runWizard (Component* ownerWindow_,
                                      const String& projectName,
                                      const File& targetFolder_)
{
    ownerWindow = ownerWindow_;
    appTitle = projectName;
    targetFolder = targetFolder_;

    if (! targetFolder.exists())
    {
        if (! targetFolder.createDirectory())
            failedFiles.add (targetFolder.getFullPathName());
    }
    else if (FileHelpers::containsAnyNonHiddenFiles (targetFolder))
    {
        if (! AlertWindow::showOkCancelBox (AlertWindow::InfoIcon, "New Juce Project",
                                            "The folder you chose isn't empty - are you sure you want to create the project there?\n\nAny existing files with the same names may be overwritten by the new files."))
            return nullptr;
    }

    projectFile = targetFolder.getChildFile (File::createLegalFileName (appTitle))
                              .withFileExtension (Project::projectFileExtension);

    ScopedPointer<Project> project (new Project (projectFile));
    project->addDefaultModules (true);

    if (failedFiles.size() == 0)
    {
        project->setFile (projectFile);
        project->setTitle (appTitle);
        project->getBundleIdentifier() = project->getDefaultBundleIdentifier();

        if (! initialiseProject (*project))
            return nullptr;

        if (project->save (false, true) != FileBasedDocument::savedOk)
            return nullptr;

        project->setChangedFlag (false);
    }

    if (failedFiles.size() > 0)
    {
        AlertWindow::showMessageBox (AlertWindow::WarningIcon,
                                     "Errors in Creating Project!",
                                     "The following files couldn't be written:\n\n"
                                        + failedFiles.joinIntoString ("\n", 0, 10));
        return nullptr;
    }

    return project.release();
}
Ejemplo n.º 27
0
ImagePixelData::Ptr OpenGLImageType::create (Image::PixelFormat, int width, int height, bool /*shouldClearImage*/) const
{
    OpenGLContext* currentContext = OpenGLContext::getCurrentContext();
    jassert (currentContext != nullptr); // an OpenGL image can only be created when a valid context is active!

    ScopedPointer<OpenGLFrameBufferImage> im (new OpenGLFrameBufferImage (*currentContext, width, height));

    if (! im->initialise())
        return ImagePixelData::Ptr();

    im->frameBuffer.clear (Colours::transparentBlack);
    return im.release();
}
Ejemplo n.º 28
0
//==============================================================================
AudioFormatReader* CoreAudioFormat::createReaderFor (InputStream* sourceStream,
                                                     bool deleteStreamIfOpeningFails)
{
    ScopedPointer<CoreAudioReader> r (new CoreAudioReader (sourceStream));

    if (r->ok)
        return r.release();

    if (! deleteStreamIfOpeningFails)
        r->input = nullptr;

    return nullptr;
}
Ejemplo n.º 29
0
//==============================================================================
AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
                                                          const bool deleteStreamIfOpeningFails)
{
    ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));

    if (r->ok)
        return r.release();

    if (! deleteStreamIfOpeningFails)
        r->input = 0;

    return nullptr;
}
Ejemplo n.º 30
0
MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
{
    jassert (callback != 0);

    using namespace CoreMidiHelpers;
    MidiInput* newInput = 0;

    if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
    {
        MIDIEndpointRef endPoint = MIDIGetSource (index);

        if (endPoint != 0)
        {
            CFStringRef name;

            if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
            {
                MIDIClientRef client = getGlobalMidiClient();

                if (client != 0)
                {
                    MIDIPortRef port;
                    ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));

                    if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
                    {
                        if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
                        {
                            mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);

                            newInput = new MidiInput (getDevices() [index]);
                            mpc->input = newInput;
                            newInput->internal = mpc;

                            const ScopedLock sl (callbackLock);
                            activeCallbacks.add (mpc.release());
                        }
                        else
                        {
                            CHECK_ERROR (MIDIPortDispose (port));
                        }
                    }
                }
            }

            CFRelease (name);
        }
    }

    return newInput;
}