bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples) { jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0); if (numSamples <= 0) return true; HeapBlock<int> tempBuffer; HeapBlock<int*> chans (numChannels + 1); chans [numChannels] = 0; if (isFloatingPoint()) { for (int i = (int) numChannels; --i >= 0;) chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample)); } else { tempBuffer.malloc (numSamples * numChannels); for (unsigned int i = 0; i < numChannels; ++i) { typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType; typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType; DestSampleType destData (chans[i] = tempBuffer + i * numSamples); SourceSampleType sourceData (source.getSampleData ((int) i, startSample)); destData.convertSamples (sourceData, numSamples); } } return write ((const int**) chans.getData(), numSamples); }
static int getNumChannels (AudioDeviceID deviceID, bool input) { int total = 0; UInt32 size; AudioObjectPropertyAddress pa; pa.mSelector = kAudioDevicePropertyStreamConfiguration; pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; pa.mElement = kAudioObjectPropertyElementMaster; if (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr) { HeapBlock <AudioBufferList> bufList; bufList.calloc (size, 1); if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList) == noErr) { const int numStreams = bufList->mNumberBuffers; for (int i = 0; i < numStreams; ++i) { const AudioBuffer& b = bufList->mBuffers[i]; total += b.mNumberChannels; } } } return total; }
void OutputStream::printf (const char* pf, ...) { unsigned int bufSize = 256; HeapBlock <char> buf (bufSize); for (;;) { va_list list; va_start (list, pf); const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list); va_end (list); if (num > 0) { write (buf, num); break; } else if (num == 0) { break; } bufSize += 256; buf.malloc (bufSize); } }
//============================================================================== // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events void juce_handleSelectionRequest (XSelectionRequestEvent &evt) { ClipboardHelpers::initSelectionAtoms(); // the selection content is sent to the target window as a window property XSelectionEvent reply; reply.type = SelectionNotify; reply.display = evt.display; reply.requestor = evt.requestor; reply.selection = evt.selection; reply.target = evt.target; reply.property = None; // == "fail" reply.time = evt.time; HeapBlock <char> data; int propertyFormat = 0, numDataItems = 0; if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD) { if (evt.target == XA_STRING || evt.target == ClipboardHelpers::atom_UTF8_STRING) { // translate to utf8 numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1; data.calloc (numDataItems + 1); ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems); propertyFormat = 8; // bits/item } else if (evt.target == ClipboardHelpers::atom_TARGETS) { // another application wants to know what we are able to send numDataItems = 2; propertyFormat = 32; // atoms are 32-bit data.calloc (numDataItems * 4); Atom* atoms = reinterpret_cast<Atom*> (data.getData()); atoms[0] = ClipboardHelpers::atom_UTF8_STRING; atoms[1] = XA_STRING; } } else { DBG ("requested unsupported clipboard"); } if (data != nullptr) { const int maxReasonableSelectionSize = 1000000; // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss if (evt.property != None && numDataItems < maxReasonableSelectionSize) { XChangeProperty (evt.display, evt.requestor, evt.property, evt.target, propertyFormat /* 8 or 32 */, PropModeReplace, reinterpret_cast<const unsigned char*> (data.getData()), numDataItems); reply.property = evt.property; // " == success" } } XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply); }
//===================================================================================================== // Free //===================================================================================================== void LargeHeapBucket::ExplicitFree(void * object, size_t sizeCat) { Assert(HeapInfo::GetMediumObjectAlignedSizeNoCheck(sizeCat) == this->sizeCat); LargeObjectHeader * header = LargeHeapBlock::GetHeaderFromAddress(object); Assert(header->GetAttributes(this->heapInfo->recycler->Cookie) == ObjectInfoBits::NoBit || header->GetAttributes(this->heapInfo->recycler->Cookie) == ObjectInfoBits::LeafBit); Assert(!header->isExplicitFreed); DebugOnly(header->isExplicitFreed = true); Assert(header->objectSize >= sizeCat); #if DBG HeapBlock* heapBlock = this->GetRecycler()->FindHeapBlock(object); Assert(heapBlock != nullptr); Assert(heapBlock->IsLargeHeapBlock()); LargeHeapBlock * largeHeapBlock = (LargeHeapBlock *)heapBlock; LargeObjectHeader * dbgHeader; Assert(largeHeapBlock->GetObjectHeader(object, &dbgHeader)); Assert(dbgHeader == header); #endif FreeObject * freeObject = (FreeObject *)object; freeObject->SetNext(this->explicitFreeList); this->explicitFreeList = freeObject; header->SetAttributes(this->heapInfo->recycler->Cookie, ObjectInfoBits::LeafBit); // We can stop scanning it now. }
static ptr update( const ptr &p, const HeapBlock *const &oldP, const InitData &id ) { HeapBlock *t = (HeapBlock*)p; if( t != oldP ) { t->fix(id); } else t->Size = id.RequiredMemory(); //leave the callstack as is, err.. easier, other wise we may have to realllocate return t->retPtr(); }
ID3D11Texture2D* D3D11Context::createTexture2DFromAppData (const char* id) { int dataSize; const char* data = demo_->appDataGet (id, dataSize); if (nullptr == data) return nullptr; juce::Image img = ImageCache::getFromMemory (data, dataSize); if (!img.isValid()) return nullptr; int w = img.getWidth(); int h = img.getHeight(); if ((w % 2) > 0 || (h % 2) > 0) { w = (w % 2) > 0 ? (w + 1) : w; h = (h % 2) > 0 ? (h + 1) : h; img = img.rescaled (w, h); } img = img.convertedToFormat (juce::Image::ARGB); HeapBlock<uint8> mem (w * h * 4); memset (mem.getData(), 0xff, w * h * 4); juce::Image::BitmapData imgData (img, juce::Image::BitmapData::readOnly); uint8* src = imgData.data; uint8* dst = mem.getData(); size_t rowPitch = (size_t)w * 4; for (int r = 0; r < h; ++r) { uint8* s = src; uint8* d = dst; for (int c = 0; c < w; ++c) { d[0] = s[2]; d[1] = s[1]; d[2] = s[0]; d[3] = s[3]; s += 4; d += 4; } src += imgData.lineStride; dst += rowPitch; } Hold<ID3D11Texture2D> texture; if (texture.set (createTexture2D (w, h, 1, DXGI_FORMAT_R8G8B8A8_UNORM, mem.getData(), rowPitch, h * rowPitch)).isNull()) return nullptr; return texture.drop(); }
bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples) { if (audioSource == 0) return false; ScopedPointer<AudioSource> source (audioSource); long bytesPerBlock; HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock); const int samplesPerBlock = bytesPerBlock / 4; bool ok = true; hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4)); HeapBlock <byte> buffer (bytesPerBlock); AudioSampleBuffer sourceBuffer (2, samplesPerBlock); int samplesDone = 0; source->prepareToPlay (samplesPerBlock, 44100.0); while (ok) { { AudioSourceChannelInfo info; info.buffer = &sourceBuffer; info.numSamples = samplesPerBlock; info.startSample = 0; sourceBuffer.clear(); source->getNextAudioBlock (info); } buffer.clear (bytesPerBlock); typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> CDSampleFormat; typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat; CDSampleFormat left (buffer, 2); left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock); CDSampleFormat right (buffer + 2, 2); right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock); hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock); if (FAILED (hr)) ok = false; samplesDone += samplesPerBlock; if (samplesDone >= numSamples) break; } hr = pimpl->redbook->CloseAudioTrack(); return ok && hr == S_OK; }
void MidiOutput::sendMessageNow (const MidiMessage& message) { #if JUCE_IOS const MIDITimeStamp timeStamp = mach_absolute_time(); #else const MIDITimeStamp timeStamp = AudioGetCurrentHostTime(); #endif HeapBlock<MIDIPacketList> allocatedPackets; MIDIPacketList stackPacket; MIDIPacketList* packetToSend = &stackPacket; const size_t dataSize = (size_t) message.getRawDataSize(); if (message.isSysEx()) { const int maxPacketSize = 256; int pos = 0, bytesLeft = (int) dataSize; const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize; allocatedPackets.malloc ((size_t) (32 * (size_t) numPackets + dataSize), 1); packetToSend = allocatedPackets; packetToSend->numPackets = (UInt32) numPackets; MIDIPacket* p = packetToSend->packet; for (int i = 0; i < numPackets; ++i) { p->timeStamp = timeStamp; p->length = (UInt16) jmin (maxPacketSize, bytesLeft); memcpy (p->data, message.getRawData() + pos, p->length); pos += p->length; bytesLeft -= p->length; p = MIDIPacketNext (p); } } else if (dataSize < 65536) // max packet size { const size_t stackCapacity = sizeof (stackPacket.packet->data); if (dataSize > stackCapacity) { allocatedPackets.malloc ((sizeof (MIDIPacketList) - stackCapacity) + dataSize, 1); packetToSend = allocatedPackets; } packetToSend->numPackets = 1; MIDIPacket& p = *(packetToSend->packet); p.timeStamp = timeStamp; p.length = (UInt16) dataSize; memcpy (p.data, message.getRawData(), dataSize); } else { jassertfalse; // packet too large to send! return; } static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal)->send (packetToSend); }
int MultiHeap::GetSizeForPtr(void* pObj) { HeapBlock* pBlock = HeapBlock::ObjPointerToHeapBlock(pObj); if (pBlock == 0) return -1; return pBlock->GetObjSize(); }
static void printAll(bool unloadSymbolsAfter) { if(Last) { SymbolMan sm(unloadSymbolsAfter); for( HeapBlock* h = Last; h; h = h->Prev ) h->print(sm); Beep( 8000, 400 ); Beep( 4000, 500 ); } }
//============================================================================== void scanForDevices() { hasScanned = true; inputDeviceNames.clear(); outputDeviceNames.clear(); inputIds.clear(); outputIds.clear(); UInt32 size; AudioObjectPropertyAddress pa; pa.mSelector = kAudioHardwarePropertyDevices; pa.mScope = kAudioObjectPropertyScopeWildcard; pa.mElement = kAudioObjectPropertyElementMaster; if (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size) == noErr) { HeapBlock <AudioDeviceID> devs; devs.calloc (size, 1); if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs) == noErr) { const int num = size / (int) sizeof (AudioDeviceID); for (int i = 0; i < num; ++i) { char name [1024]; size = sizeof (name); pa.mSelector = kAudioDevicePropertyDeviceName; if (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name) == noErr) { const String nameString (String::fromUTF8 (name, (int) strlen (name))); const int numIns = getNumChannels (devs[i], true); const int numOuts = getNumChannels (devs[i], false); if (numIns > 0) { inputDeviceNames.add (nameString); inputIds.add (devs[i]); } if (numOuts > 0) { outputDeviceNames.add (nameString); outputIds.add (devs[i]); } } } } } inputDeviceNames.appendNumbersToDuplicates (false, true); outputDeviceNames.appendNumbersToDuplicates (false, true); }
static int findLongestCommonSubstring (String::CharPointerType a, const int lenA, const String::CharPointerType b, const int lenB, int& indexInA, int& indexInB) { if (lenA == 0 || lenB == 0) return 0; HeapBlock<int> lines; lines.calloc (2 + 2 * (size_t) lenB); int* l0 = lines; int* l1 = l0 + lenB + 1; int loopsWithoutImprovement = 0; int bestLength = 0; indexInA = indexInB = 0; for (int i = 0; i < lenA; ++i) { const juce_wchar ca = a.getAndAdvance(); String::CharPointerType b2 (b); for (int j = 0; j < lenB; ++j) { if (ca != b2.getAndAdvance()) { l1[j + 1] = 0; } else { const int len = l0[j] + 1; l1[j + 1] = len; if (len > bestLength) { loopsWithoutImprovement = 0; bestLength = len; indexInA = i; indexInB = j; } } } if (++loopsWithoutImprovement > 100) break; std::swap (l0, l1); } indexInA -= bestLength - 1; indexInB -= bestLength - 1; return bestLength; }
//============================================================================== String SystemStats::getStackBacktrace() { String result; #if JUCE_ANDROID || JUCE_MINGW || JUCE_HAIKU jassertfalse; // sorry, not implemented yet! #elif JUCE_WINDOWS HANDLE process = GetCurrentProcess(); SymInitialize (process, nullptr, TRUE); void* stack[128]; int frames = (int) CaptureStackBackTrace (0, numElementsInArray (stack), stack, nullptr); HeapBlock<SYMBOL_INFO> symbol; symbol.calloc (sizeof (SYMBOL_INFO) + 256, 1); symbol->MaxNameLen = 255; symbol->SizeOfStruct = sizeof (SYMBOL_INFO); for (int i = 0; i < frames; ++i) { DWORD64 displacement = 0; if (SymFromAddr (process, (DWORD64) stack[i], &displacement, symbol)) { result << i << ": "; IMAGEHLP_MODULE64 moduleInfo; zerostruct (moduleInfo); moduleInfo.SizeOfStruct = sizeof (moduleInfo); if (::SymGetModuleInfo64 (process, symbol->ModBase, &moduleInfo)) result << moduleInfo.ModuleName << ": "; result << symbol->Name << " + 0x" << String::toHexString ((int64) displacement) << newLine; } } #else void* stack[128]; int frames = backtrace (stack, numElementsInArray (stack)); char** frameStrings = backtrace_symbols (stack, frames); for (int i = 0; i < frames; ++i) result << frameStrings[i] << newLine; ::free (frameStrings); #endif return result; }
void receive (jbyteArray byteArray, jlong offset, jint len, jlong timestamp) { jassert (byteArray != nullptr); jbyte* data = getEnv()->GetByteArrayElements (byteArray, nullptr); HeapBlock<uint8> buffer (len); std::memcpy (buffer.getData(), data + offset, len); midiConcatenator.pushMidiData (buffer.getData(), len, static_cast<double> (timestamp) * 1.0e-9, juceMidiInput, *callback); getEnv()->ReleaseByteArrayElements (byteArray, data, 0); }
void scanFileForDetails() { ComSmartPtr<IWMHeaderInfo> wmHeaderInfo; HRESULT hr = wmSyncReader.QueryInterface (wmHeaderInfo); if (SUCCEEDED (hr)) { QWORD lengthInNanoseconds = 0; WORD lengthOfLength = sizeof (lengthInNanoseconds); WORD streamNum = 0; WMT_ATTR_DATATYPE wmAttrDataType; hr = wmHeaderInfo->GetAttributeByName (&streamNum, L"Duration", &wmAttrDataType, (BYTE*) &lengthInNanoseconds, &lengthOfLength); ComSmartPtr<IWMProfile> wmProfile; hr = wmSyncReader.QueryInterface (wmProfile); if (SUCCEEDED (hr)) { ComSmartPtr<IWMStreamConfig> wmStreamConfig; hr = wmProfile->GetStream (0, wmStreamConfig.resetAndGetPointerAddress()); if (SUCCEEDED (hr)) { ComSmartPtr<IWMMediaProps> wmMediaProperties; hr = wmStreamConfig.QueryInterface (wmMediaProperties); if (SUCCEEDED (hr)) { DWORD sizeMediaType; hr = wmMediaProperties->GetMediaType (0, &sizeMediaType); HeapBlock<WM_MEDIA_TYPE> mediaType; mediaType.malloc (sizeMediaType, 1); hr = wmMediaProperties->GetMediaType (mediaType, &sizeMediaType); if (mediaType->majortype == WMMEDIATYPE_Audio) { const WAVEFORMATEX* const inputFormat = reinterpret_cast<WAVEFORMATEX*> (mediaType->pbFormat); sampleRate = inputFormat->nSamplesPerSec; numChannels = inputFormat->nChannels; bitsPerSample = inputFormat->wBitsPerSample; lengthInSamples = (lengthInNanoseconds * (int) sampleRate) / 10000000; } } } } } }
void FFT::performRealOnlyInverseTransform (float* d) const noexcept { const size_t scratchSize = 16 + sizeof (FFT::Complex) * (size_t) size; if (scratchSize < maxFFTScratchSpaceToAlloca) { performRealOnlyInverseTransform (static_cast<Complex*> (alloca (scratchSize)), d); } else { HeapBlock<char> heapSpace (scratchSize); performRealOnlyInverseTransform (reinterpret_cast<Complex*> (heapSpace.getData()), d); } }
WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_, URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext, const String& headers_, int timeOutMs_, StringPairArray* responseHeaders) : statusCode (0), connection (0), request (0), address (address_), headers (headers_), postData (postData_), position (0), finished (false), isPost (isPost_), timeOutMs (timeOutMs_) { createConnection (progressCallback, progressCallbackContext); if (! isError()) { if (responseHeaders != nullptr) { DWORD bufferSizeBytes = 4096; for (;;) { HeapBlock<char> buffer ((size_t) bufferSizeBytes); if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0)) { StringArray headersArray; headersArray.addLines (String (reinterpret_cast<const WCHAR*> (buffer.getData()))); for (int i = 0; i < headersArray.size(); ++i) { const String& header = headersArray[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)); } break; } if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) break; } } DWORD status = 0; DWORD statusSize = sizeof (status); if (HttpQueryInfo (request, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &status, &statusSize, 0)) statusCode = (int) status; } }
String getDriveFromPath (String path) { if (path.isNotEmpty() && path[1] == ':' && path[2] == 0) path << '\\'; const size_t numBytes = CharPointer_UTF16::getBytesRequiredFor (path.getCharPointer()) + 4; HeapBlock<WCHAR> pathCopy; pathCopy.calloc (numBytes, 1); path.copyToUTF16 (pathCopy, numBytes); if (PathStripToRoot (pathCopy)) path = static_cast <const WCHAR*> (pathCopy); return path; }
// Produce the pseudo-random set of records. static void createRecords (HeapBlock <Record>& records, int numRecords, int maxBytes, std::int64_t seedValue) { using namespace UnitTestUtilities; Random r (seedValue); records.malloc (numRecords); int offset = 0; for (int i = 0; i < numRecords; ++i) { int const bytes = r.nextInt (maxBytes) + 1; records [i].index = i; records [i].bytes = bytes; records [i].offset = offset; offset += bytes; } repeatableShuffle (numRecords, records, seedValue); }
static bool isBlockListPagedOut(double deadline, DoublyLinkedList<HeapBlock>* list) { unsigned itersSinceLastTimeCheck = 0; HeapBlock* current = list->head(); while (current) { current = current->next(); ++itersSinceLastTimeCheck; if (itersSinceLastTimeCheck >= Heap::s_timeCheckResolution) { double currentTime = WTF::monotonicallyIncreasingTime(); if (currentTime > deadline) return true; itersSinceLastTimeCheck = 0; } } return false; }
bool MarkedAllocator::isPagedOut(double deadline) { unsigned itersSinceLastTimeCheck = 0; HeapBlock* block = m_blockList.head(); while (block) { block = block->next(); ++itersSinceLastTimeCheck; if (itersSinceLastTimeCheck >= Heap::s_timeCheckResolution) { double currentTime = WTF::monotonicallyIncreasingTime(); if (currentTime > deadline) return true; itersSinceLastTimeCheck = 0; } } return false; }
float getStringWidth (const String& text) { const CharPointer_UTF16 utf16 (text.toUTF16()); const size_t numChars = utf16.length(); HeapBlock<int16> results (numChars + 1); results[numChars] = -1; float x = 0; if (GetGlyphIndices (dc, utf16, (int) numChars, reinterpret_cast <WORD*> (results.getData()), GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR) { for (size_t i = 0; i < numChars; ++i) x += getKerning (dc, results[i], results[i + 1]); } return x; }
int doFTime (CharPointer_UTF32 dest, const size_t maxChars, const String& format, const struct tm* const tm) noexcept { #if JUCE_ANDROID HeapBlock <char> tempDest; tempDest.calloc (maxChars + 2); const int result = (int) strftime (tempDest, maxChars, format.toUTF8(), tm); if (result > 0) dest.writeAll (CharPointer_UTF8 (tempDest.getData())); return result; #elif JUCE_WINDOWS HeapBlock <wchar_t> tempDest; tempDest.calloc (maxChars + 2); const int result = (int) wcsftime (tempDest, maxChars, format.toWideCharPointer(), tm); if (result > 0) dest.writeAll (CharPointer_UTF16 (tempDest.getData())); return result; #else return (int) wcsftime (dest.getAddress(), maxChars, format.toUTF32(), tm); #endif }
CoreAudioInternal* getRelatedDevice() const { UInt32 size = 0; ScopedPointer <CoreAudioInternal> result; AudioObjectPropertyAddress pa; pa.mSelector = kAudioDevicePropertyRelatedDevices; pa.mScope = kAudioObjectPropertyScopeWildcard; pa.mElement = kAudioObjectPropertyElementMaster; if (deviceID != 0 && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr && size > 0) { HeapBlock <AudioDeviceID> devs; devs.calloc (size, 1); if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs))) { for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i) { if (devs[i] != deviceID && devs[i] != 0) { result = new CoreAudioInternal (devs[i]); const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0; const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0; if (thisIsInput != otherIsInput || (inChanNames.size() + outChanNames.size() == 0) || (result->inChanNames.size() + result->outChanNames.size()) == 0) break; result = 0; } } } } return result.release(); }
int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const { JUCE_COLOURGRADIENT_CHECK_COORDS_INITIALISED // Trying to use this object without setting its coordinates? jassert (colours.size() >= 2); const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8), 3 * (int) point1.transformedBy (transform) .getDistanceFrom (point2.transformedBy (transform))); lookupTable.malloc ((size_t) numEntries); createLookupTable (lookupTable, numEntries); return numEntries; }
int64 calculateStreamHashCode (InputStream& in) { int64 t = 0; const int bufferSize = 4096; HeapBlock <uint8> buffer; buffer.malloc (bufferSize); for (;;) { const int num = in.read (buffer, bufferSize); if (num <= 0) break; for (int i = 0; i < num; ++i) t = t * 65599 + buffer[i]; } return t; }
static String parseNameRecord (MemoryInputStream& input, const NameRecord& nameRecord, const int64 directoryOffset, const int64 offsetOfStringStorage) { String result; const int64 oldPos = input.getPosition(); input.setPosition (directoryOffset + offsetOfStringStorage + ByteOrder::swapIfLittleEndian (nameRecord.offsetFromStorageArea)); const int stringLength = (int) ByteOrder::swapIfLittleEndian (nameRecord.stringLength); const int platformID = ByteOrder::swapIfLittleEndian (nameRecord.platformID); if (platformID == 0 || platformID == 3) { const int numChars = stringLength / 2 + 1; HeapBlock<uint16> buffer; buffer.calloc (numChars + 1); input.read (buffer, stringLength); for (int i = 0; i < numChars; ++i) buffer[i] = ByteOrder::swapIfLittleEndian (buffer[i]); static_jassert (sizeof (CharPointer_UTF16::CharType) == sizeof (uint16)); result = CharPointer_UTF16 ((CharPointer_UTF16::CharType*) buffer.getData()); } else { HeapBlock<char> buffer; buffer.calloc (stringLength + 1); input.read (buffer, stringLength); result = CharPointer_UTF8 (buffer.getData()); } input.setPosition (oldPos); return result; }
void MidiOutput::sendMessageNow (const MidiMessage& message) { CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal); if (message.isSysEx()) { const int maxPacketSize = 256; int pos = 0, bytesLeft = message.getRawDataSize(); const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize; HeapBlock <MIDIPacketList> packets; packets.malloc (32 * numPackets + message.getRawDataSize(), 1); packets->numPackets = numPackets; MIDIPacket* p = packets->packet; for (int i = 0; i < numPackets; ++i) { p->timeStamp = 0; p->length = jmin (maxPacketSize, bytesLeft); memcpy (p->data, message.getRawData() + pos, p->length); pos += p->length; bytesLeft -= p->length; p = MIDIPacketNext (p); } mpe->send (packets); } else { MIDIPacketList packets; packets.numPackets = 1; packets.packet[0].timeStamp = 0; packets.packet[0].length = message.getRawDataSize(); *(int*) (packets.packet[0].data) = *(const int*) message.getRawData(); mpe->send (&packets); } }
void butterfly2 (Complex<float>* data, const int stride, const int length) const noexcept { auto* dataEnd = data + length; auto* tw = twiddleTable.getData(); for (int i = length; --i >= 0;) { auto s = *dataEnd; s *= (*tw); tw += stride; *dataEnd++ = *data - s; *data++ += s; } }