void* SqliteResultSet::GetResultBlob(int nField, wxMemoryBuffer& Buffer) { int nLength = 0; if (m_pSqliteStatement == NULL) m_pSqliteStatement = m_pStatement->GetLastStatement(); nLength = sqlite3_column_bytes(m_pSqliteStatement, nField-1); if (nLength < 1) { wxMemoryBuffer tempBuffer(0); tempBuffer.SetDataLen(0); tempBuffer.SetBufSize(0); Buffer = tempBuffer; return NULL; } const void* pBlob = sqlite3_column_blob(m_pSqliteStatement, nField-1); wxMemoryBuffer tempBuffer(nLength); void* pBuffer = tempBuffer.GetWriteBuf(nLength); memcpy(pBuffer, pBlob, nLength); tempBuffer.UngetWriteBuf(nLength); tempBuffer.SetDataLen(nLength); tempBuffer.SetBufSize(nLength); Buffer = tempBuffer; return Buffer.GetData(); }
// Note: if the newSize == kReadToEnd (0), this function will read to the end of stream. bool bufferMoreData(size_t newSize) { if (newSize == kReadToEnd) { if (fWholeStreamRead) { // already read-to-end. return true; } // TODO: optimize for the special case when the input is SkMemoryStream. return SkStreamCopy(&fStreamBuffer, fStream.get()); } if (newSize <= fStreamBuffer.bytesWritten()) { // already buffered to newSize return true; } if (fWholeStreamRead) { // newSize is larger than the whole stream. return false; } // Try to read at least 8192 bytes to avoid to many small reads. const size_t kMinSizeToRead = 8192; const size_t sizeRequested = newSize - fStreamBuffer.bytesWritten(); const size_t sizeToRead = SkTMax(kMinSizeToRead, sizeRequested); SkAutoSTMalloc<kMinSizeToRead, uint8> tempBuffer(sizeToRead); const size_t bytesRead = fStream->read(tempBuffer.get(), sizeToRead); if (bytesRead < sizeRequested) { return false; } return fStreamBuffer.write(tempBuffer.get(), bytesRead); }
void RVolume::loadRawFile(std::string filename, size_t width, size_t height, size_t depth, size_t bytes) { std::ifstream file(filename.c_str(), std::ifstream::binary); std::vector<GLubyte> inbuffer(width * height * depth); switch (bytes) { case 1: { file.read(reinterpret_cast<char*>(&inbuffer[0]), inbuffer.size()); if (file.fail()) M_throw() << "Failed to load the texture from the file"; } break; case 2: { std::vector<uint16_t> tempBuffer(width * height * depth); file.read(reinterpret_cast<char*>(&tempBuffer[0]), 2 * tempBuffer.size()); if (file.fail()) M_throw() << "Failed to load the texture from the file"; for (size_t i(0); i < tempBuffer.size(); ++i) inbuffer[i] = uint8_t(tempBuffer[i] >> 8); } break; default: M_throw() << "Cannot load at that bit depth yet"; } loadData(inbuffer, width, height, depth); }
JNIH_EXCEPTION_TRAP_BEGIN() { JByteArray jInBuffer(env, inBuffer); JByteArray tempBuffer(env, inBufferLength); jsize outBufferLength = inBufferLength; jboolean result = SCompCompress( tempBuffer.getData(), reinterpret_cast<int*>(&outBufferLength), (jInBuffer.getData() + inBufferOffset), inBufferLength, compressionMask, 0, compressionLevel ); if (!result) { ErrorCodeToException(env, GetLastError()); } else { JByteArray outBuffer(env, outBufferLength); memcpy(outBuffer.getData(), tempBuffer.getData(), outBufferLength); return outBuffer.getArray(); } } JNIH_EXCEPTION_TRAP_END
bool AudioFileTest::convertTest() { AudioBuffer buffer, tempBuffer(2); MultiFormatAudioFilePtr file = MultiFormatAudioFilePtr(new MultiFormatAudioFile()); Path sourcePath = basePath_ / "sinus_pcm16_8000_2ch.wav"; file->open(sourcePath, AudioFile::OpenRead); file->load(&buffer); file->close(); if(buffer.hasData() == false) { return false; } // create test files // Path genPath = basePath_ / "gen"; for(unsigned i=0; i<fileInfos_.size(); ++i) { FileInfo& info = fileInfos_[i]; if(info.codecId_ == CODEC_GSM610) { int x = 0; } configureTestFile(file, info, genPath); file->open(file->getFilename(), MultiFormatAudioFile::OpenWrite); tempBuffer = buffer; tempBuffer.convertSampleRate(info.sampleRate_); file->store(&tempBuffer); file->close(); } return true; // reopen test files // bool result = true; for(unsigned i=0; i<fileInfos_.size(); ++i) { FileInfo& info = fileInfos_[i]; configureTestFile(file, info, genPath); file->open(file->getFilename(), AudioFile::OpenRead); file->load(&tempBuffer); result &= file->getSampleRate() == info.sampleRate_; result &= file->getNumChannels() == info.numChannels_; result &= file->getNumFrames() > 0; result &= file->getFormat().id_ == info.formatId_; result &= file->getCodec().id_ == info.codecId_; file->close(); if(result == false) return false; } return true; }
void* wxMysqlPreparedStatementResultSet::GetResultBlob(int nField, wxMemoryBuffer& Buffer) { void* pReturn = NULL; MYSQL_BIND* pResultBinding = GetResultBinding(nField); if (pResultBinding != NULL) { if ((*(pResultBinding->is_null) == false)) { unsigned long nBufferLength = 0; if (pResultBinding->length) nBufferLength = (*pResultBinding->length); else nBufferLength = pResultBinding->buffer_length; wxMemoryBuffer tempBuffer(nBufferLength); void* pBuffer = tempBuffer.GetWriteBuf(nBufferLength); memcpy(pBuffer, pResultBinding->buffer, nBufferLength); tempBuffer.UngetWriteBuf(nBufferLength); tempBuffer.SetDataLen(nBufferLength); tempBuffer.SetBufSize(nBufferLength); Buffer = tempBuffer; pReturn = Buffer.GetData(); } else { wxMemoryBuffer tempBuffer(0); tempBuffer.SetDataLen(0); tempBuffer.SetBufSize(0); Buffer = tempBuffer; } } else { wxMemoryBuffer tempBuffer(0); tempBuffer.SetDataLen(0); tempBuffer.SetBufSize(0); Buffer = tempBuffer; } return pReturn; }
void Circle::draw(DisplayBuffer &buffer) { int x = m_radius; int y = 0; int decisionOver2 = 1 - x; // Draw on a temp buffer and then bring over to the main buffer when done. // This is required at the moment since this circle drawing alg has a fair // amount of overdraw, and the Toggle drawmode wouldn't work with that. DisplayBuffer tempBuffer({ m_radius * 2 + 1, m_radius * 2 + 1 }); // Alg for drawing a circle while(y <= x) { int jump = m_filled ? 1 : (x * 2); for (int i = -x; i <= x; i += jump) { tempBuffer.set({ (double)i + m_radius, (double)y + m_radius }, DrawMode::Set); tempBuffer.set({ (double)i + m_radius, (double)-y + m_radius }, DrawMode::Set); tempBuffer.set({ (double)y + m_radius, (double)i + m_radius }, DrawMode::Set); tempBuffer.set({ (double)-y + m_radius, (double)i + m_radius }, DrawMode::Set); } y++; if (decisionOver2<=0) decisionOver2 += 2 * y + 1; else { x--; decisionOver2 += 2 * (y - x) + 1; } } // Copy the temp buffer over to the main buffer for (int x = 0; x < tempBuffer.getViewport().width; ++x) { for (int y = 0; y < tempBuffer.getViewport().height; ++y) { if (tempBuffer.get({ (double)x, (double)y })) { DisplayPoint point { x - m_radius + getPosition().x, y - m_radius + getPosition().y }; buffer.set(point, getDrawMode()); } } } }
qint64 QnxAudioInput::read(char *data, qint64 len) { int errorCode = 0; QByteArray tempBuffer(m_periodSize, 0); const int actualRead = snd_pcm_plugin_read(m_pcmHandle, tempBuffer.data(), m_periodSize); if (actualRead < 1) { snd_pcm_channel_status_t status; memset(&status, 0, sizeof(status)); status.channel = SND_PCM_CHANNEL_CAPTURE; if ((errorCode = snd_pcm_plugin_status(m_pcmHandle, &status)) < 0) { qWarning("QnxAudioInput: read error, couldn't get plugin status (0x%x)", -errorCode); close(); setError(QAudio::FatalError); setState(QAudio::StoppedState); return -1; } if (status.status == SND_PCM_STATUS_READY || status.status == SND_PCM_STATUS_OVERRUN) { if ((errorCode = snd_pcm_plugin_prepare(m_pcmHandle, SND_PCM_CHANNEL_CAPTURE)) < 0) { qWarning("QnxAudioInput: read error, couldn't prepare plugin (0x%x)", -errorCode); close(); setError(QAudio::FatalError); setState(QAudio::StoppedState); return -1; } } } else { setError(QAudio::NoError); setState(QAudio::ActiveState); } if (m_volume < 1.0f) QAudioHelperInternal::qMultiplySamples(m_volume, m_format, tempBuffer.data(), tempBuffer.data(), actualRead); m_bytesRead += actualRead; if (m_pullMode) { m_audioSource->write(tempBuffer.data(), actualRead); } else { memcpy(data, tempBuffer.data(), qMin(static_cast<qint64>(actualRead), len)); } m_bytesAvailable = 0; return actualRead; }
void ABSummer::Process(std::vector<Buffer>& argTargetBuffers) { // Define the Process() function for Summer class // Sums the input buffers and copies the value to all // buffers present in argTargetBuffers Buffer tempBuffer(bufferSize); // Generate the summed buffer for (int i=0; i<noInputBuffers; i++) tempBuffer.Add(inputBuffers[i]); // Assign the summed buffer to all output buffers (default one output buffer, but assigned to all just in case) for (int i=0; i<noOutputBuffers; i++) argTargetBuffers[i].Copy(tempBuffer); }
SINT AudioSource::readSampleFramesStereo( SINT numberOfFrames, CSAMPLE* sampleBuffer, SINT sampleBufferSize) { DEBUG_ASSERT(getSampleBufferSize(numberOfFrames, true) <= sampleBufferSize); switch (getChannelCount()) { case 1: // mono channel { const SINT readFrameCount = readSampleFrames( numberOfFrames, sampleBuffer); SampleUtil::doubleMonoToDualMono(sampleBuffer, readFrameCount); return readFrameCount; } case 2: // stereo channel(s) { return readSampleFrames(numberOfFrames, sampleBuffer); } default: // multiple (3 or more) channels { const SINT numberOfSamplesToRead = frames2samples(numberOfFrames); if (numberOfSamplesToRead <= sampleBufferSize) { // efficient in-place transformation const SINT readFrameCount = readSampleFrames( numberOfFrames, sampleBuffer); SampleUtil::copyMultiToStereo(sampleBuffer, sampleBuffer, readFrameCount, getChannelCount()); return readFrameCount; } else { // inefficient transformation through a temporary buffer qDebug() << "Performance warning:" << "Allocating a temporary buffer of size" << numberOfSamplesToRead << "for reading stereo samples." << "The size of the provided sample buffer is" << sampleBufferSize; SampleBuffer tempBuffer(numberOfSamplesToRead); const SINT readFrameCount = readSampleFrames( numberOfFrames, tempBuffer.data()); SampleUtil::copyMultiToStereo(sampleBuffer, tempBuffer.data(), readFrameCount, getChannelCount()); return readFrameCount; } } } }
void compress() { int bytes = buffer.size(); stream.write((char *) &bytes, sizeof(int)); if(!bytes) return; std::vector<char> tempBuffer(bytes + 12); Bytef *source = &buffer[0]; uLong sourceLength = buffer.size(); Bytef *destination = (Bytef *) &tempBuffer[0]; uLong destinationLength = tempBuffer.size(); int code = ::compress(destination, &destinationLength, source, sourceLength); if(code != Z_OK) int a = 0; stream.write(&tempBuffer[0], destinationLength); }
JNIH_EXCEPTION_TRAP_BEGIN() { JByteArray jInBuffer(env, inBuffer); JByteArray tempBuffer(env, outBufferLength); jint decompressedSize = outBufferLength; jboolean result = SCompExplode( tempBuffer.getData(), reinterpret_cast<int*>(&decompressedSize), (jInBuffer.getData() + inBufferOffset), inBufferLength ); if (!result) { ErrorCodeToException(env, GetLastError()); } else { JByteArray outBuffer(env, decompressedSize); memcpy(outBuffer.getData(), tempBuffer.getData(), decompressedSize); return outBuffer.getArray(); } } JNIH_EXCEPTION_TRAP_END
std::wstring toWideString(const char* utf8String) { int bufferSize = MultiByteToWideChar(CP_UTF8, // Code page 0, // Flags utf8String, // Input string -1, // Count, -1 for NUL-terminated NULL, // No output buffer 0 // Zero means "compute required size" ); if (bufferSize == 0) { return std::wstring(); } std::unique_ptr<wchar_t[]> tempBuffer(new wchar_t[bufferSize]); tempBuffer[0] = 0; MultiByteToWideChar(CP_UTF8, // Code page 0, // Flags utf8String, // Input string -1, // Count, -1 for NUL-terminated tempBuffer.get(), // UTF-16 output buffer bufferSize // Buffer size in wide characters ); return std::wstring(tempBuffer.get()); }
/** Returns the device type of the current device. This is different from the device type returned in GetDeviceDetails. GetDeviceDetails() returns the actual device type, this function returns the device type stored in the list (so a real device can be stored in the list as an invalid device). @return deviceType type of the current BT GPS device (value between 0-3) */ TInt CT_BTGPSDeviceListHandler::GetNextDeviceType() { //Read off the device type information (if present) TInt deviceType = 0; if(iCheckDeviceType) { TPtrC tempBuffer(iDeviceListConfig.iDeviceTypes.Right(iDeviceTypeBufferLength)); TInt endPosition = 0; //Find the next comma endPosition = tempBuffer.Find(_L(",")); if(endPosition == KErrNotFound) { //No more commas in the list, at the end of the file endPosition = tempBuffer.Length(); } TPtrC deviceTypeBuf(tempBuffer.Mid(0, endPosition)); iDeviceTypeBufferLength -= (endPosition + 1); if(iDeviceTypeBufferLength <= 0) { iCheckDeviceType = EFalse; } TLex lex(deviceTypeBuf); lex.SkipSpace(); lex.Val(deviceType); //Check the device type range if(deviceType < 0 || deviceType > 3) { //If the device type is out of the set range, just set it to an unknown device deviceType = 0; } } return deviceType; }
void generate(Type type, int resolution, int lodFactor_, bool leftLod, bool rightLod, bool upLod, bool downLod, unsigned char *clipBuffer) { faceAmount = 0; lodFactor = lodFactor_; int bufferSize = (resolution - 1) * (resolution - 1) * 6 * sizeof(short); indexBuffer.create((resolution - 1) * (resolution - 1) * 2, false); boost::scoped_array<unsigned short> tempBuffer(new unsigned short[bufferSize / sizeof(short)]); if(!tempBuffer) return; if(type == FullBuffer) generateCenter(tempBuffer.get(), resolution, clipBuffer); generateLink(tempBuffer.get(), resolution, leftLod, rightLod, upLod, downLod, clipBuffer); unsigned short *buffer = indexBuffer.lock(); memcpy(buffer, tempBuffer.get(), faceAmount * sizeof(short)); faceAmount /= 3; indexBuffer.unlock(); }
void* wxPostgresResultSet::GetResultBlob(int nField, wxMemoryBuffer& Buffer) { //int nLength = m_pInterface->GetPQgetlength()(m_pResult, m_nCurrentRow, nIndex); unsigned char* pBlob = (unsigned char*)m_pInterface->GetPQgetvalue()(m_pResult, m_nCurrentRow, nField-1); size_t nUnescapedLength = 0; unsigned char* pUnescapedBlob = m_pInterface->GetPQunescapeBytea()(pBlob, &nUnescapedLength); wxMemoryBuffer tempBuffer(nUnescapedLength); void* pUnescapedBuffer = tempBuffer.GetWriteBuf(nUnescapedLength); memcpy(pUnescapedBuffer, pUnescapedBlob, nUnescapedLength); m_pInterface->GetPQfreemem()(pUnescapedBlob); tempBuffer.UngetWriteBuf(nUnescapedLength); tempBuffer.SetBufSize(nUnescapedLength); tempBuffer.SetDataLen(nUnescapedLength); Buffer = tempBuffer; Buffer.UngetWriteBuf(nUnescapedLength); if (nUnescapedLength < 1) return NULL; return Buffer.GetData(); }
/////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Create an image with the specified size, colorspace and // bit depth // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// ptr<handlers::dataHandlerNumericBase> image::create( const imbxUint32 sizeX, const imbxUint32 sizeY, const bitDepth depth, std::wstring inputColorSpace, const imbxUint8 highBit) { PUNTOEXE_FUNCTION_START(L"image::create"); lockObject lockAccess(this); if(sizeX == 0 || sizeY == 0) { PUNTOEXE_THROW(imageExceptionInvalidSize, "An invalid image's size has been specified"); } // Normalize the color space (remove _420 & _422 and // make it uppercase). /////////////////////////////////////////////////////////// m_colorSpace=transforms::colorTransforms::colorTransformsFactory::normalizeColorSpace(inputColorSpace); // Find the number of channels to allocate /////////////////////////////////////////////////////////// m_channelsNumber = transforms::colorTransforms::colorTransformsFactory::getNumberOfChannels(inputColorSpace); if(m_channelsNumber == 0) { PUNTOEXE_THROW(imageExceptionUnknownColorSpace, "Cannot recognize the specified color space"); } // Find the datatype to use to allocate the // buffer (datatypes are in Dicom standard, plus SB // for signed bytes). /////////////////////////////////////////////////////////// m_channelPixelSize = 0; imbxUint8 defaultHighBit = 0; std::string bufferDataType; switch(depth) { case depthU8: bufferDataType = "OB"; defaultHighBit=7; break; case depthS8: bufferDataType = "SB"; defaultHighBit=7; break; case depthU16: bufferDataType = "US"; defaultHighBit=15; break; case depthS16: bufferDataType = "SS"; defaultHighBit=15; break; case depthU32: bufferDataType = "UL"; defaultHighBit=31; break; case depthS32: bufferDataType = "SL"; defaultHighBit=31; break; default: PUNTOEXE_THROW(imageExceptionUnknownDepth, "Unknown depth"); } // Adjust the high bit value /////////////////////////////////////////////////////////// if(highBit == 0 || highBit>defaultHighBit) m_highBit=defaultHighBit; else m_highBit=highBit; // If a valid buffer with the same data type is already // allocated then use it. /////////////////////////////////////////////////////////// if(m_buffer == 0 || !(m_buffer->isReferencedOnce()) ) { ptr<buffer> tempBuffer(new buffer(this, bufferDataType)); m_buffer = tempBuffer; } m_sizeX = m_sizeY = 0; ptr<handlers::dataHandler> imageHandler(m_buffer->getDataHandler(true, sizeX * sizeY * (imbxUint32)m_channelsNumber) ); if(imageHandler != 0) { m_rowLength = m_channelsNumber*sizeX; imageHandler->setSize(m_rowLength*sizeY); m_channelPixelSize = imageHandler->getUnitSize(); // Set the attributes /////////////////////////////////////////////////////////// m_imageDepth=depth; m_sizeX=sizeX; m_sizeY=sizeY; } return ptr<handlers::dataHandlerNumericBase>(dynamic_cast<handlers::dataHandlerNumericBase*>(imageHandler.get()) ); PUNTOEXE_FUNCTION_END(); }
/////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Create a data handler and connect it to the buffer // (raw or normal) // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// ptr<handlers::dataHandler> buffer::getDataHandler(bool bWrite, bool bRaw, imbxUint32 size) { PUNTOEXE_FUNCTION_START(L"buffer::getDataHandler"); // Lock the object /////////////////////////////////////////////////////////// lockObject lockAccess(this); ptr<memory> localMemory(m_memory); // If the object must be loaded from the original stream, // then load it... /////////////////////////////////////////////////////////// if(m_originalStream != 0 && (localMemory == 0 || localMemory->empty()) ) { localMemory = ptr<memory>(memoryPool::getMemoryPool()->getMemory(m_originalBufferLength)); if(m_originalBufferLength != 0) { ptr<streamReader> reader(new streamReader(m_originalStream, m_originalBufferPosition, m_originalBufferLength)); std::vector<imbxUint8> localBuffer; localBuffer.resize(m_originalBufferLength); reader->read(&localBuffer[0], m_originalBufferLength); if(m_originalWordLength != 0) { reader->adjustEndian(&localBuffer[0], m_originalWordLength, m_originalEndianType, m_originalBufferLength/m_originalWordLength); } localMemory->assign(&localBuffer[0], m_originalBufferLength); } } // Reset the pointer to the data handler /////////////////////////////////////////////////////////// ptr<handlers::dataHandler> handler; // Allocate a raw data handler if bRaw==true /////////////////////////////////////////////////////////// if(bRaw) { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerRaw); handler = tempHandler; } else { // Retrieve an Application entity handler /////////////////////////////////////////////////////////// if(m_bufferType=="AE") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringAE); handler = tempHandler; } // Retrieve an Age string data handler /////////////////////////////////////////////////////////// if(m_bufferType=="AS") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringAS); handler = tempHandler; } // Retrieve a Code string data handler /////////////////////////////////////////////////////////// if(m_bufferType=="CS") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringCS); handler = tempHandler; } // Retrieve a Decimal string data handler /////////////////////////////////////////////////////////// if(m_bufferType=="DS") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringDS); handler = tempHandler; } // Retrieve an Integer string data handler /////////////////////////////////////////////////////////// if(m_bufferType=="IS") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringIS); handler = tempHandler; } // Retrieve a Long string data handler /////////////////////////////////////////////////////////// if(m_bufferType=="LO") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringLO); handler = tempHandler; } // Retrieve a Long text data handler /////////////////////////////////////////////////////////// if(m_bufferType=="LT") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringLT); handler = tempHandler; } // Retrieve a Person Name data handler /////////////////////////////////////////////////////////// if(m_bufferType=="PN") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringPN); handler = tempHandler; } // Retrieve a Short string data handler /////////////////////////////////////////////////////////// if(m_bufferType=="SH") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringSH); handler = tempHandler; } // Retrieve a Short text data handler /////////////////////////////////////////////////////////// if(m_bufferType=="ST") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringST); handler = tempHandler; } // Retrieve an Unique Identifier data handler /////////////////////////////////////////////////////////// if(m_bufferType=="UI") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringUI); handler = tempHandler; } // Retrieve an Unlimited text data handler /////////////////////////////////////////////////////////// if(m_bufferType=="UT") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerStringUT); handler = tempHandler; } // Retrieve an object handler /////////////////////////////////////////////////////////// if(m_bufferType=="OB") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxUint8>); handler = tempHandler; } // Retrieve a signed-byte object handler. // Non standard: used by the images handler. /////////////////////////////////////////////////////////// if(m_bufferType=="SB") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxInt8>); handler = tempHandler; } // Retrieve an unknown object handler /////////////////////////////////////////////////////////// if(m_bufferType=="UN") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxUint8>); handler = tempHandler; } // Retrieve a WORD handler /////////////////////////////////////////////////////////// if(m_bufferType=="OW") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxUint16>); handler = tempHandler; } // Retrieve a WORD handler (AT) /////////////////////////////////////////////////////////// if(m_bufferType=="AT") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxUint16>); handler = tempHandler; } // Retrieve a float handler /////////////////////////////////////////////////////////// if(m_bufferType=="FL") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<float>); handler = tempHandler; } // Retrieve a double float handler /////////////////////////////////////////////////////////// if(m_bufferType=="FD") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<double>); handler = tempHandler; } // Retrieve a signed long handler /////////////////////////////////////////////////////////// if(m_bufferType=="SL") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxInt32>); handler = tempHandler; } // Retrieve a signed short handler /////////////////////////////////////////////////////////// if(m_bufferType=="SS") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxInt16>); handler = tempHandler; } // Retrieve an unsigned long handler /////////////////////////////////////////////////////////// if(m_bufferType=="UL") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxUint32>); handler = tempHandler; } // Retrieve an unsigned short handler /////////////////////////////////////////////////////////// if(m_bufferType=="US") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerNumeric<imbxUint16>); handler = tempHandler; } // Retrieve date /////////////////////////////////////////////////////////// if(m_bufferType=="DA") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerDate); handler = tempHandler; } // Retrieve date-time /////////////////////////////////////////////////////////// if(m_bufferType=="DT") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerDateTime); handler = tempHandler; } // Retrieve time /////////////////////////////////////////////////////////// if(m_bufferType=="TM") { ptr<handlers::dataHandler> tempHandler(new handlers::dataHandlerTime); handler = tempHandler; } } // check bRaw // If an error occurred during the data handler creation, // then throw an exception /////////////////////////////////////////////////////////// if(handler == 0) { PUNTOEXE_THROW(bufferExceptionUnknownType, "Unknown data type requested"); } // Connect the handler to this buffer /////////////////////////////////////////////////////////// if(localMemory == 0) { localMemory = ptr<memory>(new memory); } ptr<memory> parseMemory(localMemory); // Set the handler's attributes /////////////////////////////////////////////////////////// if(bWrite) { ptr<buffer> tempBuffer(this); handler->m_buffer = tempBuffer; imbxUint32 actualMemorySize = localMemory->size(); imbxUint32 newMemorySize = actualMemorySize; if(newMemorySize == 0) { newMemorySize = size * handler->getUnitSize(); } ptr<memory> newMemoryBuffer(memoryPool::getMemoryPool()->getMemory(newMemorySize)); if(actualMemorySize != 0) { newMemoryBuffer->copyFrom(localMemory); } parseMemory = newMemoryBuffer; // Add writing handlers to the current transaction /////////////////////////////////////////////////////////// transactionsManager::addHandlerToTransaction(handler); } handler->m_bufferType = m_bufferType; handler->setCharsetsList(&m_charsetsList); handler->parseBuffer(parseMemory); // Rewind the data pointer /////////////////////////////////////////////////////////// if(handler->getSize() != 0) { handler->setPointer(0); } // Return the allocated handler /////////////////////////////////////////////////////////// return handler; PUNTOEXE_FUNCTION_END(); }
void TextLayout::computeAdvancesWithICU(SkPaint* paint, const UChar* chars, size_t start, size_t count, size_t contextCount, int dirFlags, jfloat* outAdvances, jfloat* outTotalAdvance) { SkAutoSTMalloc<CHAR_BUFFER_SIZE, jchar> tempBuffer(contextCount); jchar* buffer = tempBuffer.get(); SkScalar* scalarArray = (SkScalar*)outAdvances; // this is where we'd call harfbuzz // for now we just use ushape.c size_t widths; const jchar* text; if (dirFlags & 0x1) { // rtl, call arabic shaping in case UErrorCode status = U_ZERO_ERROR; // Use fixed length since we need to keep start and count valid u_shapeArabic(chars, contextCount, buffer, contextCount, U_SHAPE_LENGTH_FIXED_SPACES_NEAR | U_SHAPE_TEXT_DIRECTION_LOGICAL | U_SHAPE_LETTERS_SHAPE | U_SHAPE_X_LAMALEF_SUB_ALTERNATE, &status); // we shouldn't fail unless there's an out of memory condition, // in which case we're hosed anyway for (int i = start, e = i + count; i < e; ++i) { if (buffer[i] == UNICODE_NOT_A_CHAR) { buffer[i] = UNICODE_ZWSP; // zero-width-space for skia } } text = buffer + start; widths = paint->getTextWidths(text, count << 1, scalarArray); } else { text = chars + start; widths = paint->getTextWidths(text, count << 1, scalarArray); } jfloat totalAdvance = 0; if (widths < count) { #if DEBUG_ADVANCES ALOGD("ICU -- count=%d", widths); #endif // Skia operates on code points, not code units, so surrogate pairs return only // one value. Expand the result so we have one value per UTF-16 code unit. // Note, skia's getTextWidth gets confused if it encounters a surrogate pair, // leaving the remaining widths zero. Not nice. for (size_t i = 0, p = 0; i < widths; ++i) { totalAdvance += outAdvances[p++] = SkScalarToFloat(scalarArray[i]); if (p < count && text[p] >= UNICODE_FIRST_LOW_SURROGATE && text[p] < UNICODE_FIRST_PRIVATE_USE && text[p-1] >= UNICODE_FIRST_HIGH_SURROGATE && text[p-1] < UNICODE_FIRST_LOW_SURROGATE) { outAdvances[p++] = 0; } #if DEBUG_ADVANCES ALOGD("icu-adv = %f - total = %f", outAdvances[i], totalAdvance); #endif } } else { #if DEBUG_ADVANCES ALOGD("ICU -- count=%d", count); #endif for (size_t i = 0; i < count; i++) { totalAdvance += outAdvances[i] = SkScalarToFloat(scalarArray[i]); #if DEBUG_ADVANCES ALOGD("icu-adv = %f - total = %f", outAdvances[i], totalAdvance); #endif } } *outTotalAdvance = totalAdvance; }
void VRendererNodeCommon::InitializePostProcessors() { VASSERT_MSG(IsInitialized(), "The renderer node must be initialized before initializing the post processors."); ANALYSIS_IGNORE_WARNING_BLOCK_START(6385); ANALYSIS_IGNORE_WARNING_BLOCK_START(6211); // Increment the update counter to enable modifying the post processors without recursing m_iPostProcessorUpdateCounter++; VType* pCopyPostProcessorType = GetDefaultCopyPostprocessorType(); bool bInvalidPostProcessorActive = false; do { bInvalidPostProcessorActive = false; DeInitializePostProcessors(); VPostProcessingBaseComponent* pSimpleCopy = NULL; // Collect post processor components VMemoryTempBuffer<256> tempBuffer((Components().Count() + 1) * sizeof(VPostProcessingBaseComponent*)); VPostProcessingBaseComponent** postProcessors = reinterpret_cast<VPostProcessingBaseComponent**>(tempBuffer.GetBuffer()); int iPostProcessorIndex = 0; for(int iComponentIndex = 0; iComponentIndex < Components().Count(); iComponentIndex++) { if(VPostProcessingBaseComponent* pPostProcessor = vdynamic_cast<VPostProcessingBaseComponent*>(Components().GetAt(iComponentIndex))) { // Don't take the auto added copy PP into consideration, we'll handle that separately if(pCopyPostProcessorType != NULL && pPostProcessor->IsOfType(pCopyPostProcessorType)) { pSimpleCopy = pPostProcessor; continue; } // HS#10443: Skip post-processors which do nothing - needs testing whether this works cleanly when the identity state changes if(!pPostProcessor->IsActive() /*!pPostProcessor->IsIdentity()*/) { continue; } postProcessors[iPostProcessorIndex] = pPostProcessor; iPostProcessorIndex++; } } int iNumPostProcessors = iPostProcessorIndex; qsort(postProcessors, iNumPostProcessors, sizeof(VPostProcessingBaseComponent*), ComparePostProcessorsByPriority); int iCopyPPIndex = iNumPostProcessors; // Scan backwards through post processors to find one which can take over the responsibility // of copying the scene to the final target context // // This post processor must: // - come after the MSAA resolve step // - render an opaque full screen quad // - not have any postprocessor afterwards that reads the accumulation buffer bool bUsesOffscreenRenderTarget = !m_bUsesDirectRenderToFinalTargetContext; for(int i = iNumPostProcessors - 1; i >= 0; i--) { if(postProcessors[i]->GetPriority() < VIS_RENDERCONTEXTPRIORITY_POSTPROCESSOR_RESOLVED) { bUsesOffscreenRenderTarget = true; break; } const unsigned int flags = postProcessors[i]->GetBufferUsageFlags(); // Post processors that use their own render target can't be used for copying to the back buffer if((flags & VPostProcessingBaseComponent::USES_CUSTOM_RENDERTARGET) != 0) { bUsesOffscreenRenderTarget = true; break; } // Check first if the post processors draws an opaque full screen quad, because // a PP that draws a full screen quad AND samples the accumulation buffer // is still suitable for copying the accumulation buffer into the final target context (such as tonemapping). if((flags & VPostProcessingBaseComponent::DRAWS_FULLSCREEN_QUAD) != 0 && (flags & VPostProcessingBaseComponent::USES_BLENDING) == 0) { iCopyPPIndex = i; break; } if(flags & VPostProcessingBaseComponent::SAMPLES_ACCUMULATION_BUFFER) { bUsesOffscreenRenderTarget = true; break; } } VASSERT_MSG(bUsesOffscreenRenderTarget != m_bUsesDirectRenderToFinalTargetContext, "Renderer node indicated that it renders directly to the renderer node's final target context, but post-processors require an offscreen render target!"); // If no suitable post processor was found, we need to make sure the scene is copied bool bNeedsManualCopyToTarget = (iCopyPPIndex == iNumPostProcessors) && bUsesOffscreenRenderTarget; // If we don't use an offscreen RT, we don't have a copy PP if (!bUsesOffscreenRenderTarget) iCopyPPIndex = -1; if(bNeedsManualCopyToTarget) { if (pCopyPostProcessorType != NULL) { if(pSimpleCopy == NULL) { pSimpleCopy = (VPostProcessingBaseComponent*)pCopyPostProcessorType->CreateInstance(); VASSERT(pSimpleCopy != NULL); AddComponent(pSimpleCopy); } postProcessors[iNumPostProcessors] = pSimpleCopy; iNumPostProcessors++; } } else if(pSimpleCopy != NULL) { // Remove existing copy PP if not needed RemoveComponent(pSimpleCopy); } m_assignedContexts.EnsureCapacity(iNumPostProcessors); // Create a target context for each post processor for(iPostProcessorIndex = 0; iPostProcessorIndex < iNumPostProcessors; iPostProcessorIndex++) { VPostProcessingBaseComponent* pPostProcessor = postProcessors[iPostProcessorIndex]; pPostProcessor->m_iTargetIndex = iPostProcessorIndex; const VisRenderContext_cl* pFinalTargetContext = GetFinalTargetContext(); bool bRenderIntoFinalTargetContext = (iPostProcessorIndex >= iCopyPPIndex); int iPosX, iPosY, iWidth, iHeight; float zMin, zMax; if(bRenderIntoFinalTargetContext) { pFinalTargetContext->GetViewport(iPosX, iPosY, iWidth, iHeight, zMin, zMax); } else { GetReferenceContext()->GetViewport(iPosX, iPosY, iWidth, iHeight, zMin, zMax); } VisRenderContext_cl* pContext = new VisRenderContext_cl(pFinalTargetContext->GetCamera(), 90.0f, 90.0f, iWidth, iHeight, 0.0f, 0.0f, pFinalTargetContext->GetRenderFlags()); pContext->SetRenderFilterMask(pFinalTargetContext->GetRenderFilterMask()); pContext->SetViewport(iPosX, iPosY, iWidth, iHeight, zMin, zMax); pContext->SetViewProperties(pFinalTargetContext->GetViewProperties()); pContext->SetName(pPostProcessor->GetTypeId()->m_lpszClassName); pContext->SetVisibilityCollector(pFinalTargetContext->GetVisibilityCollector(), false); pContext->SetPriority(pPostProcessor->GetPriority()); pContext->SetUserData(pPostProcessor); pContext->SetRenderLoop(new PostProcessRenderLoop_cl(pPostProcessor)); if(bRenderIntoFinalTargetContext) { pContext->SetRenderAndDepthStencilTargets(pFinalTargetContext); if (bUsesOffscreenRenderTarget) { // If possible, try to give the post processors that render directly into the final target context a useful depth-stencil target. // This is only possible if the final target context has MSAA disabled. bool bCanReplaceDST = false; if(pFinalTargetContext->RendersIntoBackBuffer()) { #if !defined(_VISION_ANDROID) && !defined(_VISION_TIZEN) && !defined(_VISION_NACL) // On Android, the back buffer context uses a fixed FBO, so we can't replace the DST. bCanReplaceDST = Vision::Video.GetCurrentConfig()->m_eMultiSample == VVIDEO_MULTISAMPLE_OFF; #endif } else if(pFinalTargetContext->GetRenderTarget(0) != NULL) { bCanReplaceDST = static_cast<VisRenderableTexture_cl*>(pFinalTargetContext->GetRenderTarget(0))->GetConfig()->m_iMultiSampling <= 1; } int iRefWidth, iRefHeight, iFinalWidth, iFinalHeight; pFinalTargetContext->GetSize(iFinalWidth, iFinalHeight); GetReferenceContext()->GetSize(iRefWidth, iRefHeight); if(iRefWidth != iFinalWidth || iRefHeight != iFinalHeight) { bCanReplaceDST = false; } if(bCanReplaceDST) { pContext->SetDepthStencilTarget(static_cast<VisRenderableTexture_cl*>(GetPostProcessDepthStencilTarget(VRTV_RESOLVED))); } else { hkvLog::Warning("Could not attach a depth-stencil target to the context of the \"%s\" post processor - depth testing will not work correctly.", pPostProcessor->GetTypeId()->m_lpszClassName); } } } else { VRenderTargetVersion_e targetVersion = (pPostProcessor->GetPriority() <= VIS_RENDERCONTEXTPRIORITY_POSTPROCESSOR_RESOLVED) ? VRTV_MSAA : VRTV_RESOLVED; if((pPostProcessor->GetBufferUsageFlags() & VPostProcessingBaseComponent::USES_CUSTOM_RENDERTARGET) == 0) { pContext->SetRenderTarget(0, static_cast<VisRenderableTexture_cl*>(GetPostProcessColorTarget(targetVersion))); pContext->SetDepthStencilTarget(static_cast<VisRenderableTexture_cl*>(GetPostProcessDepthStencilTarget(targetVersion))); } } m_assignedContexts.Add(pContext); pPostProcessor->InitializePostProcessor(); // Validity can only be determined after initialization, so deactivate the invalid postprocessor and retry the entire context setup if(!pPostProcessor->IsValid()) { // the post-processor will have deactivated itself by now pPostProcessor->SetActive(false); bInvalidPostProcessorActive = true; } } } while ( bInvalidPostProcessorActive ); m_bPostProcessorAssignmentDirty = false; m_iPostProcessorUpdateCounter--; VisRenderContext_cl::ElementManagerDeleteAllUnRef(); ANALYSIS_IGNORE_WARNING_BLOCK_END; ANALYSIS_IGNORE_WARNING_BLOCK_END; }
void ImageCodecTiff::save(const Image& image, const std::string& filename) { // create a new TIFF file Tiff::File file(TIFFOpen(filename.c_str(), "w")); if (!file) AURORA_THROW(EInOut, "File could not be created: " + filename); const int64_t cols = image.cols(); const int64_t rows = image.rows(); uint16_t samplesPerPixel; // some standard tags that must be set Tiff::setField(file, TIFFTAG_IMAGEWIDTH , cols); Tiff::setField(file, TIFFTAG_IMAGELENGTH , rows); Tiff::setField(file, TIFFTAG_BITSPERSAMPLE, 8); Tiff::setField(file, TIFFTAG_PLANARCONFIG , PLANARCONFIG_CONTIG); Tiff::setField(file, TIFFTAG_ROWSPERSTRIP , rows); if (Image::PixelFormat::Gray8 == image.pixelFormat()) { samplesPerPixel = 1; Tiff::setField(file, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); } else if (Image::PixelFormat::RGBA8 == image.pixelFormat()) { samplesPerPixel = 3; Tiff::setField(file, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else if (Image::PixelFormat::Float == image.pixelFormat()) { AURORA_THROW(ENotSupported, "Float images cannot be saved."); } else { AURORA_UNREACHABLE; } Tiff::setField(file, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel); // convert the internal format into the TIFF format std::vector<uint8_t> tempBuffer(cols * rows * samplesPerPixel); if (Image::PixelFormat::Gray8 == image.pixelFormat()) { #pragma omp parallel for for (int64_t y = 0; y < rows; ++y) for (int64_t x = 0; x < cols; ++x) tempBuffer[y * cols + x] = image.pixel<Gray8>(x, y); } else if (Image::PixelFormat::RGBA8 == image.pixelFormat()) { #pragma omp parallel for for (int64_t y = 0; y < rows; ++y) { for (int64_t x = 0; x < cols; ++x) { tempBuffer[(y * cols + x) * 3 + 0] = image.pixel<Rgba8>(x, y).r; tempBuffer[(y * cols + x) * 3 + 1] = image.pixel<Rgba8>(x, y).g; tempBuffer[(y * cols + x) * 3 + 2] = image.pixel<Rgba8>(x, y).b; } } } else { AURORA_UNREACHABLE; } // write all the image data at once const int64_t numBytes = cols * rows * samplesPerPixel; if (-1 == TIFFWriteEncodedStrip(file, 0, tempBuffer.data(), numBytes)) AURORA_THROW(EInOut, "Writing image data to TIFF file failed."); }
//============================================================================== void AudioFileConverter::run() { while ( getQueueSize() > 0 ) { { // lock jobQueue before retrieving a task const ScopedLock lock (queueLock); task = jobQueue[0]; } /* try opening the file */ File inputDataFile( task->getFileName() ); String inputFileName( inputDataFile.getFullPathName() ); if ( !inputDataFile.existsAsFile() || (inputDataFile.getSize() == 0) ) { dbgOut(L"** AudioFileConverter ** Invalid or corrupted temporary file:\t" + inputFileName); removeFromQueue(); continue; } /* try creating the input stream */ FileInputStream* fileInputStream = inputDataFile.createInputStream(); if (fileInputStream == NULL) { dbgOut(L"** AudioFileConverter ** Unable to create input stream for file:\t" + inputFileName); removeFromQueue(); continue; } dbgOut(L""); dbgOut(L" *** AudioFileConverter ***"); dbgOut(L"** AudioFileConverter ** Converting file:\t" + inputFileName + L" (" + String( inputDataFile.getSize() ) + L" b)"); int processorOutputs = task->getChannelNumber(); const int bytesPerSample = processorOutputs * sizeof(float); int bufferSize = task->getBufferSize(); double samplingRate = task->getSamplingRate(); int bitDepth = task->getBitDepth(); String audioFormatName = task->getFormat(); AudioSampleBuffer tempBuffer(1, bufferSize); // declare classes needed to save the format OwnedArray<AudioFormat> someAudioFormats; OwnedArray<AudioFormatWriter> audioFormatWriters; OwnedArray<File> audioFiles; Array<FileOutputStream*> outStreams; String audioFileName; AudioFormatWriter* tmpWriter; FileOutputStream* tmpStream; File* tmpAudioFile; String outputDir = inputDataFile.getParentDirectory().getFullPathName(); for (int i=0; i < processorOutputs ; i++) { // Delete temporary files File tmpDataFile(outputDir + File::separatorString + L"channel" + String::formatted("%.2d", i ) + ".dat"); if ( tmpDataFile != File::nonexistent) { dbgOut( L"** AudioFileConverter ** \tDeleting temporary file:\t" + tmpDataFile.getFullPathName() ); tmpDataFile.deleteFile(); } else { dbgOut( "** AudioFileConverter ** Unable to delete temporary file:\t\t" + tmpDataFile.getFullPathName() ); } // Define the format (wav is default) if (audioFormatName == "wav") someAudioFormats.add( new WavAudioFormat() ); else if (audioFormatName == "aiff") someAudioFormats.add( new AiffAudioFormat() ); else if (audioFormatName == "flac") someAudioFormats.add( new FlacAudioFormat() ); // else if (audioFormatName == "ogg") // someAudioFormats.add( new OggVorbisAudioFormat() ); else someAudioFormats.add( new WavAudioFormat() ); audioFileName = outputDir + File::separatorString + "channel" + String::formatted("%.2d",i) + someAudioFormats[i]->getFileExtensions()[0]; tmpAudioFile = new File (audioFileName); if (*tmpAudioFile == File::nonexistent) { dbgOut( L"** AudioFileConverter ** Unable to create file:\t" + audioFileName ); audioFormatWriters.clear(true); someAudioFormats.clear(true); audioFiles.clear(true); outStreams.clear(); delete fileInputStream; removeFromQueue(); continue; } audioFiles.add( tmpAudioFile ); // Delete existing files if (audioFiles[i]->existsAsFile()) { dbgOut( "** AudioFileConverter ** \tDeleting existing audio file:\t\t" + audioFileName ); if (!audioFiles[i]->deleteFile()) { dbgOut( L"** AudioFileConverter ** Unable to delete existing file:\t" + audioFileName ); audioFormatWriters.clear(true); someAudioFormats.clear(true); audioFiles.clear(true); outStreams.clear(); delete fileInputStream; removeFromQueue(); continue; } } dbgOut( "** AudioFileConverter ** \tSaving audio file:\t\t" + audioFileName ); /* Create output stream for this file */ tmpStream = audioFiles[i]->createOutputStream(); if (tmpStream == NULL) { dbgOut( L"** AudioFileConverter ** Unable to create output stream for file:\t" + audioFileName ); delete tmpAudioFile; audioFormatWriters.clear(true); someAudioFormats.clear(true); audioFiles.clear(true); outStreams.clear(); delete fileInputStream; removeFromQueue(); continue; } outStreams.add( tmpStream ); /* Create Audio Format Writer */ tmpWriter = someAudioFormats[i]->createWriterFor( outStreams[i], // streamToWriteTo, samplingRate, // sampleRateToUse, 1, // numberOfChannels, someAudioFormats[i]->getPossibleBitDepths().getLast(), // bitsPerSample - Get the maximum possible bit depth for this format NULL, // metadataValues, 0 ); if (tmpWriter == NULL) { dbgOut( L"** AudioFileConverter ** Unable to create audio format writer for:\t" + audioFileName ); delete tmpAudioFile; audioFormatWriters.clear(true); someAudioFormats.clear(true); audioFiles.clear(true); outStreams.clear(); delete fileInputStream; removeFromQueue(); continue; } audioFormatWriters.add( tmpWriter ); } // Write data to wav file int dataBlockSize = processorOutputs * bufferSize * bitDepth/8 ; MemoryBlock* buffer = new MemoryBlock( dataBlockSize, true); int64 bytesSaved = inputDataFile.getSize(); while ( !fileInputStream->isExhausted() && (fileInputStream->getPosition() < bytesSaved) ) { float* x = (float *) buffer->getData() ; int bytesRead = fileInputStream->read( (void *)x, dataBlockSize ); int numSamples = (int)( bytesRead / bytesPerSample ); for (int ch=0; ch < processorOutputs; ch++) { // const int numBytes = (int) (bytesRead/processorOutputs); tempBuffer.copyFrom( 0, // const int destChannel, 0, // const int destStartSample, x+ch*numSamples, // const float * source, numSamples // int numSamples ); audioFormatWriters[ch]->write( (const int**)(tempBuffer.getArrayOfChannels()), //AudioFormatWriter * writer, numSamples //const int numSamples ); } } // clean up delete buffer; // this should delete 'owned' objects audioFormatWriters.clear(true); someAudioFormats.clear(true); audioFiles.clear(true); // clear the outStreams without deleting objects (already deleted) outStreams.clear(); // Delete and close the stream delete fileInputStream; // Delete the data.dat file dbgOut( L"** AudioFileConverter ** \tDeleting temporary file:\t" + inputFileName ); inputDataFile.deleteFile(); // Delete the task removeFromQueue(); dbgOut( "** AudioFileConverter ** Files saved." ); } dbgOut( "** AudioFileConverter ** Thread terminates." ); }
void* wxOdbcResultSet::GetResultBlob(int nField, wxMemoryBuffer& Buffer) { if (m_BlobMap.find(nField) == m_BlobMap.end()) { if (m_pOdbcStatement == NULL) m_pOdbcStatement = m_pStatement->GetLastStatement(); if (m_NullValues.find(nField) != m_NullValues.end()) return NULL; SQLINTEGER iLength = 8192; SQLINTEGER iSize = 0; unsigned char buff[8193]; memset(buff, 0, 8193*sizeof(unsigned char)); long nReturn = m_pInterface->GetSQLBindParameter()(m_pOdbcStatement, nField, SQL_PARAM_OUTPUT, SQL_C_BINARY, SQL_BINARY, iLength, 0, &buff, iLength, &iSize); // Mark this field as retrieved m_RetrievedValues.insert(nField); // Record whether this field is NULL if (iSize == SQL_NULL_DATA) { m_NullValues.insert(nField); return NULL; } nReturn = m_pInterface->GetSQLGetData()( m_pOdbcStatement, nField, SQL_C_BINARY, &buff, iLength, &iSize ); if ( nReturn != SQL_SUCCESS && nReturn != SQL_SUCCESS_WITH_INFO ) { wxLogError(_T("Error with RunQueryWithResults - 1\n")); InterpretErrorCodes(nReturn, m_pOdbcStatement); ThrowDatabaseException(); } // NULL data if (iSize < 0) { wxMemoryBuffer tempBuffer(0); tempBuffer.SetDataLen(0); tempBuffer.SetBufSize(0); Buffer = tempBuffer; // Add null blobs to the map as well m_BlobMap[nField] = tempBuffer; return NULL; } size_t dataLength = (iLength < iSize) ? iLength : iSize; size_t bufferSize = dataLength; wxMemoryBuffer tempBuffer(dataLength); tempBuffer.AppendData( buff, dataLength ); while ( iSize > iLength ) { nReturn = m_pInterface->GetSQLGetData()( m_pOdbcStatement, nField, SQL_C_BINARY, &buff, iLength, &iSize ); if ( nReturn != SQL_SUCCESS && nReturn != SQL_SUCCESS_WITH_INFO ) { wxLogError(_T("Error with RunQueryWithResults - 2\n")); InterpretErrorCodes(nReturn, m_pOdbcStatement); ThrowDatabaseException(); } dataLength = (iLength < iSize) ? iLength : iSize; tempBuffer.AppendData( buff, dataLength ); bufferSize += dataLength; } wxMemoryBuffer tempBufferExactSize(bufferSize); void* pData = tempBufferExactSize.GetWriteBuf(bufferSize); memcpy(pData, tempBuffer.GetData(), bufferSize); tempBufferExactSize.UngetWriteBuf(bufferSize); tempBufferExactSize.SetDataLen(bufferSize); tempBufferExactSize.SetBufSize(bufferSize); Buffer = tempBufferExactSize; wxMemoryBuffer localCopy(Buffer); m_BlobMap[nField] = localCopy; return Buffer.GetData(); } else { BlobMap::iterator it = m_BlobMap.find(nField); if (it == m_BlobMap.end()) { wxMemoryBuffer tempBuffer(0); tempBuffer.SetDataLen(0); tempBuffer.SetBufSize(0); Buffer = tempBuffer; return NULL; } else { Buffer = it->second; return Buffer.GetData(); } } }