Example #1
0
static int beginRequestHandler(struct mg_connection *conn) {
    enum BeginRequestHandlerReturnValues { HANDLED = 1, NOT_HANDLED = 0 };

    struct mg_request_info *info = mg_get_request_info(conn);
    String uri(info->uri);
    if (!uri.endsWithIgnoreCase(".json") && !uri.endsWithIgnoreCase(".wav")) {
        // DBG << "Not handling as audio request" << endl;
        return NOT_HANDLED;
    }

    // DBG << "Handling URI: " << uri << endl;

    var parsed;
    // First try to look in the query string
    String queryString = urldecode(info->query_string);
    // DBG << queryString << endl;
    parsed = JSON::parse(queryString);
    // Otherwise look in the POST data
    if (!parsed) {
        MemoryBlock postDataBlock;
        char postBuffer[1024];
        int didRead;
        while ((didRead = mg_read(conn, postBuffer, sizeof(postBuffer)))) {
            postDataBlock.append(postBuffer, didRead);
        }
        MemoryInputStream postStream(postDataBlock, false);
        parsed = JSON::parse(postStream);
    }

    DBG << "Request JSON: " << JSON::toString(parsed, true) << endl;

    PluginRequestParameters params(parsed);
    if (uri.endsWithIgnoreCase(".json")) {
        params.listParameters = true;
    }

    MemoryBlock block;
    MemoryOutputStream ostream(block, false);

    // DBG << "Rendering plugin request" << endl;
    int64 startTime = Time::currentTimeMillis();
    bool result = handlePluginRequest(params, ostream);
    if (!result) {
        DBG << "-> Unable to handle plugin request!" << endl;
        mg_printf(conn, "HTTP/1.0 500 ERROR\r\n\r\n");
        return HANDLED;
    }
    DBG << "-> Rendered plugin request in " << (Time::currentTimeMillis() - startTime) << "ms" << endl;

    // Note: MemoryOutputStream::getDataSize() is the actual number of bytes written.
    // Do not use MemoryBlock::getSize() since this reports the memory allocated (but not initialized!)
    mg_printf(conn, "HTTP/1.0 200 OK\r\n"
              "Content-Length: %d\r\n"
              "Content-Type: %s\r\n"
              "\r\n",
              (int)ostream.getDataSize(), params.getContentType());
    mg_write(conn, ostream.getData(), ostream.getDataSize());

    return HANDLED;
}
void CtrlrLuaAudioConverter::convertInt16 (MemoryBlock &sourceData, AudioSampleBuffer &destination, const int numSamples, const int numChannels, const bool interleaved)
{
	if (interleaved)
	{
		AudioData::ConverterInstance <	AudioData::Pointer <AudioData::Int16,
																		AudioData::NativeEndian,
																		AudioData::Interleaved,
																		AudioData::Const>, 
													AudioData::Pointer <AudioData::Float32,
																		AudioData::NativeEndian,
																		AudioData::Interleaved,
																		AudioData::NonConst>
									> converter;
		for (int ch=0; ch<numChannels; ch++)
		{
			converter.convertSamples ((void *)destination.getReadPointer(ch), sourceData.getData(), numSamples);
		}
	}
	else
	{
		AudioData::ConverterInstance <	AudioData::Pointer <AudioData::Int16,
																		AudioData::NativeEndian,
																		AudioData::NonInterleaved,
																		AudioData::Const>, 
													AudioData::Pointer <AudioData::Float32,
																		AudioData::NativeEndian,
																		AudioData::Interleaved,
																		AudioData::NonConst>
									> converter;
		for (int ch=0; ch<numChannels; ch++)
		{
			converter.convertSamples ((void *)destination.getReadPointer(ch), ch, sourceData.getData(), ch, numSamples);
		}
	}
}
Example #3
0
const MidiMessage createFromHexData (const String &hexData)
{
	MemoryBlock bl;
	bl.loadFromHexString(hexData);

	return (MidiMessage ((uint8*)bl.getData(), (int)bl.getSize()));
}
Example #4
0
void Tester_68k::sampleNot() {
    Results* oObj;
    MemoryBlock* oSampleMem;

    oObj = new Results("NOT.B D0");
    oObj->setRegD(0, 0x12345687);
    oObj->setN();
    oObj->setCycleCount(4);

    oObj = new Results("NOT.W D0");
    oObj->setRegD(0, 0x1234ffff);
    oObj->setN()->setX();
    oObj->setCycleCount(4);

    oObj = new Results("NOT.L D0");
    oObj->setRegD(0, 0x000000ff);
    oObj->setX();
    oObj->setCycleCount(6);
    oObj->setIrqSampleCyclePos(2);

    oObj = new Results("NOT.L ($3000).L");
    oObj->setX();
    oSampleMem = new MemoryBlock();
    oSampleMem->writeLong(0x3000, 0x0ffedcee);
    oObj->setCodeBlock(oSampleMem);
    oObj->setCycleCount(28);
}
Example #5
0
static void save_fxbp(SoundPlugin *plugin, wchar_t *wfilename, bool is_fxb){
  Data *data = (Data*)plugin->data;
  AudioPluginInstance *instance = data->audio_instance;

  MemoryBlock memoryBlock;
  bool result = VSTPluginFormat::saveToFXBFile(instance, memoryBlock, is_fxb);
  if (result==false){
    GFX_Message(NULL, "Unable to create FXB/FXP data for this plugin");
    return;
  }
  
  String filename(wfilename);

  File file(filename);

  Result result2 = file.create();

  if (result2.failed()){
    GFX_Message(NULL, "Unable to create file %s (%s)", STRING_get_chars(wfilename), result2.getErrorMessage().toRawUTF8());
    return;
  }
  
  bool result3 = file.replaceWithData(memoryBlock.getData(), memoryBlock.getSize());
  if (result3==false){
    GFX_Message(NULL, "Unable to write data to file %s (disk full?)", STRING_get_chars(wfilename));
    return;
  }
  
  
  printf("\n\n\n ***************** result: %d\n\n\n\n",result);
}
Example #6
0
void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
{
    clear();
    LinkedListPointer<NamedValue>::Appender appender (values);

    const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..

    for (int i = 0; i < numAtts; ++i)
    {
        const String& name  = xml.getAttributeName (i);
        const String& value = xml.getAttributeValue (i);

        if (name.startsWith ("base64:"))
        {
            MemoryBlock mb;

            if (mb.fromBase64Encoding (value))
            {
                appender.append (new NamedValue (name.substring (7), var (mb)));
                continue;
            }
        }

        appender.append (new NamedValue (name, var (value)));
    }
}
void BenderControlConnectionHandler::messageReceived (const MemoryBlock &message)
{
	if (message.getSize() <= 2)
		return;

	BenderControlMessageType type = getControlMessageType (message);

	switch (type)
	{
		case helo:
			respondToHelo(message);
			return;

		case streamData:
			respondToStreamDataRequest(message);
			return;

		case setMotor:
			respondToSetMotorRequest(message);
			return;

		default:
			_DBG("\tunknown message received ["+message.toString()+"]");
			break;
	}
}
Example #8
0
const Result CtrlrWindows::getDefaultResources(MemoryBlock& dataToWrite)
{
#ifdef DEBUG_INSTANCE
	File temp("c:\\devel\\debug_small.bpanelz");

	MemoryBlock data;
	{
		ScopedPointer <FileInputStream> fis (temp.createInputStream());
		fis->readIntoMemoryBlock (data);
	}

	ValueTree t = ValueTree::readFromGZIPData(data.getData(), data.getSize());

	if (t.isValid())
	{
		ValueTree r = t.getChildWithName (Ids::resourceExportList);
		if (r.isValid())
		{
			MemoryOutputStream mos (dataToWrite, false);
			{
				GZIPCompressorOutputStream gzipOutputStream (&mos);
				r.writeToStream(gzipOutputStream);
				gzipOutputStream.flush();
			}
			return (Result::ok());
		}
	}
	else
	{
		return (Result::fail("Windows Native: getDefaultResources got data but couldn't parse it as a compressed ValueTree"));
	}
#endif

	return (readResource (nullptr, MAKEINTRESOURCE(CTRLR_INTERNAL_RESOURCES_RESID), RT_RCDATA, dataToWrite));
}
Example #9
0
OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
{
    if (data.getSize() > 0)
        stream.write (data.getData(), (int) data.getSize());

    return stream;
}
BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
{
    if (data.getSize() > 0)
        stream.write (data.getData(), data.getSize());

    return stream;
}
				static void crashHandler()
				{
					if (JUCEApplication::isStandaloneApp())
					{
						MemoryBlock mb (SystemStats::getStackBacktrace().toUTF8(), SystemStats::getStackBacktrace().length());
						File::getSpecialLocation(File::currentApplicationFile)
							.startAsProcess("--crashReport=\""
											+File::getSpecialLocation(File::currentApplicationFile).getFullPathName()
											+"\" --stackTrace=\""+mb.toBase64Encoding()
											+"\"");
					}
					else
					{
						const String stackTrace = SystemStats::getStackBacktrace();
						File crashFile (File::getSpecialLocation(File::currentApplicationFile).getFileExtension()+".crash");

						AlertWindow::showMessageBox (AlertWindow::WarningIcon,
														"Ctrlr has crashed",
														"Looks like Ctrlr has crashed, since this is not a standalone instance, we won't do anything.\
														A crash log will be written to "+crashFile.getFullPathName()
														+"\n\n"+stackTrace);

						crashFile.replaceWithText ("Ctrlr crash at: "+Time::getCurrentTime().toString(true, true, true, true) + "\nStack trace:\n"+stackTrace);
					}
				}
StandaloneFilterWindow::~StandaloneFilterWindow()
{
    PropertySet* const globalSettings = getGlobalSettings();

    globalSettings->setValue (T("windowX"), getX());
    globalSettings->setValue (T("windowY"), getY());

    deleteAndZero (optionsButton);

    if (globalSettings != 0 && deviceManager != 0)
    {
        XmlElement* const xml = deviceManager->createStateXml();
        globalSettings->setValue (T("audioSetup"), xml);
        delete xml;
    }

    if (globalSettings != 0 && filter != 0)
    {
        MemoryBlock data;
        filter->getStateInformation (data);

        globalSettings->setValue (T("filterState"), data.toBase64Encoding());
    }

    deleteAndZero (deviceManager);

    deleteFilter();
}
    static std::uint32_t getBinaryValue (const String& regValuePath, MemoryBlock& result, DWORD wow64Flags)
    {
        const RegistryKeyWrapper key (regValuePath, false, wow64Flags);

        if (key.key != 0)
        {
            for (unsigned long bufferSize = 1024; ; bufferSize *= 2)
            {
                result.setSize (bufferSize, false);
                DWORD type = REG_NONE;

                const LONG err = RegQueryValueEx (key.key, key.wideCharValueName, 0, &type,
                                                  (LPBYTE) result.getData(), &bufferSize);

                if (err == ERROR_SUCCESS)
                {
                    result.setSize (bufferSize, false);
                    return type;
                }

                if (err != ERROR_MORE_DATA)
                    break;
            }
        }

        return REG_NONE;
    }
void HostFilterComponent::handleSaveCommand(bool saveToExistingFileAndDontPrompt)
{
   File tmp = currentSessionFile;
   
   bool userConfirmed = true;
   if (!saveToExistingFileAndDontPrompt || !tmp.exists())
   {
      FileChooser myChooser (T("Save Session..."),
                              currentSessionFile.exists() ? tmp : Config::getInstance ()->lastSessionDirectory,
                              JOST_SESSION_WILDCARD,
                              JOST_USE_NATIVE_FILE_CHOOSER);

      if (myChooser.browseForFileToSave (true))
         tmp = myChooser.getResult().withFileExtension (JOST_SESSION_EXTENSION);
      else
         userConfirmed = false;      
   }
   
   if (userConfirmed && (tmp != File::nonexistent))
   {
      MemoryBlock fileData;
      getFilter ()->getStateInformation (fileData);

      if (tmp.replaceWithData (fileData.getData (), fileData.getSize()))
      {
         Config::getInstance()->addRecentSession (tmp);
         setCurrentSessionFile(tmp);
         Config::getInstance()->lastSessionFile = tmp;
      }
   }
}
Example #15
0
void OnlineUnlockStatus::load()
{
    MemoryBlock mb;
    mb.fromBase64Encoding (getState());

    if (mb.getSize() > 0)
        status = ValueTree::readFromGZIPData (mb.getData(), mb.getSize());
    else
        status = ValueTree (stateTagName);

    StringArray localMachineNums (getLocalMachineIDs());

    if (machineNumberAllowed (StringArray ("1234"), localMachineNums))
        status.removeProperty (unlockedProp, nullptr);

    KeyFileUtils::KeyFileData data;
    data = KeyFileUtils::getDataFromKeyFile (KeyFileUtils::getXmlFromKeyFile (status[keyfileDataProp], getPublicKey()));

    if (data.keyFileExpires)
    {
        if (! doesProductIDMatch (data.appID))
            status.removeProperty (expiryTimeProp, nullptr);

        if (! machineNumberAllowed (data.machineNumbers, localMachineNums))
            status.removeProperty (expiryTimeProp, nullptr);
    }
    else
    {
        if (! doesProductIDMatch (data.appID))
            status.removeProperty (unlockedProp, nullptr);

        if (! machineNumberAllowed (data.machineNumbers, localMachineNums))
            status.removeProperty (unlockedProp, nullptr);
    }
}
Example #16
0
Surface *Surface::getScreen(uint16 resourceId) {
	MemoryBlock *block = Disk::getReference().getEntry(resourceId);
	PictureDecoder d;
	MemoryBlock *decodedData = d.decode(block);
	delete block;
	return new Surface(decodedData, FULL_SCREEN_WIDTH, decodedData->size() / FULL_SCREEN_WIDTH);
}
Example #17
0
bool NetSocket::PostSend()
{
    int status = _netStatus.load();
    int expected = status | NET_STATUS_CONNECTED & NET_STATUS_RECV_PENDING & (!NET_STATUS_SEND_PENDING);
    int desired = expected | NET_STATUS_SEND_PENDING;

    if (!_netStatus.compare_exchange_strong(expected, desired))
    {
        DebugPrint("PostSend: netStatus exchange failed: current(0x%x)", status);
        return false;
    }

    size_t sendQueueSize = _sendQueue.unsafe_size();
    if (sendQueueSize == 0)
    {
        DebugPrint("PostSend: send queue is empty.");
        return false;
    }

    NetIoBuffer* sendOP = new NetIoBuffer(NetCompletionOP::OP_WRITE);
    sendOP->Reset(GetSocket());

    std::vector<WSABUF> wbufs;
    wbufs.resize(sendQueueSize);

    MemoryBlock* buffer = nullptr;
    int idx = 0;
    while (_sendQueue.try_pop(buffer))
    {
        wbufs[idx].buf = buffer->GetData();
        wbufs[idx].len = buffer->GetDataLen();
        sendOP->PushData(buffer);
        idx++;
    }

    int rc = WSASend(
        GetSocket(),
        &(wbufs[0]),
        static_cast<DWORD>(wbufs.size()),
        NULL,
        0,
        &(sendOP->ol),
        NULL
    );

    if (rc == SOCKET_ERROR)
    {
        if (WSAGetLastError() != WSA_IO_PENDING)
        {
            DebugPrint("PostSend: WSASend* failed: %s", SocketGetLastErrorString().c_str());
            Disconnect(NET_CTYPE_SYSTEM);
            delete sendOP;

            return false;
        }
    }

    return true;
}
Example #18
0
//==============================================================================
void AdmvAudioProcessor::getStateInformation (MemoryBlock& destData)
{
	uint8 version = getStateVersion();

	destData.ensureSize(sizeof(mState) + 1, false);
	destData.copyFrom(&version, 0, 1);
	destData.copyFrom(&mState, 1, sizeof(mState));
}
Example #19
0
const MemoryBlock CtrlrMIDITransaction::getDataFromResponse(const MidiMessage &messageToExtractFrom)
{
	MemoryBlock returnData;
	MemoryBlock temp(messageToExtractFrom.getRawData(), messageToExtractFrom.getRawDataSize());

	returnData.copyFrom (temp.getData(), getResponsePrefixLength(), getResponseDataLength());
	return (returnData);
}
Example #20
0
/**
 * Append another block.
 */
void IOStack::PrependBlock() {
  MemoryBlock *block = m_pool->Allocate();
  if (!block) {
    OLA_FATAL << "Failed to allocate block, we're out of memory!";
  }
  block->SeekBack();  // put the block into prepend mode
  m_blocks.push_front(block);
}
Example #21
0
Uuid& Uuid::operator= (const String& uuidString)
{
    MemoryBlock mb;
    mb.loadFromHexString (uuidString);
    mb.ensureSize (sizeof (uuid), true);
    mb.copyTo (uuid, 0, sizeof (uuid));
    return *this;
}
Example #22
0
    void openHTTPConnection (URL_COMPONENTS& uc, URL::OpenStreamProgressCallback* progressCallback,
                             void* progressCallbackContext)
    {
        const TCHAR* mimeTypes[] = { _T("*/*"), 0 };

        DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;

        if (address.startsWithIgnoreCase ("https:"))
            flags |= INTERNET_FLAG_SECURE;  // (this flag only seems necessary if the OS is running IE6 -
                                            //  IE7 seems to automatically work out when it's https)

        request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
                                   uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);

        if (request != 0)
        {
            INTERNET_BUFFERS buffers = { 0 };
            buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
            buffers.lpcszHeader = headers.toWideCharPointer();
            buffers.dwHeadersLength = (DWORD) headers.length();
            buffers.dwBufferTotal = (DWORD) postData.getSize();

            if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
            {
                int bytesSent = 0;

                for (;;)
                {
                    const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
                    DWORD bytesDone = 0;

                    if (bytesToDo > 0
                         && ! InternetWriteFile (request,
                                                 static_cast <const char*> (postData.getData()) + bytesSent,
                                                 (DWORD) bytesToDo, &bytesDone))
                    {
                        break;
                    }

                    if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
                    {
                        if (HttpEndRequest (request, 0, 0, 0))
                            return;

                        break;
                    }

                    bytesSent += bytesDone;

                    if (progressCallback != nullptr
                          && ! progressCallback (progressCallbackContext, bytesSent, (int) postData.getSize()))
                        break;
                }
            }
        }

        close();
    }
Example #23
0
    //==============================================================================
    void getStateInformation (MemoryBlock& destData)
    {
        destData.setSize (sizeof (float) * getNumParameters());
        destData.fillWith (0);

        float* const p = (float*) ((char*) destData.getData());
        for (int i = 0; i < getNumParameters(); ++i)
            p[i] = getParameter(i);
    }
Example #24
0
const String imageToBase64 (const Image &image)
{
	MemoryBlock memoryBlock;
	MemoryOutputStream memoryStream(memoryBlock,true);
	PNGImageFormat png;
	png.writeImageToStream (image, memoryStream);

	return (memoryBlock.toBase64Encoding());
}
Example #25
0
void ProgramListBox::itemDropped(const SourceDetails& dragSourceDetails) {
    dragCandidate = programPosition(dragSourceDetails.localPosition.x, dragSourceDetails.localPosition.y);
    
    MemoryBlock* block = dragSourceDetails.description.getBinaryData();
    if ( listener != nullptr )
        listener->programDragged(this, dragCandidate, (char *)block->getData());
    dragCandidate = -1;
    repaint();
}
void LashManager::saveState (const File& fileToSave)
{
    MemoryBlock fileData;
    filter->getStateInformation (fileData);

    if (fileToSave.replaceWithData (fileData.getData (), fileData.getSize()))
    {
    }
}
Example #27
0
MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
                                      const bool keepInternalCopy)
    : data (sourceData.getData()),
      dataSize (sourceData.getSize()),
      position (0)
{
    if (keepInternalCopy)
        createInternalCopy();
}
//==============================================================================
void LashManager::loadState (const File& fileToLoad)
{
    MemoryBlock fileData;

    if (fileToLoad.existsAsFile()
        && fileToLoad.loadFileAsData (fileData))
    {
        filter->setStateInformation (fileData.getData (), fileData.getSize());
    }
}
Example #29
0
LMemoryBlock LMemoryBlock::getRange(const int startingPosition, const int numBytes) const
{
	MemoryBlock bl;

	if (getSize() >= (startingPosition + numBytes))
	{
		bl.append ((uint8 *)getData() + startingPosition, numBytes);
	}
	return (bl);
}
    //==============================================================================
    WebInputStream (String address, bool isPost, const MemoryBlock& postData,
                    URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
                    const String& headers, int timeOutMs, StringPairArray* responseHeaders)
    {
        if (! address.contains ("://"))
            address = "http://" + address;

        JNIEnv* env = getEnv();

        jbyteArray postDataArray = 0;

        if (postData.getSize() > 0)
        {
            postDataArray = env->NewByteArray (postData.getSize());
            env->SetByteArrayRegion (postDataArray, 0, postData.getSize(), (const jbyte*) postData.getData());
        }

        LocalRef<jobject> responseHeaderBuffer (env->NewObject (StringBuffer, StringBuffer.constructor));

        stream = GlobalRef (env->CallStaticObjectMethod (BeastAppActivity,
                                                         BeastAppActivity.createHTTPStream,
                                                         javaString (address).get(),
                                                         (jboolean) isPost,
                                                         postDataArray,
                                                         javaString (headers).get(),
                                                         (jint) timeOutMs,
                                                         responseHeaderBuffer.get()));

        if (postDataArray != 0)
            env->DeleteLocalRef (postDataArray);

        if (stream != 0)
        {
            StringArray headerLines;

            {
                LocalRef<jstring> headersString ((jstring) env->CallObjectMethod (responseHeaderBuffer.get(),
                                                                                  StringBuffer.toString));
                headerLines.addLines (beastString (env, headersString));
            }

            if (responseHeaders != 0)
            {
                for (int i = 0; i < headerLines.size(); ++i)
                {
                    const String& header = headerLines[i];
                    const String key (header.upToFirstOccurrenceOf (": ", false, false));
                    const String value (header.fromFirstOccurrenceOf (": ", false, false));
                    const String previousValue ((*responseHeaders) [key]);

                    responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
                }
            }
        }
    }