PRUint8 FCGXStream::RecvByte() { // See if the current block is exhausted. while (mRecvBytesLeftInBlock == 0) { if (!RecvNextBlock(PR_TRUE)) return 0; } // Next, see if we need to receive more bytes from the socket. if (mRecvIn == mRecvOut) { mRecvIn = 0; FillBuffer(); if (mFD == INVALID_SOCKET) return 0; } mRecvBytesLeftInBlock--; g_recv.LogContents(mRecvBuf + mRecvOut, 1); return mRecvBuf[mRecvOut++]; }
int DirectSoundDrv_PCM_BeginPlayback(char *BufferStart, int BufferSize, int NumDivisions, void ( *CallBackFunc )( void ) ) { HRESULT err; if (!Initialised) { ErrorCode = DSErr_Uninitialised; return DSErr_Error; } DirectSoundDrv_PCM_StopPlayback(); MixBuffer = BufferStart; MixBufferSize = BufferSize; MixBufferCount = NumDivisions; MixBufferCurrent = 0; MixBufferUsed = 0; MixCallBack = CallBackFunc; // prime the buffer FillBuffer(0); mixThread = CreateThread(NULL, 0, fillDataThread, 0, 0, 0); if (!mixThread) { ErrorCode = DSErr_CreateThread; return DSErr_Error; } SetThreadPriority(mixThread, THREAD_PRIORITY_HIGHEST); err = IDirectSoundBuffer_Play(lpdsbsec, 0, 0, DSBPLAY_LOOPING); if (FAILED( err )) { ErrorCode = DSErr_PlaySecondary; return DSErr_Error; } Playing = 1; return DSErr_Ok; }
/* Given: DataFile A text file stream already opened for input. FileName The name of this text file (as a char array string). Task: To copy data from this file stream into sorted files (runs). Return: DataFile The modified file stream is trivially modified by reading from it. In the function name the number of runs is returned. The sorted runs themselves are created and stored under the file names: ExtSortTemp.0, ExtSortTemp.1, etc. */ int MakeSortedRuns(fstream & DataFile, PathType FileName) { fstream OutFile; StringType Word, Extension; PathType OutFileName; int NumWords, k, NumFiles = 0; BufType Buffer; bool MoreData; // Repeatedly fill one buffer and quicksort it, writing the buffer out to a temp file. DataFile.getline(Word, MaxString); if (DataFile.fail()) MoreData = false; else MoreData = true; while (MoreData) { // Fill one buffer. NumWords = FillBuffer(DataFile, Buffer, MoreData, Word); QuickSort(Buffer, 0, NumWords - 1); // Construct the temp file name. strcpy(OutFileName, "ExtSortTemp."); _itoa(NumFiles, Extension, 10); // Convert the int in NumFiles to a char array string. strcat(OutFileName, Extension); OutFile.open(OutFileName, ios::out); if (OutFile.fail()) Error("Could not open the file named ", OutFileName); for (k = 0; k < NumWords; k++) OutFile << Buffer[k] << endl; OutFile.close(); NumFiles++; } return NumFiles; }
int BC_Example_Bridge(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) { int err = -EFAULT; int command = _IOC_NR(cmd); BC_Example_ioctl_package sBridge; if (copy_from_user(&sBridge, (void *)arg, sizeof(sBridge)) != 0) { return err; } switch(command) { case _IOC_NR(BC_Example_ioctl_fill_buffer): { if(FillBuffer(sBridge.inputparam) == -1) { return err; } break; } case _IOC_NR(BC_Example_ioctl_get_buffer_count): { if(GetBufferCount(&sBridge.outputparam) == -1) { return err; } break; } default: return err; } if (copy_to_user((void *)arg, &sBridge, sizeof(sBridge)) != 0) { return err; } return 0; }
HRESULT D3D9RenderImpl::Display(BYTE* pYplane, BYTE* pVplane, BYTE* pUplane) { if(!pYplane) { return E_POINTER; } if(m_format == D3DFMT_NV12 && !pVplane) { return E_POINTER; } if(m_format == D3DFMT_YV12 && (!pVplane || !pUplane)) { return E_POINTER; } HR(CheckDevice()); HR(FillBuffer(pYplane, pVplane, pUplane)); HR(CreateScene()); return Present(); }
bool CWinGlkOGGSound::Play(int iRepeat, int iVolume, bool PauseState) { m_pReadPtr = m_pData; if (m_pReadPtr == NULL) return false; // Open the stream ov_callbacks VorbisCBs; VorbisCBs.read_func = VorbisRead; VorbisCBs.close_func = VorbisClose; VorbisCBs.seek_func = VorbisSeek; VorbisCBs.tell_func = VorbisTell; if (ov_open_callbacks(this,&m_Stream,NULL,0,VorbisCBs) < 0) return false; m_StreamOpen = true; vorbis_info* Info = ov_info(&m_Stream,-1); // Create a buffer if (CreateBuffer(Info->channels,Info->rate,16) == false) return false; // Set the duration of the sample if (iRepeat > 0) m_Duration = (DWORD)ceil(1000.0 * iRepeat * ov_time_total(&m_Stream,-1)); else m_Duration = -1; // Fill the buffer with sample data m_iRepeat = (iRepeat < 0) ? -1 : iRepeat - 1; if (FillBuffer(GetBufferSize()) == false) return false; // Set the volume for the buffer SetVolume(iVolume); // Start the buffer playing return PlayBuffer(PauseState); }
bool DART::Play () { Stopped = WaitStreamEnd = false; BytesPlayed = 0; int buffcount; for (buffcount = 0; buffcount < BufferCount; buffcount++) if (!FillBuffer (&MixBuffers [buffcount])) break; if (buffcount == 0) Stopped = WaitStreamEnd = true; else { APIRET rc = MixSetupParms.pmixWrite (MixSetupParms.ulMixHandle, &MixBuffers [0], buffcount); if (rc) { mciGetErrorString (rc, (PSZ) ErrorCode, sizeof (ErrorCode)); return FALSE; } } return TRUE; }
/// @brief Play /// @param start /// @param count /// void DirectSoundPlayer::Play(int64_t start,int64_t count) { // Make sure that it's stopped Stop(); // The thread is now guaranteed dead HRESULT res; // We sure better have a buffer assert(buffer); // Set variables startPos = start; endPos = start+count; playPos = start; offset = 0; // Fill whole buffer FillBuffer(true); DWORD play_flag = 0; if (count*provider->GetBytesPerSample() > bufSize) { // Start thread thread = new DirectSoundPlayerThread(this); thread->Create(); thread->Run(); play_flag = DSBPLAY_LOOPING; } // Play buffer->SetCurrentPosition(0); res = buffer->Play(0,0,play_flag); if (SUCCEEDED(res)) playing = true; startTime = GetTickCount(); // Update timer if (displayTimer && !displayTimer->IsRunning()) displayTimer->Start(15); }
int CAudioRenderer::OutputAudio(BYTE* pData, UINT nDataByteSize) { CAutoLock cObjectLock(this); if (GetState() & STATE_WAITFORRESOURCES) { memset(pData, 0, nDataByteSize); return S_OK; } //Log("nDataByteSize = %d\n", nDataByteSize); if (!(GetState() & STATE_EXECUTE)) { memset(pData, 0, nDataByteSize); //Log("audio 1\n"); return E_FAIL; } if (m_vecInObjs[0]->IsEOS() && m_PcmPool.GetSize() < nDataByteSize) { SetEOS(); memset(pData, 0, nDataByteSize); //Log("audio 2\n"); return E_FAIL; } FillBuffer(pData, nDataByteSize); while (!m_pRefClock->IsStarted()) { m_ASync.Wait(10000); if (m_bFlush || m_bClose || m_bInterrupt) break; } if (m_bInterrupt) { memset(pData, 0, nDataByteSize); } //Log("audio 3\n"); return S_OK; }
int GetBufferSceMp3(short* buf,int length,float amp,int channel) { int byteLength = length<<2,i=0; if (streamsSceMp3[channel].paused || !streamsSceMp3[channel].initialized) { memset(buf,0,byteLength); return PSPAALIB_WARNING_PAUSED_BUFFER_REQUESTED; } while(streamsSceMp3[channel].bufSize<byteLength) { if(sceMp3CheckStreamDataNeeded(streamsSceMp3[channel].handle)) { FillBuffer(channel); } short* decodeBuf; int bytesDecoded=sceMp3Decode(streamsSceMp3[channel].handle,&decodeBuf); if (bytesDecoded <= 0) break; streamsSceMp3[channel].buf=(u8*)realloc(streamsSceMp3[channel].buf,streamsSceMp3[channel].bufSize+bytesDecoded); memcpy(streamsSceMp3[channel].buf+streamsSceMp3[channel].bufSize,decodeBuf,bytesDecoded); streamsSceMp3[channel].bufSize+=bytesDecoded; } unsigned char byte1, byte2; int how_many = (streamsSceMp3[channel].bufSize > byteLength ? byteLength : streamsSceMp3[channel].bufSize); for (i=0;i<2*length;i++) { byte1 = (2*i >= how_many) ? 0 : streamsSceMp3[channel].buf[2*i]; byte2 = (2*i+1 >= how_many) ? 0 : streamsSceMp3[channel].buf[2*i+1]; buf[i]=((short)(byte1 | byte2<<8))*amp; } streamsSceMp3[channel].bufSize-=how_many; memmove(streamsSceMp3[channel].buf,streamsSceMp3[channel].buf+how_many,streamsSceMp3[channel].bufSize); return PSPAALIB_SUCCESS; }
static DWORD WINAPI fillDataThread(LPVOID lpParameter) { DWORD waitret, waitret2; HANDLE handles[] = { handles[0] = notifyPositions[0].hEventNotify, handles[1] = notifyPositions[1].hEventNotify, handles[2] = notifyPositions[2].hEventNotify }; UNREFERENCED_PARAMETER(lpParameter); do { waitret = WaitForMultipleObjects(3, handles, FALSE, INFINITE); switch (waitret) { case WAIT_OBJECT_0: case WAIT_OBJECT_0+1: waitret2 = WaitForSingleObject(mutex, INFINITE); if (waitret2 == WAIT_OBJECT_0) { FillBuffer(WAIT_OBJECT_0 + 1 - waitret); ReleaseMutex(mutex); } else { if (MV_Printf) MV_Printf( "DirectSound fillDataThread: wfso err %d\n", (int32_t) waitret2); } break; case WAIT_OBJECT_0+2: // initprintf( "DirectSound fillDataThread: exiting\n"); ExitThread(0); break; default: if (MV_Printf) MV_Printf( "DirectSound fillDataThread: wfmo err %d\n", (int32_t) waitret); break; } } while (1); return 0; }
/** * Consume characters until you find the terminal char * * @update gess 3/25/98 * @param aString receives new data from stream * @param addTerminal tells us whether to append terminal to aString * @return error code */ nsresult nsScanner::ReadWhitespace(nsScannerSharedSubstring& aString, PRInt32& aNewlinesSkipped, PRBool& aHaveCR) { aHaveCR = PR_FALSE; if (!mSlidingBuffer) { return kEOF; } PRUnichar theChar = 0; nsresult result = Peek(theChar); if (NS_FAILED(result)) { return result; } nsScannerIterator origin, current, end; PRBool done = PR_FALSE; origin = mCurrentPosition; current = origin; end = mEndPosition; PRBool haveCR = PR_FALSE; while(!done && current != end) { switch(theChar) { case '\n': case '\r': { ++aNewlinesSkipped; PRUnichar thePrevChar = theChar; theChar = (++current != end) ? *current : '\0'; if ((thePrevChar == '\r' && theChar == '\n') || (thePrevChar == '\n' && theChar == '\r')) { theChar = (++current != end) ? *current : '\0'; // CRLF == LFCR => LF haveCR = PR_TRUE; } else if (thePrevChar == '\r') { // Lone CR becomes CRLF; callers should know to remove extra CRs AppendUnicodeTo(origin, current, aString); aString.writable().Append(PRUnichar('\n')); origin = current; haveCR = PR_TRUE; } } break; case ' ' : case '\t': theChar = (++current != end) ? *current : '\0'; break; default: done = PR_TRUE; AppendUnicodeTo(origin, current, aString); break; } } SetPosition(current); if (current == end) { AppendUnicodeTo(origin, current, aString); result = FillBuffer(); } aHaveCR = haveCR; return result; }
/// parses input stream bool LVRtfParser::Parse() { //m_conv_table = GetCharsetByte2UnicodeTable( L"cp1251" ); bool errorFlag = false; m_callback->OnStart(this); // make fb2 document structure m_callback->OnTagOpen( NULL, L"?xml" ); m_callback->OnAttribute( NULL, L"version", L"1.0" ); m_callback->OnAttribute( NULL, L"encoding", L"utf-8" ); //m_callback->OnEncoding( GetEncodingName().c_str(), GetCharsetTable( ) ); m_callback->OnTagBody(); m_callback->OnTagClose( NULL, L"?xml" ); m_callback->OnTagOpenNoAttr( NULL, L"FictionBook" ); // DESCRIPTION m_callback->OnTagOpenNoAttr( NULL, L"description" ); m_callback->OnTagOpenNoAttr( NULL, L"title-info" ); // lString16 bookTitle = LVExtractFilenameWithoutExtension( getFileName() ); //m_stream->GetName(); m_callback->OnTagOpenNoAttr( NULL, L"book-title" ); if ( !bookTitle.empty() ) m_callback->OnText( bookTitle.c_str(), bookTitle.length(), 0 ); //queue.DetectBookDescription( m_callback ); m_callback->OnTagOpenNoAttr( NULL, L"title-info" ); m_callback->OnTagClose( NULL, L"description" ); // BODY m_callback->OnTagOpenNoAttr( NULL, L"body" ); //m_callback->OnTagOpen( NULL, L"section" ); // process text //queue.DoTextImport( m_callback ); //m_callback->OnTagClose( NULL, L"section" ); txtbuf = new lChar16[ MAX_TXT_SIZE+1 ]; txtpos = 0; txtfstart = 0; char cwname[33]; while ( !Eof() && !errorFlag && !m_stopped ) { // load next portion of data if necessary if ( m_buf_len - m_buf_pos < MIN_BUF_DATA_SIZE ) { if ( !FillBuffer( MIN_BUF_DATA_SIZE*2 ) ) { errorFlag = true; break; } } int len = (int)m_buf_len - (int)m_buf_pos; // check end of file if ( len <=0 ) break; //EOF const lUInt8 * p = m_buf + m_buf_pos; lUInt8 ch = *p++; if ( ch=='{' ) { OnBraceOpen(); m_buf_pos++; continue; } else if ( ch=='}' ) { OnBraceClose(); m_buf_pos++; continue; } lUInt8 ch2 = *p; if ( ch=='\\' && *p!='\'' ) { // control bool asteriskFlag = false; if ( ch2=='*' ) { ch = *(++p); ch2 = *(++p); asteriskFlag = true; } if ( (ch2>='A' && ch2<='Z') || (ch2>='a' && ch2<='z') ) { // control word int cwi = 0; do { cwname[cwi++] = ch2; ch2 = *++p; } while ( ( (ch2>='A' && ch2<='Z') || (ch2>='a' && ch2<='z') ) && cwi<32 ); cwname[cwi] = 0; int param = PARAM_VALUE_NONE; if ( ch2==' ' ) { p++; } else { if ( ch2 == '-' ) { p++; param = 0; for ( ;; ) { ch2 = *++p; if ( ch2<'0' || ch2>'9' ) break; param = param * 10 + (ch2-'0'); } param = -param; } else if ( ch2>='0' && ch2<='9' ) { param = 0; while ( ch2>='0' && ch2<='9' ) { param = param * 10 + (ch2-'0'); ch2 = *++p; } } if ( *p == ' ' ) p++; } // \uN -- unicode character if ( cwi==1 && cwname[0]=='u' ) { AddChar( (lChar16) (param & 0xFFFF) ); // if ( m_stack.getInt( pi_skip_ch_count )==0 ) // m_stack.set( pi_skip_ch_count, 1 ); } else { // usual control word OnControlWord( cwname, param, asteriskFlag ); } } else { // control char cwname[0] = ch2; cwname[1] = 0; p++; OnControlWord( cwname, PARAM_VALUE_NONE, asteriskFlag ); } m_buf_pos += p - (m_buf + m_buf_pos); } else { //lChar16 txtch = 0; if ( ch=='\\' ) { p++; int digit1 = charToHex( p[0] ); int digit2 = charToHex( p[1] ); p+=2; if ( digit1>=0 && digit2>=0 ) { AddChar8( (lChar8)((digit1 << 4) | digit2) ); } else { AddChar('\\'); AddChar('\''); AddChar8(digit1); AddChar8(digit2); p+=2; } } else { if ( ch>=' ' ) { AddChar8( ch ); } else { // wrong char } } //======================================================= //======================================================= m_buf_pos += p - (m_buf + m_buf_pos); } } m_callback->OnStop(); delete[] txtbuf; txtbuf = NULL; CommitText(); m_stack.getDestination()->OnAction(LVRtfDestination::RA_SECTION); m_callback->OnTagClose( NULL, L"body" ); m_callback->OnTagClose( NULL, L"FictionBook" ); return !errorFlag; }
size_t SysRead( b_file *io, char *b, size_t len ) //=============================================== { size_t bytes_read; size_t amt; size_t offs_in_b; size_t max_valid; if( io->attrs & BUFFERED ) { // determine the maximum valid position in the buffer max_valid = io->read_len; if( max_valid < io->high_water ) { max_valid = io->high_water; } // if we're beyond that position then we must fill the buffer if( io->b_curs >= max_valid ) { if( FillBuffer( io ) < 0 ) return( READ_ERROR ); max_valid = io->read_len; } amt = max_valid - io->b_curs; if( amt > len ) { amt = len; } memcpy( b, &io->buffer[io->b_curs], amt ); offs_in_b = amt; io->b_curs += amt; len -= amt; if( len ) { // flush the buffer if( FlushBuffer( io ) < 0 ) return( READ_ERROR ); if( len > io->buff_size ) { // read a multiple of io->buff_size bytes amt = len - len % io->buff_size; bytes_read = readbytes( io, b + offs_in_b, amt ); if( bytes_read == READ_ERROR ) return( READ_ERROR ); offs_in_b += bytes_read; if( bytes_read < amt ) return( offs_in_b ); len -= amt; } if( len ) { // first fill the buffer bytes_read = readbytes( io, io->buffer, io->buff_size ); if( bytes_read == READ_ERROR ) return( READ_ERROR ); io->attrs |= READ_AHEAD; io->read_len = bytes_read; // then grab our bytes from it if( len > bytes_read ) { len = bytes_read; } memcpy( b + offs_in_b, io->buffer, len ); io->b_curs = len; offs_in_b += len; } } return( offs_in_b ); } else { return( readbytes( io, b, len ) ); } }
static size_t GetTextRec( b_file *io, char *b, size_t len ) //========================================================= // Get a record from a TEXT file. { char ch; size_t read; char rs[2]; if( io->attrs & SEEK ) { // direct access if( SysRead( io, b, len ) == READ_ERROR ) return( 0 ); if( SysRead( io, rs, sizeof( char ) ) == READ_ERROR ) return( 0 ); if( rs[0] == LF ) return( len ); #if ! defined( __UNIX__ ) if( rs[0] == CR ) { if( SysRead( io, &rs[1], sizeof( char ) ) == READ_ERROR ) { return( 0 ); } if( rs[1] == LF ) return( len ); if( ( io->attrs & CARRIAGE_CONTROL ) && ( rs[1] == FF ) ) { return( len ); } } #endif FSetErr( IO_BAD_RECORD, io ); return( 0 ); } else if( io->attrs & BUFFERED ) { char *ptr; char *stop; bool seen_cr; bool trunc; size_t max_valid; // determine maximum valid position in the buffer max_valid = io->read_len; if( max_valid < io->high_water ) { max_valid = io->high_water; } stop = io->buffer + max_valid; ptr = io->buffer + io->b_curs; read = 0; seen_cr = false; trunc = false; for( ;; ) { if( ptr >= stop ) { io->b_curs = ptr - io->buffer; if( FillBuffer( io ) < 0 ) { // we have to do this so that io->b_curs is set properly // on end of file ptr = io->buffer + io->b_curs; if( read > 0 && io->stat == IO_EOF ) { IOOk( io ); } break; } stop = io->buffer + io->read_len; ptr = io->buffer + io->b_curs; } ch = *ptr; ++ptr; if( ch == LF ) break; if( !seen_cr ) { if( ch == CTRL_Z ) { --ptr; // give back char so we don't read past EOF if( read == 0 ) FSetEof( io ); break; } if( ch == CR ) { seen_cr = true; } else if( read < len ) { b[read] = ch; ++read; } else { trunc = true; } } else { if( ch == FF && (io->attrs & CARRIAGE_CONTROL) ) break; --ptr; // give back the char seen_cr = false; if( read < len ) { b[read] = CR; ++read; } else { trunc = true; } } } io->b_curs = ptr - io->buffer; if( trunc ) { FSetTrunc( io ); } return( read ); } else { // device (CON) read = 0; len = readbytes( io, b, len ); if( len == READ_ERROR ) return( 0 ); for( ;; ) { if( read == len ) break; #if defined( __UNIX__ ) || defined( __NETWARE__ ) if( *b == LF ) return( read ); #else if( *b == CR ) { ++b; if( read == len - 1 ) break; if( *b == LF ) return( read ); --b; } else if( *b == CTRL_Z ) { FSetEof( io ); return( read ); } #endif ++b; ++read; } FSetTrunc( io ); return( read ); } }
void PSIR_FileWriter::ParseFileResources ( LFA_FileRef fileRef, XMP_Uns32 length ) { bool ok; this->DeleteExistingInfo(); this->fileParsed = true; if ( length == 0 ) return; // Parse the image resource block. IOBuffer ioBuf; ioBuf.filePos = LFA_Seek ( fileRef, 0, SEEK_CUR ); XMP_Int64 psirOrigin = ioBuf.filePos; // Need this to determine the resource data offsets. XMP_Int64 fileEnd = ioBuf.filePos + length; std::string rsrcPName; while ( (ioBuf.filePos + (ioBuf.ptr - ioBuf.data)) < fileEnd ) { ok = CheckFileSpace ( fileRef, &ioBuf, 12 ); // The minimal image resource takes 12 bytes. if ( ! ok ) break; // Bad image resource. Throw instead? XMP_Int64 thisRsrcPos = ioBuf.filePos + (ioBuf.ptr - ioBuf.data); XMP_Uns32 type = GetUns32BE(ioBuf.ptr); XMP_Uns16 id = GetUns16BE(ioBuf.ptr+4); ioBuf.ptr += 6; // Advance to the resource name. XMP_Uns16 nameLen = ioBuf.ptr[0]; // ! The length for the Pascal string. XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2! ok = CheckFileSpace ( fileRef, &ioBuf, paddedLen+4 ); // Get the name text and the data length. if ( ! ok ) break; // Bad image resource. Throw instead? if ( nameLen > 0 ) rsrcPName.assign ( (char*)(ioBuf.ptr), paddedLen ); // ! Include the length byte and pad. ioBuf.ptr += paddedLen; // Move to the data length. XMP_Uns32 dataLen = GetUns32BE(ioBuf.ptr); XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total. ioBuf.ptr += 4; // Advance to the resource data. XMP_Int64 thisDataPos = ioBuf.filePos + (ioBuf.ptr - ioBuf.data); XMP_Int64 nextRsrcPos = thisDataPos + dataTotal; if ( type != k8BIM ) { XMP_Uns32 fullRsrcLen = (XMP_Uns32) (nextRsrcPos - thisRsrcPos); this->otherRsrcs.push_back ( OtherRsrcInfo ( (XMP_Uns32)thisRsrcPos, fullRsrcLen ) ); MoveToOffset ( fileRef, nextRsrcPos, &ioBuf ); continue; } InternalRsrcMap::value_type mapValue ( id, InternalRsrcInfo ( id, dataLen, kIsFileBased ) ); InternalRsrcMap::iterator newRsrc = this->imgRsrcs.insert ( this->imgRsrcs.end(), mapValue ); InternalRsrcInfo* rsrcPtr = &newRsrc->second; rsrcPtr->origOffset = (XMP_Uns32)thisDataPos; if ( nameLen > 0 ) { rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen ); if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); memcpy ( (void*)rsrcPtr->rsrcName, rsrcPName.c_str(), paddedLen ); // AUDIT: Safe, allocated enough bytes above. } if ( ! IsMetadataImgRsrc ( id ) ) { MoveToOffset ( fileRef, nextRsrcPos, &ioBuf ); continue; } rsrcPtr->dataPtr = malloc ( dataLen ); // ! Allocate after the IsMetadataImgRsrc check. if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); if ( dataTotal <= kIOBufferSize ) { // The image resource data fits within the I/O buffer. ok = CheckFileSpace ( fileRef, &ioBuf, dataTotal ); if ( ! ok ) break; // Bad image resource. Throw instead? memcpy ( (void*)rsrcPtr->dataPtr, ioBuf.ptr, dataLen ); // AUDIT: Safe, malloc'ed dataLen bytes above. ioBuf.ptr += dataTotal; // ! Add the rounded length. } else { // The image resource data is bigger than the I/O buffer. LFA_Seek ( fileRef, (ioBuf.filePos + (ioBuf.ptr - ioBuf.data)), SEEK_SET ); LFA_Read ( fileRef, (void*)rsrcPtr->dataPtr, dataLen ); FillBuffer ( fileRef, nextRsrcPos, &ioBuf ); } } #if 0 { printf ( "\nPSIR_FileWriter::ParseFileResources, count = %d\n", this->imgRsrcs.size() ); InternalRsrcMap::iterator irPos = this->imgRsrcs.begin(); InternalRsrcMap::iterator irEnd = this->imgRsrcs.end(); for ( ; irPos != irEnd; ++irPos ) { InternalRsrcInfo& thisRsrc = irPos->second; printf ( " #%d, dataLen %d, origOffset %d (0x%X)%s\n", thisRsrc.id, thisRsrc.dataLen, thisRsrc.origOffset, thisRsrc.origOffset, (thisRsrc.changed ? ", changed" : "") ); } } #endif } // PSIR_FileWriter::ParseFileResources
// the loop executed while running HRESULT FCapturePin::DoBufferProcessingLoop(void) { Command com; OnThreadStartPlay(); int32 LastFrame = -1; do { while (!CheckRequest(&com)) { // Wait for the next frame from the game thread if ( !GCaptureSyncEvent->Wait(1000) ) { FPlatformProcess::Sleep( 0.01f ); continue; // Reevaluate request } IMediaSample *pSample; int32 FrameNumber = FAVIWriter::GetInstance()->GetFrameNumber(); if (FrameNumber > LastFrame) { UE_LOG(LogMovieCapture, Log, TEXT(" FrameNumber > LastFrame = %d > %d"), FrameNumber, LastFrame); HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0); if (FAILED(hr)) { if (pSample) { pSample->Release(); } } else { LastFrame = FrameNumber; hr = FillBuffer(pSample); if (hr == S_OK) { hr = Deliver(pSample); pSample->Release(); // downstream filter returns S_FALSE if it wants us to // stop or an error if it's reporting an error. if(hr != S_OK) { UE_LOG(LogMovieCapture, Log, TEXT("Deliver() returned %08x; stopping"), hr); return S_OK; } } } } // Allow the game thread read more data GCaptureSyncEvent->Trigger(); } // For all commands sent to us there must be a Reply call! if (com == CMD_RUN || com == CMD_PAUSE) { Reply(NOERROR); } else if (com != CMD_STOP) { Reply((uint32) E_UNEXPECTED); } } while (com != CMD_STOP); return S_FALSE; }
uint8_t *FMultiPatchTexture::MakeTexture (FRenderStyle style) { // Add a little extra space at the end if the texture's height is not // a power of 2, in case somebody accidentally makes it repeat vertically. int numpix = Width * Height + (1 << HeightBits) - Height; uint8_t blendwork[256]; bool buildrgb = bComplex; auto Pixels = new uint8_t[numpix]; memset (Pixels, 0, numpix); if (style.Flags & STYLEF_RedIsAlpha) { buildrgb = !UseBasePalette(); } else { // For regular textures we can use paletted compositing if all patches are just being copied because they all can create a paletted buffer. if (!buildrgb) for (int i = 0; i < NumParts; ++i) { if (Parts[i].op != OP_COPY) { buildrgb = true; } } } if (!buildrgb) { for (int i = 0; i < NumParts; ++i) { if (Parts[i].Texture->bHasCanvas) continue; // cannot use camera textures as patch. uint8_t *trans = Parts[i].Translation? Parts[i].Translation->Remap : nullptr; { if (Parts[i].Blend != 0) { trans = GetBlendMap(Parts[i].Blend, blendwork); } Parts[i].Texture->CopyToBlock (Pixels, Width, Height, Parts[i].OriginX, Parts[i].OriginY, Parts[i].Rotate, trans, style); } } } else { // In case there are translucent patches let's do the composition in // True color to keep as much precision as possible before downconverting to the palette. uint8_t *buffer = new uint8_t[Width * Height * 4]; memset(buffer, 0, Width * Height * 4); FillBuffer(buffer, Width * 4, Height, TEX_RGB); for(int y = 0; y < Height; y++) { uint8_t *in = buffer + Width * y * 4; uint8_t *out = Pixels + y; for (int x = 0; x < Width; x++) { if (*out == 0 && in[3] != 0) { *out = RGBToPalette(style, in[2], in[1], in[0]); } out += Height; in += 4; } } delete [] buffer; } return Pixels; }
void Microphone( void *pvParameters ) { long lRetVal = -1; #ifdef MULTICAST //Wait for Network Connection while((!IS_IP_ACQUIRED(g_ulStatus))) { } #endif //MULTICAST while(1) { while(g_ucMicStartFlag || g_loopback) { int iBufferFilled = 0; iBufferFilled = GetBufferSize(pRecordBuffer); if(iBufferFilled >= (2*PACKET_SIZE)) { if(!g_loopback) { #ifndef MULTICAST lRetVal = sendto(g_UdpSock.iSockDesc, \ (char*)(pRecordBuffer->pucReadPtr),PACKET_SIZE,\ 0,(struct sockaddr*)&(g_UdpSock.Client),\ sizeof(g_UdpSock.Client)); if(lRetVal < 0) { UART_PRINT("Unable to send data\n\r"); LOOP_FOREVER(); } #else //MULTICAST lRetVal = SendMulticastPacket(); if(lRetVal < 0) { UART_PRINT("Unable to send data\n\r"); LOOP_FOREVER(); } #endif //MULTICAST } else { lRetVal = FillBuffer(pPlayBuffer,\ (unsigned char*)(pRecordBuffer->pucReadPtr), \ PACKET_SIZE); if(lRetVal < 0) { UART_PRINT("Unable to fill buffer\n\r"); } g_iReceiveCount++; } UpdateReadPtr(pRecordBuffer, PACKET_SIZE); g_iSentCount++; } } MAP_UtilsDelay(1000); } }
int ApplyBSDiffPatchMem(const unsigned char* old_data, ssize_t old_size, const Value* patch, ssize_t patch_offset, unsigned char** new_data, ssize_t* new_size) { // Patch data format: // 0 8 "BSDIFF40" // 8 8 X // 16 8 Y // 24 8 sizeof(newfile) // 32 X bzip2(control block) // 32+X Y bzip2(diff block) // 32+X+Y ??? bzip2(extra block) // with control block a set of triples (x,y,z) meaning "add x bytes // from oldfile to x bytes from the diff block; copy y bytes from the // extra block; seek forwards in oldfile by z bytes". unsigned char* header = (unsigned char*) patch->data + patch_offset; if (memcmp(header, "BSDIFF40", 8) != 0) { printf("corrupt bsdiff patch file header (magic number)\n"); return 1; } ssize_t ctrl_len, data_len; ctrl_len = offtin(header+8); data_len = offtin(header+16); *new_size = offtin(header+24); if (ctrl_len < 0 || data_len < 0 || *new_size < 0) { printf("corrupt patch file header (data lengths)\n"); return 1; } int bzerr; bz_stream cstream; cstream.next_in = patch->data + patch_offset + 32; cstream.avail_in = ctrl_len; cstream.bzalloc = NULL; cstream.bzfree = NULL; cstream.opaque = NULL; if ((bzerr = BZ2_bzDecompressInit(&cstream, 0, 0)) != BZ_OK) { printf("failed to bzinit control stream (%d)\n", bzerr); } bz_stream dstream; dstream.next_in = patch->data + patch_offset + 32 + ctrl_len; dstream.avail_in = data_len; dstream.bzalloc = NULL; dstream.bzfree = NULL; dstream.opaque = NULL; if ((bzerr = BZ2_bzDecompressInit(&dstream, 0, 0)) != BZ_OK) { printf("failed to bzinit diff stream (%d)\n", bzerr); } bz_stream estream; estream.next_in = patch->data + patch_offset + 32 + ctrl_len + data_len; estream.avail_in = patch->size - (patch_offset + 32 + ctrl_len + data_len); estream.bzalloc = NULL; estream.bzfree = NULL; estream.opaque = NULL; if ((bzerr = BZ2_bzDecompressInit(&estream, 0, 0)) != BZ_OK) { printf("failed to bzinit extra stream (%d)\n", bzerr); } *new_data = malloc(*new_size); if (*new_data == NULL) { printf("failed to allocate %ld bytes of memory for output file\n", (long)*new_size); return 1; } off_t oldpos = 0, newpos = 0; off_t ctrl[3]; off_t len_read; int i; unsigned char buf[24]; while (newpos < *new_size) { // Read control data if (FillBuffer(buf, 24, &cstream) != 0) { printf("error while reading control stream\n"); return 1; } ctrl[0] = offtin(buf); ctrl[1] = offtin(buf+8); ctrl[2] = offtin(buf+16); if (ctrl[0] < 0 || ctrl[1] < 0) { printf("corrupt patch (negative byte counts)\n"); return 1; } // Sanity check if (newpos + ctrl[0] > *new_size) { printf("corrupt patch (new file overrun)\n"); return 1; } // Read diff string if (FillBuffer(*new_data + newpos, ctrl[0], &dstream) != 0) { printf("error while reading diff stream\n"); return 1; } // Add old data to diff string for (i = 0; i < ctrl[0]; ++i) { if ((oldpos+i >= 0) && (oldpos+i < old_size)) { (*new_data)[newpos+i] += old_data[oldpos+i]; } } // Adjust pointers newpos += ctrl[0]; oldpos += ctrl[0]; // Sanity check if (newpos + ctrl[1] > *new_size) { printf("corrupt patch (new file overrun)\n"); return 1; } // Read extra string if (FillBuffer(*new_data + newpos, ctrl[1], &estream) != 0) { printf("error while reading extra stream\n"); return 1; } // Adjust pointers newpos += ctrl[1]; oldpos += ctrl[2]; } BZ2_bzDecompressEnd(&cstream); BZ2_bzDecompressEnd(&dstream); BZ2_bzDecompressEnd(&estream); return 0; }
inline unsigned long LowFirstBitReader::PeekBits(unsigned int length) { bool result = FillBuffer(length); assert(result); return m_buffer & (((unsigned long)1 << length) - 1); }
int main() { /************************************ * INITIALIZATIONS ************************************/ // Set up Camera VDMA VDMAInit(FrameBuffer); // Set up Compositor unsigned int threshold = 0x0CCC0FFF; CompositorInit(FrameBuffer, DrawBuffer, DisplayBuffer, threshold); // Initialize Buffers FillBuffer(FrameBuffer,0x00ff0000); //black FillBuffer(DrawBuffer,0x0); //black FillBuffer(DisplayBuffer,0x0); //black // Turn on Display Display(DisplayBuffer); /************************************ * MAIN LOOP ************************************/ while(1){ // Capture a Frame // -We are guaranteed a single frame because Microblaze is faster than // 30Hz, so as long as we don't sleep to early, we are guaranteed // VDMA will write a single frame and stop, decreasing the sleep // value more will not make a difference, may cause no frame to be written // -If there is a compositor/VMDA race condition, use VDMAStopAndWait() VDMAStart(); sleep(500000); VDMAStop(); // Run Compositor // -Super slow, need to accelerate CompositorRun(); // LED Detection & Draw on Drawing Buffer // -Currently this appears to give very large unchanging values //unsigned int x = CompositorGetXPos(); //unsigned int y = CompositorGetYPos(); // find the white blobs Vector blobList; vector_init(&blobList); // search region: 80 pix box at the center OnePass(&blobList, (char*) FrameBuffer, 640/2, 480/2, 240); // draw the found blobs int i, avg_x, avg_y, radius; struct Blob blob; for (i = 0; i < blobList.size; i ++){ blob = vector_get(&blobList, i); avg_x = blob.total_x/blob.count; avg_y = blob.total_y/blob.count; radius = sqrt(blob.count)/2; //DrawSqure(avg_x, avg_y, radius, 2, (char*) DrawBuffer, 15, 15, 15); FillColor(avg_x-radius, avg_y-radius, avg_x+radius, avg_y+radius, (char*) DrawBuffer, 0, 0, 15); } } }
HRESULT CAudioPin::DoBufferProcessingLoop(void) { if (!m_bConnected) { return S_OK; m_bThreadRunning = false; } Command com; OnThreadStartPlay(); m_bThreadRunning = true; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); do { while (!CheckRequest(&com)) { IMediaSample *pSample; HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0); if (FAILED(hr)) { Sleep(1); continue; // go round again. Perhaps the error will go away // or the allocator is decommited & we will be asked to // exit soon. } // Virtual function user will override. hr = FillBuffer(pSample); if (hr == S_OK) { // Some decoders seem to crash when we provide empty samples if ((pSample->GetActualDataLength() > 0) && !m_pTsReaderFilter->IsStopping() && m_bConnected) { hr = Deliver(pSample); m_sampleCount++ ; } else { m_bDiscontinuity = true; } pSample->Release(); // downstream filter returns S_FALSE if it wants us to // stop or an error if it's reporting an error. if(hr != S_OK) { DbgLog((LOG_TRACE, 2, TEXT("Deliver() returned %08x; stopping"), hr)); m_bThreadRunning = false; return S_OK; } } else if (hr == S_FALSE) { // derived class wants us to stop pushing data pSample->Release(); DeliverEndOfStream(); m_bThreadRunning = false; return S_OK; } else { // derived class encountered an error pSample->Release(); DbgLog((LOG_ERROR, 1, TEXT("Error %08lX from FillBuffer!!!"), hr)); DeliverEndOfStream(); m_pFilter->NotifyEvent(EC_ERRORABORT, hr, 0); m_bThreadRunning = false; return hr; } // all paths release the sample } // For all commands sent to us there must be a Reply call! if (com == CMD_RUN || com == CMD_PAUSE) { Reply(NOERROR); } else if (com != CMD_STOP) { Reply((DWORD) E_UNEXPECTED); DbgLog((LOG_ERROR, 1, TEXT("Unexpected command!!!"))); } } while (com != CMD_STOP); m_bThreadRunning = false; return S_FALSE; }
BOOL CALLBACK DlgProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static BOOL bShutOff, bClosing ; static HWAVEOUT hWaveOut ; static HWND hwndScroll ; static int iFreq = FREQ_INIT ; static PBYTE pBuffer1, pBuffer2 ; static PWAVEHDR pWaveHdr1, pWaveHdr2 ; static WAVEFORMATEX waveformat ; int iDummy ; switch (message) { case WM_INITDIALOG: hwndScroll = GetDlgItem (hwnd, IDC_SCROLL) ; SetScrollRange (hwndScroll, SB_CTL, FREQ_MIN, FREQ_MAX, FALSE) ; SetScrollPos (hwndScroll, SB_CTL, FREQ_INIT, TRUE) ; SetDlgItemInt (hwnd, IDC_TEXT, FREQ_INIT, FALSE) ; return TRUE ; case WM_HSCROLL: switch (LOWORD (wParam)) { case SB_LINELEFT: iFreq -= 1 ; break ; case SB_LINERIGHT: iFreq += 1 ; break ; case SB_PAGELEFT: iFreq /= 2 ; break ; case SB_PAGERIGHT: iFreq *= 2 ; break ; case SB_THUMBTRACK: iFreq = HIWORD (wParam) ; break ; case SB_TOP: GetScrollRange (hwndScroll, SB_CTL, &iFreq, &iDummy) ; break ; case SB_BOTTOM: GetScrollRange (hwndScroll, SB_CTL, &iDummy, &iFreq) ; break ; } iFreq = max (FREQ_MIN, min (FREQ_MAX, iFreq)) ; SetScrollPos (hwndScroll, SB_CTL, iFreq, TRUE) ; SetDlgItemInt (hwnd, IDC_TEXT, iFreq, FALSE) ; return TRUE ; case WM_COMMAND: switch (LOWORD (wParam)) { case IDC_ONOFF: // If turning on waveform, hWaveOut is NULL if (hWaveOut == NULL) { // Allocate memory for 2 headers and 2 buffers pWaveHdr1 = malloc (sizeof (WAVEHDR)) ; pWaveHdr2 = malloc (sizeof (WAVEHDR)) ; pBuffer1 = malloc (OUT_BUFFER_SIZE) ; pBuffer2 = malloc (OUT_BUFFER_SIZE) ; if (!pWaveHdr1 || !pWaveHdr2 || !pBuffer1 || !pBuffer2) { if (!pWaveHdr1) free (pWaveHdr1) ; if (!pWaveHdr2) free (pWaveHdr2) ; if (!pBuffer1) free (pBuffer1) ; if (!pBuffer2) free (pBuffer2) ; MessageBeep (MB_ICONEXCLAMATION) ; MessageBox (hwnd, TEXT ("Error allocating memory!"), szAppName, MB_ICONEXCLAMATION | MB_OK) ; return TRUE ; } // Variable to indicate Off button pressed bShutOff = FALSE ; // Open waveform audio for output waveformat.wFormatTag = WAVE_FORMAT_PCM ; waveformat.nChannels = 1 ; waveformat.nSamplesPerSec = SAMPLE_RATE ; waveformat.nAvgBytesPerSec = SAMPLE_RATE ; waveformat.nBlockAlign = 1 ; waveformat.wBitsPerSample = 8 ; waveformat.cbSize = 0 ; if (waveOutOpen (&hWaveOut, WAVE_MAPPER, &waveformat, (DWORD) hwnd, 0, CALLBACK_WINDOW) != MMSYSERR_NOERROR) { free (pWaveHdr1) ; free (pWaveHdr2) ; free (pBuffer1) ; free (pBuffer2) ; hWaveOut = NULL ; MessageBeep (MB_ICONEXCLAMATION) ; MessageBox (hwnd, TEXT ("Error opening waveform audio device!"), szAppName, MB_ICONEXCLAMATION | MB_OK) ; return TRUE ; } // Set up headers and prepare them pWaveHdr1->lpData = pBuffer1 ; pWaveHdr1->dwBufferLength = OUT_BUFFER_SIZE ; pWaveHdr1->dwBytesRecorded = 0 ; pWaveHdr1->dwUser = 0 ; pWaveHdr1->dwFlags = 0 ; pWaveHdr1->dwLoops = 1 ; pWaveHdr1->lpNext = NULL ; pWaveHdr1->reserved = 0 ; waveOutPrepareHeader (hWaveOut, pWaveHdr1, sizeof (WAVEHDR)) ; pWaveHdr2->lpData = pBuffer2 ; pWaveHdr2->dwBufferLength = OUT_BUFFER_SIZE ; pWaveHdr2->dwBytesRecorded = 0 ; pWaveHdr2->dwUser = 0 ; pWaveHdr2->dwFlags = 0 ; pWaveHdr2->dwLoops = 1 ; pWaveHdr2->lpNext = NULL ; pWaveHdr2->reserved = 0 ; waveOutPrepareHeader (hWaveOut, pWaveHdr2, sizeof (WAVEHDR)) ; } // If turning off waveform, reset waveform audio else { bShutOff = TRUE ; waveOutReset (hWaveOut) ; } return TRUE ; } break ; // Message generated from waveOutOpen call case MM_WOM_OPEN: SetDlgItemText (hwnd, IDC_ONOFF, TEXT ("Turn Off")) ; // Send two buffers to waveform output device FillBuffer (pBuffer1, iFreq) ; waveOutWrite (hWaveOut, pWaveHdr1, sizeof (WAVEHDR)) ; FillBuffer (pBuffer2, iFreq) ; waveOutWrite (hWaveOut, pWaveHdr2, sizeof (WAVEHDR)) ; return TRUE ; // Message generated when a buffer is finished case MM_WOM_DONE: if (bShutOff) { waveOutClose (hWaveOut) ; return TRUE ; } // Fill and send out a new buffer FillBuffer (((PWAVEHDR) lParam)->lpData, iFreq) ; waveOutWrite (hWaveOut, (PWAVEHDR) lParam, sizeof (WAVEHDR)) ; return TRUE ; case MM_WOM_CLOSE: waveOutUnprepareHeader (hWaveOut, pWaveHdr1, sizeof (WAVEHDR)) ; waveOutUnprepareHeader (hWaveOut, pWaveHdr2, sizeof (WAVEHDR)) ; free (pWaveHdr1) ; free (pWaveHdr2) ; free (pBuffer1) ; free (pBuffer2) ; hWaveOut = NULL ; SetDlgItemText (hwnd, IDC_ONOFF, TEXT ("Turn On")) ; if (bClosing) EndDialog (hwnd, 0) ; return TRUE ; case WM_SYSCOMMAND: switch (wParam) { case SC_CLOSE: if (hWaveOut != NULL) { bShutOff = TRUE ; bClosing = TRUE ; waveOutReset (hWaveOut) ; } else EndDialog (hwnd, 0) ; return TRUE ; } break ; } return FALSE ; }
OMX_ERRORTYPE EncoderFileSource::ThreadRun(OMX_PTR pThreadData) { (void)pThreadData; OMX_ERRORTYPE result = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *pHeader = NULL; BufferInfo *pBuffer = NULL; OMX_S32 nFrameBytes = m_nFrameWidth * m_nFrameHeight * 3 / 2; OMX_TICKS nTimeStamp = 0; for (OMX_S32 i = 1; i <= m_nFrames && !m_bThreadStop; i++) { // Since frame rate can change at any time, let's make sure that we use // the same frame rate for the duration of this loop iteration OMX_S32 nFramerate = m_nFramerate; // If in live mode we deliver frames in a real-time fashion if (m_bIsProfileMode) { VTEST_MSG_LOW("delaying frame %u ms", (unsigned int)(1000 / nFramerate)); Sleeper::Sleep(1000 / nFramerate); } result = m_pBufferQueue->Pop(&pBuffer, sizeof(BufferInfo**), 0); VTEST_MSG_LOW("queue pop %u of %u...", (unsigned int)i, (unsigned int)m_nFrames); if ((pBuffer == NULL) || (result != OMX_ErrorNone)) { /* Can only happen if stop is called or someone else ran into an * error */ VTEST_MSG_HIGH("Stopping thread"); result = OMX_ErrorNone; continue; } pHeader = pBuffer->pHeaderOut; pHeader->nOffset = 0; pHeader->nTimeStamp = 0; pHeader->nFlags = 0; pHeader->nFilledLen = 0; result = FillBuffer(pHeader, nFrameBytes); if (result != OMX_ErrorNone) { SetError(); pHeader->nFlags = OMX_BUFFERFLAG_EOS; m_pSink->SetBuffer(pBuffer, this); continue; } // set the EOS flag if this is the last frame if (i >= m_nFrames) { pHeader->nFlags = OMX_BUFFERFLAG_EOS; VTEST_MSG_HIGH("enable OMX_BUFFERFLAG_EOS on frame %u", (unsigned int)i); m_bThreadStop = OMX_TRUE; } pHeader->nFilledLen = nFrameBytes; if (m_bIsProfileMode) { nTimeStamp = (OMX_TICKS)Time::GetTimeMicrosec(); } else { nTimeStamp = nTimeStamp + (OMX_TICKS)(1000000 / nFramerate); } pHeader->nTimeStamp = nTimeStamp; VTEST_MSG_MEDIUM("delivering frame %u", (unsigned int)i); pHeader->nOffset = ((m_nFrameWidth * m_nDVSYOffset) + m_nDVSXOffset) * 3 / 2; m_pSink->SetBuffer(pBuffer, this); } // end for-loop //clean up while(m_pBufferQueue->GetSize() > 0) { VTEST_MSG_LOW("cleanup: q-wait (qsize %u)", (unsigned int)m_pBufferQueue->GetSize()); m_pBufferQueue->Pop(&pBuffer, sizeof(BufferInfo **), 0); m_pSink->SetBuffer(pBuffer, this); } VTEST_MSG_HIGH("thread exiting..."); return result; }
NS_IMETHODIMP nsBufferDecoderSupport::Convert(const char * aSrc, PRInt32 * aSrcLength, PRUnichar * aDest, PRInt32 * aDestLength) { // we do all operations using pointers internally const char * src = aSrc; const char * srcEnd = aSrc + *aSrcLength; PRUnichar * dest = aDest; PRUnichar * destEnd = aDest + *aDestLength; PRInt32 bcr, bcw; // byte counts for read & write; nsresult res = NS_OK; // do we have some residual data from the last conversion? if (mBufferLength > 0) { if (dest == destEnd) { res = NS_OK_UDEC_MOREOUTPUT; } else { for (;;) { // we need new data to add to the buffer if (src == srcEnd) { res = NS_OK_UDEC_MOREINPUT; break; } // fill that buffer PRInt32 buffLen = mBufferLength; // initial buffer length FillBuffer(&src, srcEnd - src); // convert that buffer bcr = mBufferLength; bcw = destEnd - dest; res = ConvertNoBuff(mBuffer, &bcr, dest, &bcw); dest += bcw; // Detect invalid input character if (res == NS_ERROR_ILLEGAL_INPUT && mErrBehavior == kOnError_Signal) { break; } if ((res == NS_OK_UDEC_MOREINPUT) && (bcw == 0)) { res = NS_ERROR_UNEXPECTED; #if defined(DEBUG_yokoyama) || defined(DEBUG_ftang) NS_ERROR("This should not happen. Internal buffer may be corrupted."); #endif break; } else { if (bcr < buffLen) { // we didn't convert that residual data - unfill the buffer src -= mBufferLength - buffLen; mBufferLength = buffLen; #if defined(DEBUG_yokoyama) || defined(DEBUG_ftang) NS_ERROR("This should not happen. Internal buffer may be corrupted."); #endif } else { // the buffer and some extra data was converted - unget the rest src -= mBufferLength - bcr; mBufferLength = 0; res = NS_OK; } break; } } } } if (res == NS_OK) { bcr = srcEnd - src; bcw = destEnd - dest; res = ConvertNoBuff(src, &bcr, dest, &bcw); src += bcr; dest += bcw; // if we have partial input, store it in our internal buffer. if (res == NS_OK_UDEC_MOREINPUT) { bcr = srcEnd - src; // make sure buffer is large enough if (bcr > mBufferCapacity) { // somehow we got into an error state and the buffer is growing out // of control res = NS_ERROR_UNEXPECTED; } else { FillBuffer(&src, bcr); } } } *aSrcLength -= srcEnd - src; *aDestLength -= destEnd - dest; return res; }
// // DoBufferProcessingLoop // // Grabs a buffer and calls the users processing function. // Overridable, so that different delivery styles can be catered for. HRESULT CSourceStream::DoBufferProcessingLoop(void) { Command com; OnThreadStartPlay(); do { while (!CheckRequest(&com)) { IMediaSample *pSample; HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0); if (FAILED(hr)) { Sleep(1); continue; // go round again. Perhaps the error will go away // or the allocator is decommited & we will be asked to // exit soon. } // Virtual function user will override. hr = FillBuffer(pSample); if (hr == S_OK) { hr = Deliver(pSample); pSample->Release(); // downstream filter returns S_FALSE if it wants us to // stop or an error if it's reporting an error. if(hr != S_OK) { DbgLog((LOG_TRACE, 2, TEXT("Deliver() returned %08x; stopping"), hr)); return S_OK; } } else if (hr == S_FALSE) { // derived class wants us to stop pushing data pSample->Release(); DeliverEndOfStream(); return S_OK; } else { // derived class encountered an error pSample->Release(); DbgLog((LOG_ERROR, 1, TEXT("Error %08lX from FillBuffer!!!"), hr)); DeliverEndOfStream(); m_pFilter->NotifyEvent(EC_ERRORABORT, hr, 0); return hr; } // all paths release the sample } // For all commands sent to us there must be a Reply call! if (com == CMD_RUN || com == CMD_PAUSE) { Reply(NOERROR); } else if (com != CMD_STOP) { Reply((DWORD) E_UNEXPECTED); DbgLog((LOG_ERROR, 1, TEXT("Unexpected command!!!"))); } } while (com != CMD_STOP); return S_FALSE; }
void addData(const ByteArray &inBytes) { mDynamicDone = false; mDynamicDataDue = mDynamicFillPos + mDynamicStartPos; FillBuffer(inBytes); }
HRESULT CMPIptvSourceStream::DoBufferProcessingLoop(void) { Command com; OnThreadStartPlay(); WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); #ifdef logging LogDebug("Starting grabber thread"); #endif sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; if (localip) { addr.sin_addr.s_addr = inet_addr(localip); } else { addr.sin_addr.s_addr = htonl(INADDR_ANY); } addr.sin_port = htons((u_short)port); ip_mreq imr; imr.imr_multiaddr.s_addr = inet_addr(ip); if (localip) { imr.imr_interface.s_addr = inet_addr(localip); } else { imr.imr_interface.s_addr = INADDR_ANY; } unsigned long nonblocking = 1; if((m_socket = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) { /* u_long argp = 1; ioctlsocket(m_socket, FIONBIO, &argp); */ DWORD dw = TRUE; int dwLen = sizeof(dw); if(setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&dw, sizeof(dw)) < 0) { closesocket(m_socket); m_socket = -1; } if(setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, (const char*)&dw, sizeof(dw)) < 0) { closesocket(m_socket); m_socket = -1; } getsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&dw, &dwLen); #ifdef logging LogDebug("Socket receive buffer is: %d (%d)", dw, dwLen); LogDebug("Trying to set receive buffer to %d", IPTV_SOCKET_BUFFER_SIZE); #endif dw = IPTV_SOCKET_BUFFER_SIZE; if(setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (const char*)&dw, sizeof(dw)) < 0) { closesocket(m_socket); m_socket = -1; } dwLen = sizeof(dw); getsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&dw, &dwLen); #ifdef logging LogDebug("New socket receive buffer is: %d (%d)", dw, dwLen); #endif if (ioctlsocket(m_socket, FIONBIO, &nonblocking) != 0) { closesocket(m_socket); m_socket = -1; } if(bind(m_socket, (struct sockaddr*)&addr, sizeof(addr)) < 0) { closesocket(m_socket); m_socket = -1; } if(IN_MULTICAST(htonl(imr.imr_multiaddr.s_addr))) { int ret = setsockopt(m_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&imr, sizeof(imr)); if(ret < 0) ret = ::WSAGetLastError(); ret = ret; } } SetThreadPriority(m_hThread, THREAD_PRIORITY_TIME_CRITICAL); int fromlen = sizeof(addr); m_buffsize = 0; timeval tv; //Will be used for select() below tv.tv_sec = 0; tv.tv_usec = 100000; //100 msec do { BOOL requestAvail; while ((requestAvail = CheckRequest(&com)) == FALSE) { DWORD startRecvTime; startRecvTime = GetTickCount(); #ifdef FILL_DIRECTLY_INTO_BUFFER IMediaSample *pSample; char *pData; long cbData; HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0); if (FAILED(hr)) continue; CheckPointer(pSample, E_POINTER); // Access the sample's data buffer pSample->GetPointer((BYTE **)&pData); cbData = pSample->GetSize(); #endif do { //Try to read the complete remaining buffer size //But stop reading after 100ms have passed (slow streams like internet radio) #ifdef FILL_DIRECTLY_INTO_BUFFER int len = recvfrom(m_socket, &pData[m_buffsize], cbData - m_buffsize, 0, (SOCKADDR*)&addr, &fromlen); #else int len = recvfrom(m_socket, &m_buffer[m_buffsize], IPTV_BUFFER_SIZE - m_buffsize, 0, (SOCKADDR*)&addr, &fromlen); #endif if(len <= 0) { //Wait until there's something in the receive buffer fd_set myFDsocket; myFDsocket.fd_count = 1; myFDsocket.fd_array[0] = m_socket; int selectRet = select(0, &myFDsocket, NULL, NULL, &tv); #ifdef logging LogDebug("select return code: %d", selectRet); #endif continue; //On error or nothing read just repeat the loop } #ifdef logging LogDebug("Read %d bytes at pos %d of %d", len, m_buffsize, IPTV_BUFFER_SIZE); #endif m_buffsize += len; #ifdef FILL_DIRECTLY_INTO_BUFFER } while ((requestAvail = CheckRequest(&com)) == FALSE && m_buffsize < (cbData * 3 / 4) && abs((signed long)(GetTickCount() - startRecvTime)) < 100); #else } while ((requestAvail = CheckRequest(&com)) == FALSE && m_buffsize < (IPTV_BUFFER_SIZE * 3 / 4) && abs((signed long)(GetTickCount() - startRecvTime)) < 100); #endif if (requestAvail) break; #ifndef FILL_DIRECTLY_INTO_BUFFER if (m_buffsize == 0) continue; //100ms passed but no buffer received IMediaSample *pSample; HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0); if (FAILED(hr)) { continue; // go round again. Perhaps the error will go away // or the allocator is decommited & we will be asked to // exit soon. } #endif // fill buffer hr = FillBuffer(pSample); if (hr == S_OK) { hr = Deliver(pSample); pSample->Release(); // downstream filter returns S_FALSE if it wants us to // stop or an error if it's reporting an error. if(hr != S_OK) { #ifdef logging LogDebug("Deliver() returned %08x; stopping", hr); #endif if(m_socket >= 0) {closesocket(m_socket); m_socket = -1;} WSACleanup(); return S_OK; } } else if (hr == S_FALSE) { // derived class wants us to stop pushing data pSample->Release(); DeliverEndOfStream(); if(m_socket >= 0) {closesocket(m_socket); m_socket = -1;} WSACleanup(); return S_OK; } else { // derived class encountered an error pSample->Release(); #ifdef logging LogDebug("Error %08lX from FillBuffer!!!", hr); #endif DeliverEndOfStream(); m_pFilter->NotifyEvent(EC_ERRORABORT, hr, 0); if(m_socket >= 0) {closesocket(m_socket); m_socket = -1;} WSACleanup(); return hr; } // all paths release the sample } // For all commands sent to us there must be a Reply call! if (com == CMD_RUN || com == CMD_PAUSE) { Reply(NOERROR); } else if (com != CMD_STOP) { Reply((DWORD) E_UNEXPECTED); #ifdef logging LogDebug("Unexpected command %d!!!", com); #endif } } while (com != CMD_STOP);
int GetC(){ FillBuffer(); return pos<count ? buffer[pos++] : EOF; }