XSerializeEngine::XSerializeEngine(BinInputStream* inStream , XMLGrammarPool* const gramPool , unsigned long bufSize) :fStoreLoad(mode_Load) ,fStorerLevel(0) ,fGrammarPool(gramPool) ,fInputStream(inStream) ,fOutputStream(0) ,fBufCount(0) ,fBufSize(bufSize) ,fBufStart( (XMLByte*) gramPool->getMemoryManager()->allocate(bufSize)) ,fBufEnd(0) ,fBufCur(fBufStart) ,fBufLoadMax(fBufStart) ,fStorePool(0) ,fLoadPool( new (gramPool->getMemoryManager()) ValueVectorOf<void*>(29, gramPool->getMemoryManager(), false)) ,fObjectCount(0) { /*** * initialize buffer from the inStream ***/ fillBuffer(); }
void rviewOSectionImage::updateSlice(unsigned int num, long value, bool useDummy) { unsigned int map = secmap[num].z; //cout << "update slice " << num << endl; // make an update if the value has changed or we need a full update and the current // section is a dummy. if ((intersection[map] != value) || (!useDummy && (getSectionProjection(num) != value))) { if ((interv[map].low() <= value) && (value <= interv[map].high())) { intersection[map] = value; sliders[num]->SetValue(value); sltexts[num]->SetValue(value); if (useDummy) createDummySection(num); else ensureSections(); fillBuffer(); updatePixmap(imgData, imgData); } } }
void VorbisFileReader::rewind(double position) { if (position < 0 || position >= length) { buffer_start_time = position; buffer_actual_size = 0; cursor_position_in_buffer = 0; } else { int ret = ov_time_seek(&vf, position); if (ret < 0) { throwVorbisError(ret, L"rewind"); } if (ret == 0) { fillBuffer(); } } updatePlayhead(); }
int beMaster(int ppiFD, UINT16 bufX, UINT16 bufY, int dims) { int retval; UINT16 value = 0; int done = 0; char buf[128]; CfgTable *table; printf("Setting up master..."); #ifdef DEBUG ioctl( ppiFD, CMD_PPI_GET_ALLCONFIG, 0); #endif gRows = bufX; gCols = bufY; gImage = realloc_image(); if ( gImage == NULL ){ return(-1); } /* fill in common values */ if ( dims == DIM2D ){ table = ppiMasterTable2D; /* 2D configuration */ retval = ioctl( ppiFD, CMD_PPI_NUMLINES, bufY ); if(retval){ perror("ppi ioctl error"); return(-1); } retval = ioctl( ppiFD, CMD_PPI_LINELEN, bufX ); if(retval){ perror("ppi ioctl error"); return(-1); } } else { /* 1D configuration */ table = ppiMasterTable1D; } config_device( ppiFD, table ); printf("Master set up complete...further input is transmited to slave\n"); #ifdef DEBUG ioctl( ppiFD, CMD_PPI_GET_ALLCONFIG, 0); #endif while ( !done ) { printf("Enter fill pattern [CcQqRrTtVvHh?]: "); if ( fgets( buf, sizeof(buf), stdin ) == NULL ){ done = 1; break; } switch( buf[0] ) { case 'q': case 'Q': done = 1; value = 0xdead; gPatternID = 'q'; break; case 'v': case 'V': gPatternID = 'v'; printf("\nEnter fill value: "); if ( fgets( buf, sizeof(buf), stdin ) == NULL ){ done = 1; break; } if ( sscanf(buf, "%hx", &value) != 1 ){ printf("\nError reading value...retry\n"); continue; } break; case 'h': case 'H': case '?': printf("\nColumn, Row, Sequential, Tile, Value, Help?, Quit\n"); continue; break; default: gPatternID = buf[0]; } fillBuffer( (UINT16 *)gImage, bufX, bufY, gPatternID, value ); showBuffer( (UINT16 *)gImage, bufX, bufY, 0x0FFF ); retval = write( ppiFD, gImage, gImageSize ); if ( retval != gImageSize ){ perror("ppi write error"); done = 1; } } printf("Done \n"); return(0); }
WinHelpPhrImageFile::WinHelpPhrImageFile(QFile &file, qint64 off, QTextCodec *codec, const WinHelpPhrIndexFile &index) : phrases(), phrasesRaw() { PRINT_DBG("Loading WinHelp PhrImage file at %lld", off); if (codec == NULL) { throw std::runtime_error("Codec is NULL"); } seekFile(file, off); InternalDirectoryFileHeader hdr(file, off); seekFile(file, off + InternalDirectoryFileHeader::size); if (index.getPhrImageCompressedSize() < index.getPhrImageSize()) { PRINT_DBG("Reading compressed phrases at %lld", file.pos()); QScopedArrayPointer<quint8> uncompressedPhrases( new quint8[static_cast<size_t> (index.getPhrImageSize())]); unpackLZ77(file, file.pos(), index.getPhrImageCompressedSize(), uncompressedPhrases.data(), static_cast<size_t> (index.getPhrImageSize())); quint64 pointer = 0; for (quint16 i = 0; i < (static_cast<quint16> (index.getPhraseOffsetsCount()) - 1); i++) { uint size = index.getPhraseOffset(i + 1) - index.getPhraseOffset(i); QString phrase = readFixedLengthStringFromBuffer( uncompressedPhrases.data(), static_cast<size_t> (index.getPhrImageSize()), static_cast<size_t> (pointer), size, codec); this->phrases.append(phrase); QScopedArrayPointer<quint8> phraseRaw( new quint8[static_cast<size_t> (size)]); copyBytesFromBuffer( reinterpret_cast<const void *> (uncompressedPhrases.data()), static_cast<size_t> (index.getPhrImageSize()), static_cast<size_t> (pointer), static_cast<size_t> (size), reinterpret_cast<void *> (phraseRaw.data()), static_cast<size_t> (size)); this->phrasesRaw.append(QByteArray( reinterpret_cast<const char *> (phraseRaw.data()), static_cast<int>(size))); pointer += static_cast<quint64> (size); PRINT_DBG(" Phrase: %s", phrase.toLocal8Bit().data()); } } else { PRINT_DBG("Reading phrases at %lld", file.pos()); for (quint16 i = 0; i < (static_cast<quint16> (index.getPhraseOffsetsCount()) - 1); i++) { uint size = index.getPhraseOffset(i + 1) - index.getPhraseOffset(i); qint64 posMem = file.pos(); QString phrase = readFixedLengthString(file, size, codec); this->phrases.append(phrase); QScopedArrayPointer<quint8> phraseRaw( new quint8[static_cast<size_t> (size)]); seekFile(file, posMem); fillBuffer(file, static_cast<qint64> (size), reinterpret_cast<void *> (phraseRaw.data()), static_cast<size_t> (size)); this->phrasesRaw.append(QByteArray( reinterpret_cast<const char *> (phraseRaw.data()), static_cast<int>(size))); PRINT_DBG(" Phrase: %s", phrase.toLocal8Bit().data()); } } PRINT_DBG("WinHelp PhrImage file loaded successfully"); }
void updateBuffer( ) { fillBuffer( m_buffer, m_end ); m_cur = m_buffer; }
void TunnelPlayer::extractorThreadEntry() { mLock.lock(); uint32_t BufferSizeToUse = MEM_BUFFER_SIZE; pid_t tid = gettid(); androidSetThreadPriority(tid, mHasVideo ? ANDROID_PRIORITY_NORMAL : ANDROID_PRIORITY_AUDIO); prctl(PR_SET_NAME, (unsigned long)"Extractor Thread", 0, 0, 0); ALOGV("extractorThreadEntry wait for signal \n"); if (!mStarted && !mKillExtractorThread) { mExtractorCv.wait(mLock); } ALOGV("extractorThreadEntry ready to work \n"); mLock.unlock(); if (mKillExtractorThread) { return; } if(mSource != NULL) { sp<MetaData> format = mSource->getFormat(); const char *mime; bool success = format->findCString(kKeyMIMEType, &mime); } void* local_buf = malloc(BufferSizeToUse); int *lptr = ((int*)local_buf); int bytesWritten = 0; bool lSeeking = false; bool lPaused = false; while (!mKillExtractorThread) { if (mReachedEOS || mPaused || !mIsAudioRouted) { ALOGV("Going to sleep before write since " "mReachedEOS %d, mPaused %d, mIsAudioRouted %d", mReachedEOS, mPaused, mIsAudioRouted); mExtractorMutex.lock(); mExtractorCv.wait(mExtractorMutex); mExtractorMutex.unlock(); ALOGV("Woke up from sleep before write since " "mReachedEOS %d, mPaused %d, mIsAudioRouted %d", mReachedEOS, mPaused, mIsAudioRouted); continue; } ALOGV("FillBuffer: MemBuffer size %d", BufferSizeToUse); ALOGV("Fillbuffer started"); bytesWritten = fillBuffer(local_buf, BufferSizeToUse); ALOGV("FillBuffer completed bytesToWrite %d", bytesWritten); if(!mKillExtractorThread) { mLock.lock(); lPaused = mPaused; mLock.unlock(); if(lPaused == true) { //write only if player is not in paused state. Sleep on lock // resume is called ALOGV("Going to sleep in decodethreadiwrite since sink is paused"); mExtractorMutex.lock(); mExtractorCv.wait(mExtractorMutex); ALOGV("Going to unlock n decodethreadwrite since sink " "resumed mPaused %d, mIsAudioRouted %d, mReachedEOS %d", mPaused, mIsAudioRouted, mReachedEOS); mExtractorMutex.unlock(); } mLock.lock(); lSeeking = mSeeking||mInternalSeeking; mLock.unlock(); if(lSeeking == false && (mKillExtractorThread == false)){ //if we are seeking, ignore write, otherwise write ALOGV("Fillbuffer before seek flag %d", mSeeking); int lWrittenBytes = mAudioSink->write(local_buf, bytesWritten); ALOGV("Fillbuffer after write, written bytes %d and seek flag %d", lWrittenBytes, mSeeking); if(lWrittenBytes > 0) { //send EOS only if write was successful, if is_buffer_available // is flushed out (which returns 0 do not SEND EOS ALOGV("Fillbuffer after write and seek flag %d", mSeeking); mLock.lock(); lSeeking = mSeeking||mInternalSeeking; mLock.unlock(); //ignore posting zero length buffer is seeking is set if(mReachedEOS && bytesWritten && !lSeeking && (mKillExtractorThread == false)) { ALOGV("Fillbuffer after write sent EOS flag %d", lSeeking); mAudioSink->write(local_buf, 0); } else { ALOGV("Not sending EOS buffer sent since seeking %d, " "kill %d and mReachedEOS %d", \ lSeeking, mKillExtractorThread, mReachedEOS); } } else { ALOGV("write exited because of flush %d", mSeeking); } } else { ALOGV("Fillbuffer ignored since we seeked after fillBuffer was set %d", mSeeking); } } } free(local_buf); //TODO: Call fillbuffer with different size and write to mAudioSink() }
int TapeDrive::read(void *buf, int recSize, int binary) { TAPEDBG2(cout << "Read request for " << recSize << " " << (binary ? "binary" : "ASCII") << " bytes to " << (void *)buf << endl); if (bufferType != readBuffer) { cerr << "Must do a seek before switching from writing to reading" << endl; exit(1); } DOASSERT(bufferOffset >= 0 && bufferOffset <= blockSize, "Inconsistent data"); DOASSERT(bufferBytes >= 0 && bufferBytes <= blockSize, "Inconsistent data"); DOASSERT(bufferOffset <= bufferBytes, "Inconsistent data"); #ifdef TARFILESIZE if (haveTarHeader // is file in a tar archive? && tarFileOffset >= tarFileSize) // and at end of file? atEof = 1; #endif if (atEof) // already at end of tape file? return 0; if (bufferOffset >= bufferBytes) { // no more bytes in buffer? fillBuffer(); // get next block from file if (!bufferBytes) { // end of file? #ifdef TARFILESIZE // for non-tar files, end of tape file is the natural end of // user file; for tar files, the file size indicated in the // tar header should trigger the atEof statement a few lines // up; it is an error if the tape file (tar file) ends before // the file inside the tar file if (haveTarHeader) cerr << "File in tar archive prematurely terminated." << endl; #endif return 0; } } read_cnt++; if (read_cnt % 1000 == 0) TAPEDBG2(cout << read_cnt << " " << flush); #ifdef TAPE_BLOCK_PADDING char *start = buffer + bufferOffset; // starting point for this record DOASSERT(*start != 0, "Unexpected record"); // must not be an empty record if (recSize > bufferBytes - bufferOffset) recSize = bufferBytes - bufferOffset; #ifdef TARFILESIZE if (haveTarHeader // past EOF of file in tar archive? && recSize > tarFileSize - tarFileOffset) recSize = tarFileSize - tarFileOffset; #endif if (!binary) { // reading an ASCII record? char *end = (char *)memchr(start, 0, recSize); DOASSERT(end, "End of record not found"); recSize = end - start; // do not include record separator } TAPEDBG2(cout << "Copying " << recSize << " bytes to " << (void *)buf << endl); memcpy(buf, start, recSize); bufferOffset += recSize + 1; // go past record separator too if (!binary // in ASCII mode? && bufferOffset < bufferBytes // still data left but... && !buffer[bufferOffset])) // last record in block? bufferOffset = bufferBytes; // must fetch new block next time #else int bytesLeft = recSize; #ifdef TARFILESIZE if (haveTarHeader // past EOF of file in tar archive? && bytesLeft > tarFileSize - tarFileOffset) bytesLeft = tarFileSize - tarFileOffset; #endif recSize = 0; char *p = (char *)buf; while(bytesLeft > 0) { char *start = buffer + bufferOffset; int b = bufferBytes - bufferOffset; // bytes left in buffer if (bytesLeft < b) // caller doesn't want that many? b = bytesLeft; char *end = 0; if (!binary) { // reading an ASCII record? end = (char *)memchr((void *)start, '\n', b); if (end) // found newline = end of record? b = end - start + 1; } TAPEDBG2(cout << "Copying " << b << " bytes to " << (void *)p << endl); memcpy(p, start, b); bufferOffset += b; bytesLeft -= b; recSize += b; p += b; if (end) // found newline = end of record? break; if (bufferOffset >= bufferBytes) // need next block? fillBuffer(); if (!bufferBytes) // end of physical file? break; } if (!binary // in ASCII mode? && bufferOffset < bufferBytes // still data left but... && !buffer[bufferOffset]) // end of logical file (NULL char)? bufferOffset = bufferBytes; // must try to fetch block next time #endif #ifdef TARFILESIZE if (haveTarHeader) { tarFileOffset += recSize; DOASSERT(tarFileOffset <= tarFileSize, "Inconsistent data"); } #endif return recSize; }
status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_INTERFACE(IOMX, data, reply); reply->writeInt32(livesLocally((pid_t)data.readInt32())); return OK; } case LIST_NODES: { CHECK_INTERFACE(IOMX, data, reply); List<ComponentInfo> list; listNodes(&list); reply->writeInt32(list.size()); for (List<ComponentInfo>::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List<String8>::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp<IOMXObserver> observer = interface_cast<IOMXObserver>(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeIntPtr((intptr_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_COMMANDTYPE cmd = static_cast<OMX_COMMANDTYPE>(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32()); size_t size = data.readInt32(); void *params = malloc(size); data.read(params, size); status_t err; switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; default: TRESPASS(); } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } free(params); params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeIntPtr((intptr_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeIntPtr((intptr_t)buffer); } return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = storeMetaDataInBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case ALLOC_BUFFER: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); size_t size = data.readInt32(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeIntPtr((intptr_t)buffer); reply->writeIntPtr((intptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeIntPtr((intptr_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (void*)data.readIntPtr(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); buffer_id buffer = (void*)data.readIntPtr(); reply->writeInt32(fillBuffer(node, buffer)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); buffer_id buffer = (void*)data.readIntPtr(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); reply->writeInt32( emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_INTERFACE(IOMX, data, reply); node_id node = (void*)data.readIntPtr(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } }
bool Source::updateDispatched(uint source) { if (!valid()) return false; // Audio if (hasAudio()) { // Update time progression in the current buffer ::alGetSourcef(source, AL_SEC_OFFSET, &pSecondsCurrent); // Check if a buffer has finished playing ALint processed = 0; ::alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed); if (!processed) return true; // A buffer has finished playing, unqueue it ALuint buffer = Private::Media::OpenAL::UnqueueBufferFromSource(source); // Reset current buffer time pSecondsCurrent = 0.0f; uint bits = pAStream->bits(); uint channels = pAStream->channels(); uint frequency = pAStream->rate(); int bufferSize; ::alGetBufferi(buffer, AL_SIZE, &bufferSize); pSecondsElapsed += bufferSize * 8.0f / bits / frequency; // Get the next data to feed the buffer uint size = fillBuffer(); if (!size) return false; // Buffer the data with OpenAL and queue the buffer onto the source if (!Private::Media::OpenAL::SetBufferData(buffer, pAStream->alFormat(), pData.data(), size, frequency / channels)) return false; if (!Private::Media::OpenAL::QueueBufferToSource(buffer, source)) return false; } // Video if (hasVideo()) { /* if (hasAudio() and Private::Media::OpenAL::IsSourcePlaying(source)) { std::cout << "Video and audio sync !" << std::endl; // Try to sync with audio ALfloat elapsed; ::alGetSourcef(source, AL_SEC_OFFSET, &elapsed); while (!pFrames.empty() and elapsed > pFrames.front()->timestamp()) { pFrames.pop_front(); if (pFrames.empty()) fillQueue(); } } */ // TEMPORARY // The sync code is not working yet, just get some frames when we need them for now // if (pFrames.empty()) // fillQueue(); if (pFrames.empty()) // Failed to load anymore return false; } return true; }
Entity::Entity(const int _type, const short _x, const short _y, const short _w, const short _h, const char *_data, const WORD _colour) : Graphic(_x, _y, _w, _h), type(_type), colour(_colour) { fillBuffer(_data, _colour); }
point_count_t OptechReader::read(PointViewPtr data, point_count_t countRequested) { point_count_t numRead = 0; point_count_t dataIndex = data->size(); while (numRead < countRequested) { if (m_returnIndex == 0) { if (!m_extractor.good()) { if (m_recordIndex >= m_header.numRecords) { break; } m_recordIndex += fillBuffer(); } m_extractor >> m_pulse.gpsTime >> m_pulse.returnCount >> m_pulse.range[0] >> m_pulse.range[1] >> m_pulse.range[2] >> m_pulse.range[3] >> m_pulse.intensity[0] >> m_pulse.intensity[1] >> m_pulse.intensity[2] >> m_pulse.intensity[3] >> m_pulse.scanAngle >> m_pulse.roll >> m_pulse.pitch >> m_pulse.heading >> m_pulse.latitude >> m_pulse.longitude >> m_pulse.elevation; if (m_pulse.returnCount == 0) { m_returnIndex = 0; continue; } // In all the csd files that we've tested, the longitude // values have been less than -2pi. if (m_pulse.longitude < -M_PI * 2) { m_pulse.longitude = m_pulse.longitude + M_PI * 2; } else if (m_pulse.longitude > M_PI * 2) { m_pulse.longitude = m_pulse.longitude - M_PI * 2; } } georeference::Xyz gpsPoint = georeference::Xyz( m_pulse.longitude, m_pulse.latitude, m_pulse.elevation); georeference::RotationMatrix rotationMatrix = createOptechRotationMatrix(m_pulse.roll, m_pulse.pitch, m_pulse.heading); georeference::Xyz point = pdal::georeference::georeferenceWgs84( m_pulse.range[m_returnIndex], m_pulse.scanAngle, m_boresightMatrix, rotationMatrix, gpsPoint); data->setField(Dimension::Id::X, dataIndex, point.X * 180 / M_PI); data->setField(Dimension::Id::Y, dataIndex, point.Y * 180 / M_PI); data->setField(Dimension::Id::Z, dataIndex, point.Z); data->setField(Dimension::Id::GpsTime, dataIndex, m_pulse.gpsTime); if (m_returnIndex == MaximumNumberOfReturns - 1) { data->setField(Dimension::Id::ReturnNumber, dataIndex, m_pulse.returnCount); } else { data->setField(Dimension::Id::ReturnNumber, dataIndex, m_returnIndex + 1); } data->setField(Dimension::Id::NumberOfReturns, dataIndex, m_pulse.returnCount); data->setField(Dimension::Id::EchoRange, dataIndex, m_pulse.range[m_returnIndex]); data->setField(Dimension::Id::Intensity, dataIndex, m_pulse.intensity[m_returnIndex]); data->setField(Dimension::Id::ScanAngleRank, dataIndex, m_pulse.scanAngle * 180 / M_PI); if (m_cb) m_cb(*data, dataIndex); ++dataIndex; ++numRead; ++m_returnIndex; if (m_returnIndex >= m_pulse.returnCount || m_returnIndex >= MaximumNumberOfReturns) { m_returnIndex = 0; } } return numRead; }
//----------------------------------------------------------------------------- bool FileStream::_read(const U32 i_numBytes, void *o_pBuffer) { AssertFatal(0 != mStreamCaps, "FileStream::_read: the stream isn't open"); AssertFatal(NULL != o_pBuffer || i_numBytes == 0, "FileStream::_read: NULL destination pointer with non-zero read request"); if (!hasCapability(Stream::StreamRead)) { AssertFatal(false, "FileStream::_read: file stream lacks capability"); Stream::setStatus(IllegalCall); return(false); } // exit on pre-existing errors if (Ok != getStatus()) return(false); // if a request of non-zero length was made if (0 != i_numBytes) { U8 *pDst = (U8 *)o_pBuffer; U32 readSize; U32 remaining = i_numBytes; U32 bytesRead; U32 blockHead; U32 blockTail; // check if the buffer has some data in it if (BUFFER_INVALID != mBuffHead) { // copy as much as possible from the buffer into the destination readSize = ((mBuffTail + 1) >= mBuffPos) ? (mBuffTail + 1 - mBuffPos) : 0; readSize = getMin(readSize, remaining); calcBlockHead(mBuffPos, &blockHead); dMemcpy(pDst, mBuffer + (mBuffPos - blockHead), readSize); // reduce the remaining amount to read remaining -= readSize; // advance the buffer pointers mBuffPos += readSize; pDst += readSize; if (mBuffPos > mBuffTail && remaining != 0) { flush(); mBuffHead = BUFFER_INVALID; if (mEOF == true) Stream::setStatus(EOS); } } // if the request wasn't satisfied by the buffer and the file has more data if (false == mEOF && 0 < remaining) { // flush the buffer if its dirty, since we now need to go to disk if (true == mDirty) flush(); // make sure we know the current read location in the underlying file mBuffPos = mFile->getPosition(); calcBlockBounds(mBuffPos, &blockHead, &blockTail); // check if the data to be read falls within a single block if ((mBuffPos + remaining) <= blockTail) { // fill the buffer from disk if (true == fillBuffer(mBuffPos)) { // copy as much as possible from the buffer to the destination remaining = getMin(remaining, mBuffTail - mBuffPos + 1); dMemcpy(pDst, mBuffer + (mBuffPos - blockHead), remaining); // advance the buffer pointer mBuffPos += remaining; } else return(false); } // otherwise the remaining spans multiple blocks else { clearBuffer(); // read from disk directly into the destination bytesRead = mFile->read((char *)pDst, remaining); setStatus(); // check to make sure we read as much as expected if (Ok == getStatus() || EOS == getStatus()) { // if not, update the end-of-file status if (0 != bytesRead && EOS == getStatus()) { Stream::setStatus(Ok); mEOF = true; } } else return(false); } } } return(true); }
void MovedSound::rewind(double position) { playhead = position; fillBuffer(); }
// this method only support H.264 + AMR_NB void MediaStreamer::doCapture() { unsigned char *buf; buf = new unsigned char[MAX_VIDEO_PACKAGE]; unsigned int aseq = 0; unsigned int vseq = 0; const unsigned int STACK_SIZE = 128; std::list<int64_t> timestack; unsigned long last_ts = 0; // skip none useable heaer bytes fillBuffer( buf, mediaInfo.begin_skip); // fectching real time video data from camera while(1) { if ( fillBuffer(buf, 4) < 0) break; checking_buffer: if ( buf[0] == 0x00 ) { unsigned int vpkg_len = (buf[1] << 16) + (buf[2] << 8) + buf[3]; if ( fillBuffer(&buf[4], vpkg_len ) < 0) break; vpkg_len += 4; if ( vpkg_len > (unsigned int)MAX_VIDEO_PACKAGE ) { LOGD("ERROR: Drop big video frame...."); vseq++; fillBuffer(vpkg_len); continue; } int slice_type = 0; if ( (buf[5] & 0xF8 ) == 0xB8) { slice_type = 1; } else if ( ((buf[5] & 0xFF) == 0x88) && ((buf[5] & 0x80) == 0x80) ) { slice_type = 1; } else if ( (buf[5] & 0xE0) == 0xE0) { slice_type = 0; } else if ( (buf[5] & 0xFE) == 0x9A) { slice_type = 0; } buf[0] = 0x00; buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x01; #if 1 // computing the current package's timestamp int64_t cts = getCurrentTime() / 1000; if( timestack.size() >= STACK_SIZE) { timestack.pop_back(); timestack.push_front(cts); } else { timestack.push_front(cts); } if ( timestack.size() < STACK_SIZE) { cts = (timestack.size() - 1) * 100; // default = 10 fps last_ts = (unsigned long)cts; } else { unsigned long total_ms; total_ms = timestack.front() - timestack.back(); cts = last_ts + total_ms / (STACK_SIZE - 1); last_ts = cts; } mediaBuffer->PushBuffer( buf, vpkg_len, last_ts, slice_type ? MEDIA_TYPE_VIDEO_KEYFRAME : MEDIA_TYPE_VIDEO); #else vseq ++; mediaBuffer->PushBuffer( buf, vpkg_len, vseq * 1000 / mediaInfo.video_frame_rate, slice_type ? MEDIA_TYPE_VIDEO_KEYFRAME : MEDIA_TYPE_VIDEO); #endif } else { // fetching AMR_NB audio package static const unsigned char packed_size[16] = {12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0}; unsigned int mode = (buf[0]>>3) & 0x0F; unsigned int size = packed_size[mode] + 1; if ( size > 4) { if ( fillBuffer(&buf[4], size - 4) < 0) break; aseq ++; //SignalNewPackage(buf, 32, ats, MEDIA_TYPE_AUDIO); } else { fillBuffer(&buf[4], size ); for(int i = 0; i < 4; i++) buf[i] = buf[size+i]; //SignalNewPackage(buf, 32, ats, MEDIA_TYPE_AUDIO); goto checking_buffer; } } } delete buf; }
// this method support any camera, but will generating error video package. void MediaStreamer::doCapture2() { std::deque<unsigned char> video_check_pattern; video_check_pattern.resize(9, 0x00); unsigned char *buf; buf = new unsigned char[1024*512]; /* FILE *fp = fopen ("/sdcard/streaming.flv", "wb"); flvPackager->setParameter(640, 480, 30); flvPackager->addVideoHeader(&mediaInfo.sps_data[0], mediaInfo.sps_data.size(), &mediaInfo.pps_data[0], mediaInfo.pps_data.size()); fwrite(flvPackager->getBuffer(), flvPackager->bufferLength(), 1, fp); flvPackager->resetBuffer(); */ LOGD("Native: Begin capture"); unsigned int last_frame_num = 0; int frame_count = 0; while(1) { if ( infd < 0) break; // find video slice data from es streaming unsigned char current_byte; if ( read(infd, ¤t_byte, 1) < 0) break; video_check_pattern.pop_front(); video_check_pattern.push_back(current_byte); int slice_type; unsigned int frame_num; int nal_length = checkSingleSliceNAL( video_check_pattern, slice_type, frame_num ); if ( nal_length > 0) { if ( (slice_type == 0) && (frame_num != (last_frame_num + 1) ) ) { LOGD("Error, wrong number, FIXME FIXME"); { char temp[512]; snprintf(temp, 512, "ST=%d, FN=%d, NAL=%d, LFN=%d, FNL=%d, 0x%02x%02x%02x%02x", slice_type, frame_num, nal_length, last_frame_num, frame_num_length, video_check_pattern[5],video_check_pattern[6],video_check_pattern[7],video_check_pattern[8] ); //LOGD(temp); } //last_frame_num = frame_num; continue; } last_frame_num = frame_num; for(int i = 0; i < (int)video_check_pattern.size(); i++) { buf[i] = video_check_pattern[i]; } if ( fillBuffer( &buf[video_check_pattern.size()] , nal_length - (video_check_pattern.size() - 4) ) < 0) break; /* flvPackager->addVideoFrame( buf, nal_length + 4, slice_type, frame_count*30); fwrite(flvPackager->getBuffer(), flvPackager->bufferLength(), 1, fp); flvPackager->resetBuffer(); */ mediaBuffer->PushBuffer( buf, nal_length + 4, frame_count*88, slice_type ? MEDIA_TYPE_VIDEO_KEYFRAME : MEDIA_TYPE_VIDEO); frame_count++; } } delete buf; }
WinHelpPhraseFile::WinHelpPhraseFile(QFile &file, qint64 off, QTextCodec *codec, bool compressed, bool mvbHint) : phrases(), phrasesRaw() { PRINT_DBG("Loading WinHelp phrase file at %lld", off); if (codec == NULL) { throw std::runtime_error("Codec is NULL"); } seekFile(file, off); InternalDirectoryFileHeader hdr(file, off); if (compressed) { if (mvbHint) { seekFile(file, off + InternalDirectoryFileHeader::size); quint16 eightHundr = readUnsignedWord(file); quint16 nPhr = readUnsignedWord(file); quint16 oneHundr = readUnsignedWord(file); if ((eightHundr == 0x0800) && (oneHundr == 0x0100) && (nPhr != 0)) { PRINT_DBG( "Loading compressed WinHelp phrase file, MVB alternative"); seekFile(file, off + InternalDirectoryFileHeader::size); quint16 eightHundred = readUnsignedWord(file); PRINT_DBG(" Eight hundred: %d", eightHundred); quint16 numPhrases = readUnsignedWord(file); PRINT_DBG(" Num phrases: %d", numPhrases); quint16 oneHundred = readUnsignedWord(file); PRINT_DBG(" One hundred: %d", oneHundred); if (oneHundred != 0x0100) { throw std::runtime_error("Not a WinHelp phrase file"); } quint32 uncompressedSize = readUnsignedDWord(file); PRINT_DBG(" Uncompressed size: %d", uncompressedSize); for (int i = 0; i < 30; i++) { quint8 unused = readUnsignedByte(file); PRINT_DBG(" Unused: %d", unused); } QScopedArrayPointer<uint> phraseOffset( new uint[static_cast<size_t> (numPhrases + 1)]); PRINT_DBG("Reading phrase offsets at %lld", file.pos()); for (quint16 index = 0; index < numPhrases + 1; index++) { phraseOffset[index] = static_cast<uint> (readUnsignedWord( file)); PRINT_DBG(" Phrase offset: %d", phraseOffset[index]); } qint64 inputLength = off + hdr.getReservedSpace() - file.pos(); PRINT_DBG("Reading compressed phrases at %lld", file.pos()); QScopedArrayPointer<quint8> uncompressedPhrases( new quint8[static_cast<size_t> (uncompressedSize)]); unpackLZ77(file, file.pos(), inputLength, uncompressedPhrases.data(), static_cast<size_t> (uncompressedSize)); size_t pointer = static_cast<size_t> (0); for (quint16 index = 0; index < numPhrases; index++) { uint size = phraseOffset[index + 1] - phraseOffset[index]; QString phrase = readFixedLengthStringFromBuffer( uncompressedPhrases.data(), static_cast<size_t> (uncompressedSize), pointer, size, codec); this->phrases.append(phrase); QScopedArrayPointer<quint8> phraseRaw( new quint8[static_cast<size_t> (size)]); copyBytesFromBuffer( reinterpret_cast<const void *> (uncompressedPhrases. data()), static_cast<size_t> (uncompressedSize), pointer, static_cast<size_t> (size), reinterpret_cast<void *> (phraseRaw.data()), static_cast<size_t> (size)); this->phrasesRaw.append(QByteArray( reinterpret_cast<const char *> (phraseRaw.data()), static_cast<int> (size))); pointer += static_cast<size_t> (size); PRINT_DBG(" Phrase: %s", phrase.toLocal8Bit().data()); } } else { PRINT_DBG("Loading compressed WinHelp phrase file"); seekFile(file, off + InternalDirectoryFileHeader::size); quint16 numPhrases = readUnsignedWord(file); PRINT_DBG(" Num phrases: %d", numPhrases); quint16 oneHundred = readUnsignedWord(file); PRINT_DBG(" One hundred: %d", oneHundred); if (oneHundred != 0x0100) { throw std::runtime_error("Not a WinHelp phrase file"); } quint32 uncompressedSize = readUnsignedDWord(file); PRINT_DBG(" Uncompressed size: %d", uncompressedSize); QScopedArrayPointer<uint> phraseOffset( new uint[static_cast<size_t> (numPhrases + 1)]); PRINT_DBG("Reading phrase offsets at %lld", file.pos()); for (quint16 index = 0; index < numPhrases + 1; index++) { phraseOffset[index] = static_cast<uint> (readUnsignedWord( file)); PRINT_DBG(" Phrase offset: %d", phraseOffset[index]); } PRINT_DBG("Reading compressed phrases at %lld", file.pos()); qint64 inputLength = off + hdr.getReservedSpace() - file.pos(); QScopedArrayPointer<quint8> uncompressedPhrases( new quint8[static_cast<size_t> (uncompressedSize)]); unpackLZ77(file, file.pos(), inputLength, uncompressedPhrases.data(), static_cast<size_t> (uncompressedSize)); size_t pointer = static_cast<size_t> (0); for (quint16 index = 0; index < numPhrases; index++) { uint size = phraseOffset[index + 1] - phraseOffset[index]; QString phrase = readFixedLengthStringFromBuffer( uncompressedPhrases.data(), static_cast<size_t> (uncompressedSize), pointer, size, codec); this->phrases.append(phrase); QScopedArrayPointer<quint8> phraseRaw( new quint8[static_cast<size_t> (size)]); copyBytesFromBuffer( reinterpret_cast<const void *> (uncompressedPhrases. data()), static_cast<size_t> (uncompressedSize), pointer, static_cast<size_t> (size), reinterpret_cast<void *> (phraseRaw.data()), static_cast<size_t> (size)); this->phrasesRaw.append(QByteArray( reinterpret_cast<const char *> (phraseRaw.data()), static_cast<int> (size))); pointer += static_cast<size_t> (size); PRINT_DBG(" Phrase: %s", phrase.toLocal8Bit().data()); } } } else { PRINT_DBG("Loading compressed WinHelp phrase file"); seekFile(file, off + InternalDirectoryFileHeader::size); quint16 numPhrases = readUnsignedWord(file); PRINT_DBG(" Num phrases: %d", numPhrases); quint16 oneHundred = readUnsignedWord(file); PRINT_DBG(" One hundred: %d", oneHundred); if (oneHundred != 0x0100) { throw std::runtime_error("Not a WinHelp phrase file"); } quint32 uncompressedSize = readUnsignedDWord(file); PRINT_DBG(" Uncompressed size: %d", uncompressedSize); QScopedArrayPointer<uint> phraseOffset( new uint[static_cast<size_t> (numPhrases + 1)]); PRINT_DBG("Reading phrase offsets at %lld", file.pos()); for (quint16 index = 0; index < numPhrases + 1; index++) { phraseOffset[index] = static_cast<uint> (readUnsignedWord(file)); PRINT_DBG(" Phrase offset: %d", phraseOffset[index]); } PRINT_DBG("Reading compressed phrases at %lld", file.pos()); qint64 inputLength = off + hdr.getReservedSpace() - file.pos(); QScopedArrayPointer<quint8> uncompressedPhrases( new quint8[static_cast<size_t> (uncompressedSize)]); unpackLZ77(file, file.pos(), inputLength, uncompressedPhrases.data(), static_cast<size_t> (uncompressedSize)); size_t pointer = static_cast<size_t> (0); for (quint16 index = 0; index < numPhrases; index++) { uint size = phraseOffset[index + 1] - phraseOffset[index]; QString phrase = readFixedLengthStringFromBuffer( uncompressedPhrases.data(), static_cast<size_t> (uncompressedSize), pointer, size, codec); this->phrases.append(phrase); QScopedArrayPointer<quint8> phraseRaw( new quint8[static_cast<size_t> (size)]); copyBytesFromBuffer( reinterpret_cast<const void *> (uncompressedPhrases.data()), static_cast<size_t> (uncompressedSize), pointer, static_cast<size_t> (size), reinterpret_cast<void *> (phraseRaw.data()), static_cast<size_t> (size)); this->phrasesRaw.append(QByteArray( reinterpret_cast<const char *> (phraseRaw.data()), static_cast<int> (size))); pointer += static_cast<size_t> (size); PRINT_DBG(" Phrase: %s", phrase.toLocal8Bit().data()); } } } else { PRINT_DBG("Loading uncompressed WinHelp phrase file"); seekFile(file, off + InternalDirectoryFileHeader::size); quint16 numPhrases = readUnsignedWord(file); PRINT_DBG(" Num phrases: %d", numPhrases); quint16 oneHundred = readUnsignedWord(file); PRINT_DBG(" One hundred: %d", oneHundred); if (oneHundred != 0x0100) { throw std::runtime_error("Not a WinHelp phrase file"); } QScopedArrayPointer<uint> phraseOffset( new uint[static_cast<size_t> (numPhrases + 1)]); PRINT_DBG("Reading phrase offsets at %lld", file.pos()); for (quint16 index = 0; index < numPhrases + 1; index++) { phraseOffset[index] = static_cast<uint> (readUnsignedWord(file)); PRINT_DBG(" Phrase offset: %d", phraseOffset[index]); } PRINT_DBG("Reading phrases at %lld", file.pos()); for (quint16 index = 0; index < numPhrases; index++) { uint size = phraseOffset[index + 1] - phraseOffset[index]; qint64 posMem = file.pos(); QString phrase = readFixedLengthString(file, size, codec); this->phrases.append(phrase); QScopedArrayPointer<quint8> phraseRaw( new quint8[static_cast<size_t> (size)]); seekFile(file, posMem); fillBuffer(file, static_cast<qint64> (size), reinterpret_cast<void *> (phraseRaw.data()), static_cast<size_t> (size)); this->phrasesRaw.append(QByteArray( reinterpret_cast<const char *> (phraseRaw.data()), static_cast<int> (size))); PRINT_DBG(" Phrase: %s", phrase.toLocal8Bit().data()); } } PRINT_DBG("WinHelp phrase file loaded successfully"); }
VorbisFileReader::VorbisFileReader(wstring file_name, int buffer_size_request) : buffer_size_request(buffer_size_request) #else VorbisFileReader::VorbisFileReader(string file_name, int buffer_size_request) : buffer_size_request(buffer_size_request) #endif { #ifdef __MINGW32__ file = _wfopen(file_name.c_str(), L"rb"); #else file = fopen(file_name.c_str(), "rb"); #endif if (file == NULL) { throwError(etCantOpen, L"constructor (1)"); } // Opening vorbis file int ret = ov_open_callbacks(file, &vf, NULL, 0, OV_CALLBACKS_NOCLOSE); if (ret < 0) { throwVorbisError(ret, L"constructor (2)"); } if (ret == 0) { // Reading the comments char **ptr = ov_comment(&vf, -1)->user_comments; vorbis_info *vi = ov_info(&vf, -1); while (*ptr) { comments.push_back(string(*ptr)); ++ptr; } bitsPerSecond = ov_bitrate(&vf, -1); channels = vi->channels; rate = vi->rate; read_buffer = new float[channels]; vendor = string(ov_comment(&vf,-1)->vendor); length = ov_time_total(&vf, -1); playhead = 0; fillBuffer(); } } VorbisFileReader::~VorbisFileReader() { delete [] read_buffer; ov_clear(&vf); if (file != NULL) fclose(file); } const float* VorbisFileReader::readSample() { bool playhead_was_negative = playhead < 0; cursor_position_in_buffer ++; updatePlayhead(); if (playhead >= 0 && playhead_was_negative) // if we have just stepped into the sound { fillBuffer(); } if (buffer_actual_size > 0) // if the buffer isn't empty { if (cursor_position_in_buffer >= buffer_actual_size) // if the buffer has run away { fillBuffer(); } for (int i = 0; i < channels; i++) // filling the read buffer with the sound buffer sample at position { read_buffer[i] = buffer[i][cursor_position_in_buffer]; } } else { for (int i = 0; i < channels; i++) // filling the read buffer with zeroes { read_buffer[i] = 0.f; } } return read_buffer; }
uint64 readBuffer::read(void *buf, uint64 len) { char *bufchar = (char *)buf; // Handle the mmap'd file first. if (_mmap) { uint64 c = 0; while ((_bufferPos < _bufferLen) && (c < len)) { bufchar[c++] = _buffer[_bufferPos++]; _filePos++; } if (c == 0) _eof = true; return(c); } // Easy case; the next len bytes are already in the buffer; just // copy and move the position. if (_bufferLen - _bufferPos > len) { memcpy(bufchar, _buffer + _bufferPos, len); _bufferPos += len; fillBuffer(); _filePos += len; return(len); } // Existing buffer not big enough. Copy what's there, then finish // with a read. uint64 bCopied = 0; // Number of bytes copied into the buffer uint64 bRead = 0; // Number of bytes read into the buffer uint64 bAct = 0; // Number of bytes actually read from disk memcpy(bufchar, _buffer + _bufferPos, _bufferLen - _bufferPos); bCopied = _bufferLen - _bufferPos; _bufferPos = _bufferLen; while (bCopied + bRead < len) { errno = 0; bAct = (uint64)::read(_file, bufchar + bCopied + bRead, len - bCopied - bRead); if (errno) fprintf(stderr, "readBuffer()-- couldn't read "F_U64" bytes from '%s': n%s\n", len, _filename, strerror(errno)), exit(1); // If we hit EOF, return a short read if (bAct == 0) len = 0; bRead += bAct; } fillBuffer(); _filePos += bCopied + bRead; return(bCopied + bRead); }
//-------------------------------------- bool ZipSubRStream::_read(const U32 in_numBytes, void *out_pBuffer) { m_lastBytesRead = 0; if (in_numBytes == 0) return true; AssertFatal(out_pBuffer != NULL, "NULL output buffer"); if (getStatus() == Closed) { AssertFatal(false, "Attempted read from closed stream"); return false; } if (Ok != getStatus()) return false; if (m_EOS) { setStatus(EOS); return true; }; // Ok, we need to call inflate() until the output buffer is full. // first, set up the output portion of the z_stream // m_pZipStream->next_out = (Bytef*)out_pBuffer; m_pZipStream->avail_out = in_numBytes; m_pZipStream->total_out = 0; while (m_pZipStream->avail_out != 0) { S32 retVal = Z_OK; if(m_pZipStream->avail_in == 0) { // check if there is more output pending inflate(m_pZipStream, Z_SYNC_FLUSH); if(m_pZipStream->total_out != in_numBytes) { // Need to provide more input bytes for the stream to read... U32 buffSize = fillBuffer(csm_inputBufferSize); //AssertFatal(buffSize != 0, "Must find a more graceful way to handle this"); m_pZipStream->next_in = m_pInputBuffer; m_pZipStream->avail_in = buffSize; m_pZipStream->total_in = 0; } } // need to get more? if(m_pZipStream->total_out != in_numBytes) retVal = inflate(m_pZipStream, Z_SYNC_FLUSH); AssertFatal(retVal != Z_BUF_ERROR, "Should never run into a buffer error"); AssertFatal(retVal == Z_OK || retVal == Z_STREAM_END, "error in the stream"); m_lastBytesRead = m_pZipStream->total_out; if (retVal == Z_STREAM_END) { if (m_pZipStream->avail_out != 0) m_EOS = true; setStatus(EOS); m_currentPosition += m_pZipStream->total_out; return true; } } AssertFatal(m_pZipStream->total_out == in_numBytes, "Error, didn't finish the decompression!"); // If we're here, everything went peachy... setStatus(Ok); m_currentPosition += m_pZipStream->total_out; return true; }
int main(int argc, char **argv) { usb_dev_handle *handle = NULL; const uchar rawVid[2] = {USB_CFG_VENDOR_ID}, rawPid[2] = {USB_CFG_DEVICE_ID}; char vendor[] = {USB_CFG_VENDOR_NAME, 0}, product[] = {USB_CFG_DEVICE_NAME, 0}; char txBuffer[64], rxBuffer[64]; int cnt, vid, pid, i, j; usb_init(); /* compute VID/PID from usbconfig.h so that there is a central source of information */ vid = rawVid[1] * 256 + rawVid[0]; pid = rawPid[1] * 256 + rawPid[0]; /* The following function is in opendevice.c: */ if(usbOpenDevice(&handle, vid, vendor, pid, product, NULL, NULL, NULL) != 0){ fprintf(stderr, "Could not find USB device \"%s\" with vid=0x%x pid=0x%x\n", product, vid, pid); exit(1); } if(argc > 1 && strcasecmp(argv[1], "osccal") == 0){ if(argc > 2){ /* set osccal */ int osccal = atoi(argv[2]); printf("setting osccal to %d\n", osccal); cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_SET_OSCCAL, osccal, 0, txBuffer, 0, 5000); if(cnt < 0){ fprintf(stderr, "\nUSB error setting osccal: %s\n", usb_strerror()); } }else{ cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_GET_OSCCAL, 0, 0, rxBuffer, 1, 5000); if(cnt < 0){ fprintf(stderr, "\nUSB error getting osccal: %s\n", usb_strerror()); }else{ printf("osccal = %d\n", (unsigned char)rxBuffer[0]); } } }else{ srandomdev(); for(i = 0; i <= 100000; i++){ fillBuffer(txBuffer, sizeof(txBuffer)); cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, CUSTOM_RQ_SET_DATA, 0, 0, txBuffer, sizeof(txBuffer), 5000); if(cnt < 0){ fprintf(stderr, "\nUSB tx error in iteration %d: %s\n", i, usb_strerror()); break; }else if(cnt != sizeof(txBuffer)){ fprintf(stderr, "\nerror in iteration %d: %d bytes sent instead of %d\n", i, cnt, (int)sizeof(txBuffer)); break; } for(j = 0; j < sizeof(rxBuffer); j++){ rxBuffer[j] = ~txBuffer[j]; } cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_GET_DATA, 0, 0, rxBuffer, sizeof(rxBuffer), 5000); if(cnt < 0){ fprintf(stderr, "\nUSB rx error in iteration %d: %s\n", i, usb_strerror()); break; }else if(cnt != sizeof(txBuffer)){ fprintf(stderr, "\nerror in iteration %d: %d bytes received instead of %d\n", i, cnt, (int)sizeof(rxBuffer)); break; } if(compareBuffers(txBuffer, rxBuffer, sizeof(rxBuffer))){ fprintf(stderr, "\ncompare error in iteration %d.\n", i); break; } if(i != 0 && i % 100 == 0){ printf("."); fflush(stdout); if(i % 5000 == 0) printf(" %6d\n", i); } } fprintf(stderr, "\nTest completed.\n"); } usb_close(handle); return 0; }
/*------------------------------------------------------------* * WIN32 Version * * This uses FindNextFile, et al. to negotiate the dir tree. * * This works differently from the POSIX version, as there is * no seek on the windows variant of the dir functions, I will * do the seek on the 'back end' of the search. * * I wish I had made a note of how differed change worked when * I wrote it. I think that if the last file is a good one, I * need to change the directory level after I have handled the * file. I think this because I am one file behind, the get * next mechanism that Win32 uses. * * Windows is a pain in the ar*e. *------------------------------------------------------------*/ int find_next_file(DIR_ENTRY* dir_tree,int* curr_dir,char** extention_list,char* filename,int recursive) { int count,infile = -1, found = 0; char *dot; /* handle the case when the last file is a file that we are * looking for. */ if (defered_change != 0) { if (defered_change == -1) { dir_tree[*curr_dir].name[0] = '\0'; }else{ dir_tree[(*curr_dir)+1].name = dir_tree[*curr_dir].name + dir_tree[*curr_dir].size; dir_tree[(*curr_dir)+1].size = hold_size; memcpy(dir_tree[(*curr_dir)+1].name,hold_path,hold_size); dir_tree[(*curr_dir)+1].name[dir_tree[(*curr_dir)+1].size++] = DIR_DELIMETER; dir_tree[(*curr_dir)+1].name[dir_tree[(*curr_dir)+1].size] = '\0'; } (*curr_dir) += defered_change; defered_change = 0; } if (*curr_dir < MAX_DEPTH && *curr_dir > -1) { do { /* check to see if current file in directory is one we are looking for */ if (dir_tree[*curr_dir].dir != INVALID_HANDLE_VALUE) { count = 0; if ((dot = strrchr(FileData.cFileName,'.')) != NULL) { while(extention_list[count] != NULL && !found) { if (strcmp(dot,extention_list[count]) == 0) { /* found a file with one of the extention */ if ((infile = open(FileData.cFileName,READ_FILE_STATUS)) != -1) { strncpy(filename,FileData.cFileName,NAME_MAX); fillBuffer(infile); found = 1; } } count++; } } } /* now get the next file ready */ if (!FindNextFile(dir_tree[*curr_dir].dir, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) { FindClose(dir_tree[*curr_dir].dir); chdir(".."); /*BUG FIX: unix fix for symbolic links broke WIN 32 version */ /* we dont want to change the name before we have used it */ if (found) { defered_change = -1; }else{ dir_tree[*curr_dir].name[0] = '\0'; (*curr_dir)--; } } }else{ if (FileData.dwFileAttributes | FILE_ATTRIBUTE_DIRECTORY) { if (FileData.cFileName[0] != '.') { if (recursive) { /* we have a directory, lets move into it */ if(chdir(FileData.cFileName) != -1) { /* BUG FIX: Oh my god this code was poor! now does what it supposed to */ if (!found) { /* change the directory */ dir_tree[(*curr_dir)+1].name = dir_tree[*curr_dir].name + dir_tree[*curr_dir].size; dir_tree[(*curr_dir)+1].size = cpystrlen(dir_tree[(*curr_dir)+1].name,FileData.cFileName,NAME_MAX); dir_tree[(*curr_dir)+1].name[dir_tree[(*curr_dir)+1].size++] = DIR_DELIMETER; dir_tree[(*curr_dir)+1].name[dir_tree[(*curr_dir)+1].size] = '\0'; dir_tree[(*curr_dir)+1].dir = FindFirstFile("*.*",&FileData); (*curr_dir)++; }else{ /* we want to defer changing directory until after we have used it */ hold_size = strnlen(FileData.cFileName,NAME_MAX); memcpy(hold_path,FileData.cFileName,hold_size); defered_change = 1; dir_tree[(*curr_dir)+1].dir = FindFirstFile("*.*",&FileData); } } } } } } } while(!found && *curr_dir > -1 && *curr_dir < MAX_DEPTH); } /* Known fault: * If the last but one file is end of the directory and about to go up a level, then * it will do the last file twice. */ return infile; }
std::string scigraphics::sprintfNumberStyle::numberText( const number Number ) const { char Buf[64]; fillBuffer( Buf, sizeof(Buf), Number ); return std::string(Buf); }
int main(int argc, char* argv[]){ FILE *inputFile; //done int breakMe = 0, lastRead = 0; char *buffer, *tmpChar; //done long i=0, j=0, n=0, l=0, colAmt=0, rowAmt=0, fileSize=0, k=atoi(argv[2]); long closePoint = 0; long iterCount = 0; double *M, *centers1, *centers2, *tmpCenters, *centerWeights; //done //Variable allocation and initialization inputFile = fopen(argv[1], "r"); buffer = malloc(memBlock); M = malloc(memBlock); srand(time(NULL)); fgets(buffer, memBlock, inputFile); tmpChar = strtok(buffer, delims); while(tmpChar != NULL){ ++colAmt; tmpChar = strtok(NULL, delims); } rowAmt = memBlock/(sizeof(double)*colAmt); fseek(inputFile, 0, SEEK_END); fileSize = ftell(inputFile); rewind(inputFile); centers1 = (double*) malloc(sizeof(double)*k*colAmt); centers2 = (double*) malloc(sizeof(double)*k*colAmt); centerWeights = (double*) malloc(sizeof(double)*k); /*******SEEDING**********************/ tmpChar = NULL; lastRead = 0; do{ fillBuffer(inputFile, fileSize, buffer); for(i=0;i<(rowAmt*colAmt); ++i){ if(tmpChar == NULL){ if(lastRead){ breakMe=1; break; } else{ lastRead = fillBuffer(inputFile, fileSize, buffer); tmpChar = strtok(buffer, delims); } } M[i] = atof(tmpChar); tmpChar = strtok(NULL, delims); } }while(i<(rowAmt*colAmt) && !breakMe); breakMe = 0; for(j=0; j<k; ++j){ centerWeights[j] = 0; memmove(centers1+(j*colAmt), M+((rand()%(i/colAmt))*colAmt), sizeof(double)*colAmt); memmove(centers2+(j*colAmt), centers1+(j*colAmt), sizeof(double)*colAmt); } /********CLUSTERING**********************/ rewind(inputFile); tmpChar = NULL; lastRead = 0; breakMe = 0; iterCount = 0; for(n=0; n<10; ++n){ do{ do{ for(i=0;i<(rowAmt*colAmt); ++i){ if(tmpChar == NULL){ if(lastRead){ breakMe=1; break; } else{ printf("%zu : %lu\r", ftell(inputFile), fileSize); lastRead = fillBuffer(inputFile, fileSize, buffer); tmpChar = strtok(buffer, delims); } } M[i] = atof(tmpChar); tmpChar = strtok(NULL, delims); } for(j=0; j<(i/colAmt); ++j){ closePoint = findClosest(M+(j*colAmt), centers1, colAmt, k); for(l=0; l<colAmt; ++l){ centers2[closePoint*colAmt+l] = ((centers2[closePoint*colAmt+l] * centerWeights[closePoint]) + M[j*colAmt + l]) / (centerWeights[closePoint] +1); } ++centerWeights[closePoint]; } }while(!breakMe); /*******PRINT CENTERS************************ printf("---CENTERS---\n"); for(j=0;j<k; ++j){ printf("%lu: ", j+1); for(l=0; l<colAmt; ++l) printf("%f ", centers2[j*colAmt + l]); printf("\n"); } ********************************************/ for(i=0;i<k;++i) centerWeights[i] = 0; tmpCenters = centers1; centers1 = centers2; centers2 = tmpCenters; breakMe = 0; lastRead = 0; rewind(inputFile); ++iterCount; if(iterCount > iterLimit){ printf("ITERLIMITBREAK\n"); break; } }while(centerDiff(centers1, centers2, .0001, k, colAmt)); } printf("---CENTERS---\n"); for(j=0;j<k; ++j){ printf("%lu: ", j+1); for(l=0; l<colAmt; ++l) printf("%f ", centers2[j*colAmt + l]); printf("\n"); } fclose(inputFile); free(buffer); free(M); free(centers1); free(centers2); free(centerWeights); return 1; }
ANTLR3_API void fillBufferExt(pANTLR3_COMMON_TOKEN_STREAM tokenStream) { fillBuffer(tokenStream); }
int main(int argc, char **argv) { gfxInitDefault(); PrintConsole botScreen; PrintConsole topScreen; consoleInit(GFX_TOP, &topScreen); consoleInit(GFX_BOTTOM, &botScreen); consoleSelect(&topScreen); constexpr size_t NUM_SAMPLES = 160*200; u32 *audio_buffer = (u32*)linearAlloc(NUM_SAMPLES * sizeof(u32)); fillBuffer(audio_buffer, NUM_SAMPLES); AudioState state; { auto dspfirm = loadDspFirmFromFile(); if (!dspfirm) { printf("Couldn't load firmware\n"); goto end; } auto ret = audioInit(*dspfirm); if (!ret) { printf("Couldn't init audio\n"); goto end; } state = *ret; } state.waitForSync(); initSharedMem(state); state.write().dsp_configuration->mixer1_enabled_dirty = true; state.write().dsp_configuration->mixer1_enabled = true; //state.write().dsp_configuration->limiter_enabled = 1; state.notifyDsp(); printf("init\n"); state.waitForSync(); state.notifyDsp(); state.waitForSync(); for (auto& gain : state.write().source_configurations->config[0].gain) { for (auto& g : gain) { g = 0.0; } } state.write().source_configurations->config[0].gain[0][0] = 1.0; state.write().source_configurations->config[0].gain[1][0] = 1.0; state.write().source_configurations->config[0].gain[1][1] = 0.5; state.write().source_configurations->config[0].gain_1_dirty = true; state.notifyDsp(); state.waitForSync(); state.notifyDsp(); state.waitForSync(); state.notifyDsp(); { while (true) { state.waitForSync(); printf("sync = %i, play = %i, cbi = %i\n", state.read().source_statuses->status[0].sync, state.read().source_statuses->status[0].is_enabled, state.read().source_statuses->status[0].current_buffer_id); if (state.read().source_statuses->status[0].sync == 1) break; state.notifyDsp(); } printf("fi: %i\n", state.frame_id); u16 buffer_id = 0; //unsigned next_queue_position = 0; state.write().source_configurations->config[0].play_position = 0; state.write().source_configurations->config[0].physical_address = osConvertVirtToPhys(audio_buffer); state.write().source_configurations->config[0].length = NUM_SAMPLES; state.write().source_configurations->config[0].mono_or_stereo = DSP::HLE::SourceConfiguration::Configuration::MonoOrStereo::Stereo; state.write().source_configurations->config[0].format = DSP::HLE::SourceConfiguration::Configuration::Format::PCM16; state.write().source_configurations->config[0].fade_in = false; state.write().source_configurations->config[0].adpcm_dirty = false; state.write().source_configurations->config[0].is_looping = false; state.write().source_configurations->config[0].buffer_id = ++buffer_id; state.write().source_configurations->config[0].partial_reset_flag = true; state.write().source_configurations->config[0].play_position_dirty = true; state.write().source_configurations->config[0].embedded_buffer_dirty = true; state.write().source_configurations->config[0].enable = true; state.write().source_configurations->config[0].enable_dirty = true; state.notifyDsp(); bool continue_reading = true; for (size_t frame_count = 0; continue_reading; frame_count++) { state.waitForSync(); if (state.read().source_statuses->status[0].current_buffer_id) { printf("%i cbi = %i\n", frame_count, state.read().source_statuses->status[0].current_buffer_id); } for (size_t i = 0; i < 160; i++) { if (state.write().intermediate_mix_samples->mix1.pcm32[0][i]) { printf("[intermediate] frame=%i, sample=%i\n", frame_count, i); for (size_t j = 0; j < 20; j++) { printf("%08lx ", (u32)state.write().intermediate_mix_samples->mix1.pcm32[0][j]); } printf("\n"); break; } } for (size_t i = 0; i < 160 * 2; i++) { if (state.read().final_samples->pcm16[i]) { printf("[final] frame=%i, sample=%i\n", frame_count, i); for (size_t j = 0; j < 20; j++) { printf("%04x ", (u16)state.read().final_samples->pcm16[j]); } printf("\n"); continue_reading = false; break; } } state.notifyDsp(); } state.waitForSync(); state.write().source_configurations->config[0].sync = 2; state.write().source_configurations->config[0].sync_dirty = true; state.notifyDsp(); while (true) { state.waitForSync(); printf("sync = %i, play = %i\n", state.read().source_statuses->status[0].sync, state.read().source_statuses->status[0].is_enabled); if (state.read().source_statuses->status[0].sync == 2) break; state.notifyDsp(); } state.notifyDsp(); printf("Done!\n"); } end: audioExit(state); waitForKey(); gfxExit(); return 0; }
/*------------------------------------------------------------* * POSIX Version * * This uses opendir, et al. to negotiate the dir tree. * * The rather strange way I neg. the tree is due to the presents * of symbolic links. These are now partially transversed. *------------------------------------------------------------*/ int find_next_file(DIR_ENTRY* dir_tree,int* curr_dir,char** extention_list,char* filename,int recursive) { int found = 0,count; int infile = -1; char cur_dirname[256],*dot; struct dirent* d_ent; struct stat dir_stat; if (*curr_dir < MAX_DEPTH && *curr_dir > -1) { do { if ((d_ent = readdir(dir_tree[*curr_dir].dir)) != NULL) { /* check to see if its a directory */ if (d_ent->d_name[0] != '.') { /* NOTE: This is BAD code. It ignores ALL hidden files */ if (stat(d_ent->d_name, &dir_stat) != -1) { if (S_ISDIR(dir_stat.st_mode)) { /* dont go into the directory if the 'recursive' flag is not set */ if (recursive) { /* lets add the name to the full path */ *curr_dir = *curr_dir + 1; dir_tree[*curr_dir].dir = opendir(d_ent->d_name); if (dir_tree[*curr_dir].dir == NULL) { /* failed to open the directory */ *curr_dir = *curr_dir - 1; }else{ dir_tree[*curr_dir].name = dir_tree[*curr_dir-1].name + dir_tree[*curr_dir-1].size; dir_tree[*curr_dir].size = cpystrlen(dir_tree[*curr_dir].name,d_ent->d_name,NAME_MAX); dir_tree[*curr_dir].name[dir_tree[*curr_dir].size++] = DIR_DELIMETER; dir_tree[*curr_dir].name[dir_tree[*curr_dir].size] = '\0'; /* lets walk into this directory */ chdir(d_ent->d_name); } } }else{ /* found 'rightmost' file -- position back to * the file we have just read. */ if ((dot = strrchr(d_ent->d_name,'.')) != NULL) { count = 0; /* we have an extension-list find a file */ while(extention_list[count] != NULL && !found) { if (strcmp(dot,extention_list[count]) == 0) { /* found a file with one of the extension */ if ((infile = open(d_ent->d_name,READ_FILE_STATUS)) != -1) { fillBuffer(infile); found = 1; } } count++; } } } } } }else{ /* we are now at the end of a (empty?) dir * let go back up a level */ dir_tree[*curr_dir].name[0] = '\0'; chdir(".."); closedir(dir_tree[*curr_dir].dir); *curr_dir = *curr_dir - 1; } } while(!found && *curr_dir > -1 && *curr_dir < MAX_DEPTH); } /* report the file name */ if (found) strcpy(filename,d_ent->d_name); return infile; }
u8 MemoryOsSpecific::getByte( u64 offset ) const { u8 value = 0; fillBuffer(&value, offset, 1); return value; }
NewFontDescriptor::NewFontDescriptor(QFile &file, qint64 off) : FontDescriptor(NEW_FONT_DESCRIPTOR) { PRINT_DBG("Reading New font descriptor at %lld", off); seekFile(file, off); quint8 unknownByte1 = readUnsignedByte(file); PRINT_DBG(" Unknown byte 1: %d", unknownByte1); this->facenameIndex = readUnsignedWord(file); PRINT_DBG(" Facename index: %d", this->facenameIndex); this->fgColor = readRGBBytes(file); PRINT_DBG(" Fg Red: %d", qRed(this->fgColor)); PRINT_DBG(" Fg Green: %d", qGreen(this->fgColor)); PRINT_DBG(" Fg Blue: %d", qBlue(this->fgColor)); this->bgColor = readRGBBytes(file); PRINT_DBG(" Bg Red: %d", qRed(this->bgColor)); PRINT_DBG(" Bg Green: %d", qGreen(this->bgColor)); PRINT_DBG(" Bg Blue: %d", qBlue(this->bgColor)); quint8 unknownBytes2[5] = { 0, 0, 0, 0, 0 }; fillBuffer(file, Q_INT64_C( 5), reinterpret_cast<void *>(&unknownBytes2), static_cast<size_t>(5)); PRINT_DBG(" Unknown byte 2-1: %d", unknownBytes2[0]); PRINT_DBG(" Unknown byte 2-2: %d", unknownBytes2[1]); PRINT_DBG(" Unknown byte 2-3: %d", unknownBytes2[2]); PRINT_DBG(" Unknown byte 2-4: %d", unknownBytes2[3]); PRINT_DBG(" Unknown byte 2-5: %d", unknownBytes2[4]); this->height = readSignedDWord(file); PRINT_DBG(" Height: %d", this->height); this->width = readSignedDWord(file); PRINT_DBG(" Width: %d", this->width); this->escapement = readSignedDWord(file); PRINT_DBG(" Escapement: %d", this->escapement); this->orientation = readSignedDWord(file); PRINT_DBG(" Orientation: %d", this->orientation); this->weight = readSignedDWord(file); PRINT_DBG(" Weight: %d", this->weight); quint8 italicByte = readUnsignedByte(file); this->italic = false; if(italicByte != 0) { this->italic = true; PRINT_DBG(" Italic font"); } quint8 underlineByte = readUnsignedByte(file); this->underline = false; if(underlineByte != 0) { this->underline = true; PRINT_DBG(" Underline font"); } quint8 strikeoutByte = readUnsignedByte(file); this->strikeOut = false; if(strikeoutByte != 0) { this->strikeOut = true; PRINT_DBG(" Strike out font"); } this->charset = readUnsignedByte(file); PRINT_DBG(" Charset: %d", this->charset); this->outPrecision = readUnsignedByte(file); PRINT_DBG(" Out precision: %d", this->outPrecision); this->clipPrecision = readUnsignedByte(file); PRINT_DBG(" Clip precision: %d", this->clipPrecision); this->quality = readUnsignedByte(file); PRINT_DBG(" Quality: %d", this->quality); quint8 pitchAndFamily = readUnsignedByte(file); this->pitch = pitchAndFamily & 0x03; PRINT_DBG(" Pitch: %d", this->pitch); this->family = (((pitchAndFamily & 0xF0) >> 4) & 0x0F); PRINT_DBG(" Family: %d", this->family); PRINT_DBG("New font descriptor loaded successfully"); }
/*! * \brief Get the next token in the stream */ HllTokenizer::Token HllTokenizer::getNext() { Token next; // Start out by moving past any whitespace skipCharacters(whitespace); // Check if we've reached the end of the file if(!fillBuffer(1)) { next = createToken(Token::TypeEnd, ""); return next; } // Scan through the list of literals and see if any match if(scanLiteral(literals, next)) { return next; } // If no literals matched, see if an identifier can be constructed if(std::isalpha(buffer()[0]) || buffer()[0] == '_') { size_t len = 0; while(std::isalpha(buffer()[len]) || buffer()[len] == '_') { len++; if(!fillBuffer(len + 1)) { break; } } TokenType type = TypeIdentifier; std::string string = buffer().substr(0, len); // Check if the string is a keyword for(std::string &keyword : keywords) { if(string == keyword) { type = TypeLiteral; break; } } // Construct a token out of the characters found next = createToken(type, string); emptyBuffer(len); return next; } // If an identifier couldn't be found, check for a number if(std::isdigit(buffer()[0])) { size_t len = 0; while(std::isdigit(buffer()[len])) { len++; if(!fillBuffer(len + 1)) { break; } } // Construct a token out of the characters found next = createToken(TypeNumber, buffer().substr(0, len)); emptyBuffer(len); return next; } if(buffer()[0] == '\"') { size_t len = 1; while(true) { if(!fillBuffer(len + 1)) { setError("Unterminated string literal"); return next; } if(buffer()[len] == '\"') { break; } len++; } // Construct a token out of the characters found std::string text = buffer().substr(1, len - 1); emptyBuffer(len + 1); if(evaluateEscapes(text)) { next = createToken(TypeString, text); } return next; } if(buffer()[0] == '\'') { size_t len = 1; while(true) { if(!fillBuffer(len + 1)) { setError("Unterminated character literal"); return next; } if(buffer()[len] == '\'') { break; } len++; } // Construct a token out of the characters found std::string text = buffer().substr(1, len - 1); emptyBuffer(len + 1); if(evaluateEscapes(text)) { if(text.size() == 1) { next = createToken(TypeChar, text); } else { setError("Invalid character literal"); } } return next; } // Nothing matched, log an error std::stringstream ss; ss << "Illegal symbol '" << buffer()[0] << "'"; setError(ss.str()); return next; }