bool AudioBufferManager::reset_buffer_mode()
{
	if (0 == mLenOfSample || 0 == mFrameShiftSize || 0 == mPostProcessBufferLen)
	{
		AUDIO_PROCESSING_PRINTF("init param is invalid!");
		return false;
	}

	CAUDIO_U32_t initDelayLen = mInitDelay * mLenOfSample;
	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mInChannelNum; channelIndex++)
	{
		mpBufferCondition[channelIndex].mSrcBufferReadPtr = 0;
		mpBufferCondition[channelIndex].mInDefBufferWritePtr = mInitDelay * mLenOfSample;;
		//mpBufferCondition[channelIndex].mInDefBufferWritePtr = mLenOfSample*mFrameShiftSize / 2;
		resetBuffer(mpBufferCondition[channelIndex].mpInDeficiencyBuffer, mInDefBufferLen, mpBufferCondition[channelIndex].mInDefBufferWritePtr);
	}

	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mOutChannelNum; channelIndex++)
	{
		mpBufferCondition[channelIndex].mPostProBufWrtPtr = initDelayLen;
		resetBuffer(mpBufferCondition[channelIndex].mpPostProcessBuffer, mPostProcessBufferLen);
	}

	return true;
}
Exemplo n.º 2
0
void MASASerial::update(){

  if (!messageAvailable()){
    while(SerialUSB.available()){
      if (lastIndex<PACKET_SIZE) bufferIn[lastIndex++] = SerialUSB.read();
    }
    
    if (inputState(bufferIn, lastIndex)==RESET){
      resetBuffer();
    }else if (!inAvailable&&inputState(bufferIn, lastIndex)==COMPLETE){
      inAvailable = true;
      for (uint8_t i = 3; i < 3+bufferIn[2]; i++){
        dataIn.data[i-3] = bufferIn[i];
      }
        dataIn.header = bufferIn[1];
        dataIn.lengthData = bufferIn[2];
    }
    
  }else{
	if (SerialUSB.available() == 64) resetBuffer();
  
  }
  
  
}
Exemplo n.º 3
0
    //-------------------------------------------------------------------------
    void
    ManualObject::resetBuffers()
    {
        for( int i(BINDING_COUNT); i--; )
        {
            resetBuffer( m_vertex_buffers[i] );
        }

        resetBuffer( m_index_buffer );
        m_position = nullptr;
        m_normal = nullptr;
        m_colour = nullptr;
        m_texture_coordinate = nullptr;
        m_index = nullptr;
    }
Exemplo n.º 4
0
/*
	Get next vCard list buffer
*/
bool folderGetNextListBuffer(void)
{
	bool lFinished = TRUE;

	resetBuffer();
	
	if (the_app->folderData.listLeft > 0)
	{
		uint16 lToCopy;
		uint16 lStart = sizeof(gVCardListHeader) - the_app->folderData.listLeft;
		lToCopy = (the_app->buffer.sizeBuffer <= the_app->folderData.listLeft) ? the_app->buffer.sizeBuffer : the_app->folderData.listLeft;
		
		memcpy(the_app->buffer.buffer, &gVCardListHeader[lStart], lToCopy);
		the_app->buffer.freeSpace -= lToCopy;
		the_app->buffer.nextPos += lToCopy;
		the_app->buffer.used += lToCopy;
		the_app->folderData.listLeft = the_app->folderData.listLeft - lToCopy;
	}
	
	if (the_app->buffer.freeSpace >= 0)
	{
		lFinished = folderFillBuffer();
	}
	
	return lFinished;
}
Exemplo n.º 5
0
//AutoreleasePool pool;
bool ImageAlphaLut::initWithImage(std::string file)
{
    file = FileUtils::getInstance()->fullPathForFilename(file);
    auto na = file.substr(file.find_last_of("/") + 1);

    _name = (char *)malloc(na.length() + 1);
    strcpy(_name, na.c_str());


    auto img = new Image();

    CCASSERT(img->initWithImageFile(file), "Init image fail");

    auto lengh = img->getDataLen();
    CCASSERT(lengh >= 8, "NO image data");

    _width = img->getWidth();
    _height = img->getHeight();
    auto data = img->getData();
    // 初始化 BUFF
    resetBuffer();
    // 提取图片透明信息
    for (int i = 0 ; i < _width * _height; ++i)
    {
        if (data[i*4+3] )
        {
            setPixelAlpha(i);
        }
    }

    CC_SAFE_RELEASE(img);

    return true;
}
Exemplo n.º 6
0
static retCode completeLine(LineState *ls) {
  integer cx = 0;
  strgPo snapShot = stringFromBuffer(ls->lineBuff);
  integer snapPos = bufferOutPos(ls->lineBuff);

  do {
    retCode ret = completionCallback(ls->lineBuff, completionCl, cx++);

    switch (ret) {
      case Ok: {
        char ch;
        if (rawInChar(&ch) != Ok) {
          resetBuffer(ls->lineBuff, snapShot, snapPos);
          decReference(O_OBJECT(snapShot));
          return Error;
        } else {
          switch (ch) {
            case TAB:
              resetBuffer(ls->lineBuff, snapShot, snapPos);
              continue;
            case ESC:
              resetBuffer(ls->lineBuff, snapShot, snapPos);
              decReference(O_OBJECT(snapShot));
              refreshLine(ls->firstPos, ls->lineBuff);
              return Ok;
            case SPACE:
            case ENTER:
              decReference(O_OBJECT(snapShot));
              return Ok;
            default:
              beep();
              continue;
          }
        }
      }

      case Eof:
        resetBuffer(ls->lineBuff, snapShot, snapPos);
        decReference(O_OBJECT(snapShot));
        refreshLine(ls->firstPos, ls->lineBuff);
        return Ok;
      default:
      case Error:
        return Error;
    }
  } while (True);
}
Exemplo n.º 7
0
void StreamBuffer::removeChunk(qint64 offset)
{
    qint64 remainingBytes = size() - offset;

    if(remainingBytes > 0){
        reset();
        seek(offset);

        QByteArray array = read(remainingBytes);

        resetBuffer(array);
        seek(remainingBytes);
    }
    else{
        resetBuffer(QByteArray());
    }
}
Exemplo n.º 8
0
int PrettySource(Tableau *tab,char *path){

	FILE * output;
	char *BufferStandard=malloc(1000*sizeof(char));
	output=fopen(path,"w+");
;
	if(tab->Codeword==0){
		fprintf(output,"%s\n",tab->mot);
	}

	tab=tab->suivant;
	tab=tab->suivant;

	while(tab->suivant!=NULL){

		if(tab->Codeword==5){
			break;
		}

		while(tab->Codeword!=7){

			switch(tab->Codeword){

				case 2:

				fprintf(output,"\t");
				PrettyStandard(tab,BufferStandard);
				fprintf(output,"%s\n",BufferStandard);

				break;

				case 3:
				fprintf(output, "%s\n",tab->mot);
				break;
			}


			while(tab->Codeword!=7){
				tab=tab->suivant;
			}

		}
		resetBuffer(BufferStandard,1000);
		tab=tab->suivant;
	}

	if(tab->Codeword==5){

		fprintf(output,"\t");
		fprintf(output, "%s\n",tab->mot);

	}
	fclose(output);
	return 0;
}
Exemplo n.º 9
0
uint8_t* MASASerial::getMessage(){
  if (messageAvailable()){
    inAvailable = false;
    
    resetBuffer();
    
    return dataIn.data;
  
  } else 
    return NULL;
}
Exemplo n.º 10
0
void Audio::checkPlaying()
{
    if (finalPoints->size())
    {
        synth->playing = true;
        translator->translate();
    }
    else
    {
        resetBuffer();
        synth->playing = false;
    }
}
    void operator()( genome_pointer first, genome_pointer last ) {
        resetBuffer();

        while( first != last ) {
            index_type idx = *first++;


            unsigned int k = 0, offset = idx * m_trait_count;
            while( k < m_trait_count ) {
                m_weight_buffer[ k++ ] = (*m_traits)[ offset++ ];
            }
        }
    }
Exemplo n.º 12
0
// Received an event, a full packetSignalEvent
void ParticlePMS7003::onEvent(const PollEvent& evt)
{
  // Get the message
  const UartPacket& pkt = UartLinux::uartRead(wire()->handle());

  // Get the message
  const std::string& message = pkt.message;

  // Get the length of the message
  const int msg_len = message.length();

  // Get the pointer to the first character of the message
  const byte* msg_bytes = (byte*) message.c_str();

  // Go through the message byte by byte
  for (int i = 0; i < msg_len; i++)
  {
    // Check if we have a partial message being populated
    if (_partial)
    {
      // Check if it is the correct second start character or any other character
      if (_index != 1 || (_index == 1 && msg_bytes[i] == PMS7003_START_CHAR_2))
      {
        // Put character in buffer
        _buffer[_index] = msg_bytes[i];

        // Increment message and Callback on the end of message if needed
        if (++_index == PMS7003_MESSAGE_LEN) { onMessage(); }
      }
      // There is a mistake we reset the buffer
      else { resetBuffer(); }
    }
    // We do not have a partial message yet, looking for the begining
    else
    {
      // Check if it could be begining of message
      if (msg_bytes[i] == PMS7003_START_CHAR_1)
      {
        // Initialize new message
        _buffer[0] = msg_bytes[i];
        _partial = true;
        _index = 1;
      }
    }
  }
}
Exemplo n.º 13
0
 int receiveData()
 {
   resetBuffer();
   int free = buffer_size_ - data_begin_ - data_cnt_;
   int recv_cnt = 0;
   if( free > 0 )
   {
     // Receive available data from the socket
     recv_cnt = ::recv( socket_, &buffer_[data_begin_+data_cnt_], free, 0);
     if( recv_cnt < 0 )
     {
       return 0;
     }
     data_cnt_ += recv_cnt;
   }
   return recv_cnt;
 }
Exemplo n.º 14
0
void init() {
	void *fbp0 = 0;

	drawbuf = (u32 *)sceGeEdramGetAddr();

	sceGuInit();
	sceGuStart(GU_DIRECT, list);
	sceGuDrawBuffer(GU_PSM_8888, fbp0, BUF_WIDTH);
	sceGuDispBuffer(SCR_WIDTH, SCR_HEIGHT, fbp0, BUF_WIDTH);
	sceGuScissor(0, 0, SCR_WIDTH, SCR_HEIGHT);
	sceGuEnable(GU_SCISSOR_TEST);
	sceGuFinish();
	sceGuSync(0, 0);

	sceDisplayWaitVblankStart();
	sceGuDisplay(1);

	resetBuffer();
}
Exemplo n.º 15
0
void ParticlePMS7003::onMessage()
{
  // Initialize check sum
  uint16_t chk_sum = 0;

  // Compute the check sum
  for (int i = 0; i < PMS7003_CHK_INDEX; i++) { chk_sum += _buffer[i]; }

  // Parse useful data
  _pm1 = uint8To16(&_buffer[PMS7003_PM1_INDEX]);
  _pm2 = uint8To16(&_buffer[PMS7003_PM2_INDEX]);
  _pm10 = uint8To16(&_buffer[PMS7003_PM10_INDEX]);
  uint16_t chk_byte = uint8To16(&_buffer[PMS7003_CHK_INDEX]);

  // Perform check on the data integrity
  //if (chk_sum == chk_byte)
  {
    INFO_PF("message pm1:%u pm2.5:%u pm10:%u chk:%u/%u", _pm1, _pm2, _pm10, chk_sum, chk_byte);
  }

  // Reset the buffer
  resetBuffer();
}
Exemplo n.º 16
0
XSerializeEngine::XSerializeEngine(BinOutputStream*        outStream
                                 , XMLGrammarPool* const   gramPool
                                 , unsigned long           bufSize)
:fStoreLoad(mode_Store)
,fStorerLevel(0)
,fGrammarPool(gramPool)
,fInputStream(0)
,fOutputStream(outStream)
,fBufCount(0)
,fBufSize(bufSize)
,fBufStart((XMLByte*) gramPool->getMemoryManager()->allocate(bufSize))
,fBufEnd(fBufStart+bufSize)
,fBufCur(fBufStart)
,fBufLoadMax(0)
,fStorePool( new (gramPool->getMemoryManager()) RefHashTableOf<XSerializedObjectId>(29, true, new (gramPool->getMemoryManager()) HashPtr(), gramPool->getMemoryManager()) )
,fLoadPool(0)
,fObjectCount(0)
{
    resetBuffer();

    //initialize store pool
    fStorePool->put(0, new (gramPool->getMemoryManager()) XSerializedObjectId(fgNullObjectTag));

}
Exemplo n.º 17
0
// -----------------------------------------------------------------------------
// BufferManager::SetPosition()
// -----------------------------------------------------------------------------
//
void BufferManager::setPosition( int aIndex )
{
    // If all the items fit in the buffer no need to move the buffer
    if(mTotalCount <= mBufferSize) return;
	
	bool forceUpdate = false;
    aIndex -= mBufferSize / 2; // normalize index to Buffer start
    
    if(aIndex < 0){
        aIndex = 0;
        forceUpdate = true;
    }else if( aIndex > mTotalCount - mBufferSize ){
        aIndex = mTotalCount - mBufferSize;
        forceUpdate = true;
    }

    mDiff = mBufferPosition - aIndex; 

    // Too large change reset whole buffer
    if( mDiff >= mBufferSize || -mDiff >= mBufferSize || mResetOrdered ) {
        resetBuffer(aIndex + (mBufferSize/2), mTotalCount);
    } else if( mDiff >= mBufferTreshold ) { // Move Up
        mRequestCount = mDiff;
        mReleaseCount = mDiff;
        calculate();
    } else if ( -mDiff >= mBufferTreshold ) {// Move Down
        mRequestCount = -mDiff;
        mReleaseCount = -mDiff;
        calculate();
    } else if( forceUpdate && mDiff ) { // Top or bottom has been reached
        int diff = mDiff < 0 ? -mDiff : mDiff;
        mRequestCount = diff;
        mReleaseCount = diff;
        calculate();
    }
}
Exemplo n.º 18
0
int __cdecl main(int argc, char **argv)
{
	WSADATA wsaData;
	int iResult;

	SOCKET ListenSocket = INVALID_SOCKET;
	SOCKET ClientSocket = INVALID_SOCKET;

	struct addrinfo *result = NULL;
	struct addrinfo hints;

	int iSendResult;
	char recvbuf[DEFAULT_BUFLEN] = {0};
	char sendbuf[DEFAULT_BUFLEN] = {0};
	int recvbuflen = DEFAULT_BUFLEN;
	UINT16 networkbytes;
	char welcomeMessage[8] = "Welcome\n";
	char successMessage[8] = "Success\n";
	char failureMessage[8] = "Failure\n";
	char endMessage[20] = "it is over\0";

	int foundEntry = -1;
	int passedCheck = FALSE;

	//below is bad pratice but it works for storing IDS Names and Passwords
	char *IDArray[] = { "12345", "555", "2" };
	char *NameArray[] = { "Tim", "Michael", "Ed" };
	char *PasswordArry[] = {"password", "yes", "no"};

	int i = 0;

	while (TRUE)
	{
		resetBuffer(recvbuf, DEFAULT_BUFLEN);
		resetBuffer(sendbuf, DEFAULT_BUFLEN);
		//memset(recvbuf, '\0', DEFAULT_BUFLEN);
		//memset(send, '\0', DEFAULT_BUFLEN);
		// Initialize Winsock
		iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
		if (iResult != 0) {
			printf("WSAStartup failed with error: %d\n", iResult);
			return 1;
		}

		ZeroMemory(&hints, sizeof(hints));
		hints.ai_family = AF_INET;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_protocol = IPPROTO_TCP;
		hints.ai_flags = AI_PASSIVE;

		// Resolve the server address and port
		iResult = getaddrinfo(NULL, argv[1], &hints, &result);
		if (iResult != 0) {
			printf("getaddrinfo failed with error: %d\n", iResult);
			WSACleanup();
			continue;
		}

		// Create a SOCKET for connecting to server
		ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
		if (ListenSocket == INVALID_SOCKET) {
			printf("socket failed with error: %ld\n", WSAGetLastError());
			freeaddrinfo(result);
			WSACleanup();
			continue;
		}

		// Setup the TCP listening socket
		iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
		if (iResult == SOCKET_ERROR) {
			printf("bind failed with error: %d\n", WSAGetLastError());
			freeaddrinfo(result);
			closesocket(ListenSocket);
			WSACleanup();
			continue;
		}

		freeaddrinfo(result);

		iResult = listen(ListenSocket, SOMAXCONN);
		if (iResult == SOCKET_ERROR) {
			printf("listen failed with error: %d\n", WSAGetLastError());
			closesocket(ListenSocket);
			WSACleanup();
			continue;
		}

		// Accept a client socket
		ClientSocket = accept(ListenSocket, NULL, NULL);
		if (ClientSocket == INVALID_SOCKET) {
			printf("accept failed with error: %d\n", WSAGetLastError());
			closesocket(ListenSocket);
			WSACleanup();
			continue;
		}

		// No longer need server socket
		closesocket(ListenSocket);


		//send Client welcome message
		iSendResult = send(ClientSocket, welcomeMessage, 8, 0);
		if (iSendResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}

		//get id number and name
		iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
		if (iResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}
		printf("Recieved ID number:");
		printNewLineString(recvbuf);

		//set to invalid value
		foundEntry = -1;
		passedCheck = 0;
		//checks ID vs ID array
		for (i = 0; i < 3; i++)
		{
			//check length so we know we don't over flow array
			if ((iResult -1) == strlen(IDArray[i]))
			{
				//compay recived id to ID Array element minus to \n
				if (memcmp(recvbuf, IDArray[i], (iResult - 1)) == 0)
				{
					foundEntry = i;
				}
			}
		}

		iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
		if (iResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}

		printf("Recieved Name number:");
		printNewLineString(recvbuf);

		//checks name vs Name array
		if ((foundEntry != -1) && ((iResult - 1) == strlen(NameArray[foundEntry])))
		{
			//compay recived name to name Array element minus to \n
			if (memcmp(recvbuf, NameArray[foundEntry], (iResult - 1)) == 0)
			{
				passedCheck = TRUE;
			}
		}

		//if correct ID and Name send success otherwise send failure
		if (passedCheck == TRUE)
		{
			printf("found ID and name\n");
			iSendResult = send(ClientSocket, successMessage, 8, 0);
			if (iSendResult == SOCKET_ERROR) {
				printf("send failed with error: %d\n", WSAGetLastError());
				closesocket(ClientSocket);
				WSACleanup();
				continue;
			}
		}
		else
		{
			printf("did not find ID and name\n");
			iSendResult = send(ClientSocket, failureMessage, 8, 0);
			if (iSendResult == SOCKET_ERROR) {
				printf("send failed with error: %d\n", WSAGetLastError());
				closesocket(ClientSocket);
				WSACleanup();
				continue;
			}
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}

		//get password length and password
		printf("getting password lenght\n");
		iResult = recv(ClientSocket, &networkbytes, sizeof(UINT16), 0);
		if (iResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}

		networkbytes = ntohs(networkbytes);
		printf("length recv is %hd\n", networkbytes);
		printf("getting password\n");
		iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
		if (iResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}
		recvbuf[iResult] = 0;
		printf("password recv is: %s\n", recvbuf);

		passedCheck = FALSE;

		//checks password
		if ((foundEntry != -1) && (iResult == strlen(PasswordArry[foundEntry])))
		{
			//compay recived name to passwprd Array element minus to \n
			if (memcmp(recvbuf, PasswordArry[foundEntry], (iResult - 1)) == 0)
			{
				passedCheck = TRUE;
			}
		}

		//create out end message
		if (passedCheck == TRUE)
		{
			strcat(sendbuf, "Condratulations ");
			strcat(sendbuf, NameArray[foundEntry]);
			strcat(sendbuf, "; you've just revealed the password for ");
			strcat(sendbuf, IDArray[foundEntry]);
			strcat(sendbuf, " to the world");
		}
		else
		{
			strcat(sendbuf, "Password incorrect.");
		}

		networkbytes = htons(strlen(sendbuf));
		printf("sending length %hd", strlen(sendbuf));
		iSendResult = send(ClientSocket, &networkbytes, sizeof(UINT16), 0);
		if (iSendResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}
		iSendResult = send(ClientSocket, sendbuf, (int)strlen(sendbuf), 0);
		if (iSendResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			continue;
		}
		closesocket(ClientSocket);
		WSACleanup();
	}
	

	return 0;
}
Exemplo n.º 19
0
int Editor::loadFile(const QString& filename)
{
	if(filename.isNull())
	{
		m_filename = QFileDialog::getOpenFileName(
			this,
			tr("Open file"),       // caption
			QString(),         // dir
			tr("TS files (*.ts)")  // filter
		);
	}
	else
		m_filename = filename;
	
	if(m_filename.isNull())
		return 1;
	
	// Allowed to be called repeatedly
	av_register_all();
	
// 	m_stream = avformat_alloc_context();
// 	m_stream->pb = io_http_create(filename.toAscii().constData());
// 	m_stream = 0;
	
	// Have to open repeatedly to get the correct stream duration despite
	// a Kathrein bug (see seek_time() below for a description)
	
	int tries;
	for(tries = 5; tries > 0; --tries)
	{
		m_stream = 0;
		if(avformat_open_input(&m_stream, m_filename.toAscii().constData(), NULL, NULL) != 0)
			return error("Could not open input stream '%s'",
				m_filename.toAscii().constData());
		
		if(avformat_find_stream_info(m_stream, NULL) < 0)
			return error("Could not find stream information");
		
		if(m_stream->duration < AV_TIME_BASE * 10
			|| m_stream->duration > 12LL * 60 * 60 * AV_TIME_BASE
			|| m_stream->nb_streams > 12)
		{
			log_warning(
				"Duration is %10lld seconds with %d streams",
				m_stream->duration / AV_TIME_BASE,
				m_stream->nb_streams
			);
			avformat_free_context(m_stream);
			continue;
		}
		
		break;
	}
	
	if(!tries)
		return error("Could not get around KATHREIN bug");
	
	av_dump_format(m_stream, 0, m_filename.toAscii().constData(), false);
	
	m_videoCodecCtx = 0;
	for(int i = 0; i < m_stream->nb_streams; ++i)
	{
		AVStream* stream = m_stream->streams[i];
		
		if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			m_videoID = i;
			m_videoCodecCtx = stream->codec;
			break;
		}
	}
	
	if(!m_videoCodecCtx)
		return error("Could not find video stream");
	
	// Try to decode as fast as possible
	m_videoCodecCtx->flags2 |= CODEC_FLAG2_FAST;
	m_videoCodecCtx->skip_loop_filter = AVDISCARD_ALL;
	
	m_videoCodec = avcodec_find_decoder(m_videoCodecCtx->codec_id);
	if(!m_videoCodec)
		return error("Unsupported video codec");
	
	if(avcodec_open2(m_videoCodecCtx, m_videoCodec, NULL) < 0)
		return error("Could not open video codec");
	
	initBuffer();
	resetBuffer();
	
	m_timeStampStart = av_rescale_q(m_stream->start_time,
		AV_TIME_BASE_Q, m_stream->streams[m_videoID]->time_base);
	m_timeStampFirstKey = m_frameTimestamps[0];
	
	m_videoTimeBase_q = m_stream->streams[m_videoID]->time_base;
	m_videoTimeBase = av_q2d(m_videoTimeBase_q);
	
	log_debug("File duration is % 5.2fs", (float)m_stream->duration / AV_TIME_BASE);
	m_ui->timeSlider->setMaximum(m_stream->duration / AV_TIME_BASE);
	
	if(!m_indexFile)
		log_debug("No index file present.");
	
	int w = m_videoCodecCtx->width;
	int h = m_videoCodecCtx->height;
	
	float aspectRatio = av_q2d(m_videoCodecCtx->sample_aspect_ratio);
	m_ui->videoWidget->setSize(w, h, aspectRatio);
	m_ui->cutVideoWidget->setSize(w, h, aspectRatio);
	
	displayCurrentFrame();
	
	setDisabled(false);
	
	return 0;
}
Exemplo n.º 20
0
void Editor::seek_time(float seconds, bool display)
{
	int64_t ts_rel = seconds / m_videoTimeBase;
	int64_t req_ts = pts_val(m_timeStampStart + ts_rel);
	int64_t ts = pts_val(req_ts + m_timeFudge);
	int64_t min_ts = ts - 2.0 / m_videoTimeBase;
	int64_t max_ts = ts;
	
	int64_t pts_base = av_rescale_q(ts_rel + m_timeFudge, m_videoTimeBase_q, AV_TIME_BASE_Q);
	
	// From time to time, my receiver (Kathrein UFS-910) screws up
	// and gives me the start of the stream instead of the requested
	// offset. So we have to wrap this in a loop and try again...
	
	int tries;
	for(tries = 5; tries > 0; --tries)
	{
		loff_t byte_offset = (loff_t)-1;
		
		avcodec_flush_buffers(m_videoCodecCtx);
		
		// If we got an index file, use it
		if(m_indexFile)
			byte_offset = m_indexFile->bytePositionForPTS(pts_base);
		
		if(byte_offset != (loff_t)-1)
		{
			log_debug("Seeking to byte pos %'10lld", byte_offset);
			if(avformat_seek_file(m_stream, -1, 0, byte_offset, byte_offset, AVSEEK_FLAG_BYTE) < 0)
			{
				log_debug("Byte seeking to %fs failed", seconds);
				byte_offset = (loff_t)-1;
			}
		}
		
		// Fallback to binary search
		if(byte_offset == (loff_t)-1)
		{
			log_debug("Seeking to pts %'10lld", ts);
			if(avformat_seek_file(m_stream, m_videoID, min_ts, ts, max_ts, 0) < 0)
			{
				error("could not seek");
				return;
			}
		}
		
		resetBuffer();
		
		// Detect Kathrein bug
		if(byte_offset
			&& seconds > 1.0 // not actually at start of stream
			&& m_frameTimestamps[0] - m_timeStampFirstKey == 0) // bug
		{
			log_debug("KATHREIN BUG detected");
			continue;
		}
		
		break;
	}
	
	if(!tries)
		QMessageBox::critical(this, tr("Error"), tr("Seeking failed, sorry."));
	
	int64_t diff = req_ts - m_frameTimestamps[0];
	if(llabs(diff) > 20.0 / m_videoTimeBase)
		log_debug("seek_time: missed destination (PTS: %'10lld) by more than 20 seconds, fudge = %'10lld", 
			ts, m_frameTimestamps[0], diff, m_videoTimeBase * diff, m_timeFudge
		);
	
	m_timeFudge += diff;
	if(llabs(m_timeFudge) > 10.0 / m_videoTimeBase)
	{
		log_debug("Resetting time fudge value");
		m_timeFudge = 0;
	}
	
	if(display)
		displayCurrentFrame();
}
Exemplo n.º 21
0
int main(void)
{

	SystemInit();
	GPIOInit();
	FLASH_Unlock();
	EE_Init();

  USBD_Init(&USB_OTG_dev,
#ifdef USE_USB_OTG_HS
  USB_OTG_HS_CORE_ID,
#else
  USB_OTG_FS_CORE_ID,
#endif
  &USR_desc,
  &USBD_HID_cb,
  &USR_cb);

	bitCount = 0;
	currentValue = 0;
	set = 0;
	ignoreNext = 0;
	uppercaseNext = 0;
	shiftPressed = 0;
	buttonPressed = 0;
	getHowMany();

	int i = 0;
	resetBuffer();

	for(;;)
	{
		/*
		 * Po wcisnieciu przycisku nastepuje wyslanie raportu USB
		 * zawierajacego rejestr przycisnietych klaiwszy
		 */
		if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0))
		{
			if (!buttonPressed)
			{
				buttonPressed = 1;
				for (i = 0; i < 64; i++)
				{
					EE_ReadVariable(VirtAddVarTab[i], &InBuffer[i]);
				}

				USBD_HID_SendReport (&USB_OTG_dev, InBuffer, 64);

			}
		} else if (buttonPressed)
		{
			buttonPressed = 0;
		}

		if (checkBufferReady())
		{
			/*
			 * Jezeli zapisano 64 wcisniecia klawiszy,
			 * nalezy oproznic EEPROM przed kontynuacja zapisu
			 *
			 */
			if(EEPROMFull())
			{
				GPIO_ToggleBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15);
				continue;
			}

			unsetBufferReady();
			startTimer();

			EE_WriteVariable(VirtAddVarTab[howMany=howMany+0x01], currentChar);
			EE_WriteVariable(VirtAddVarTab[63], howMany);

			}

		}
}
static void work_task(void *arg)
{
    BTM_TRACE_WARNING0("WORK THREAD START");
    while (1)
    {
        VOHOG_LOCK();
        if(adpcm_rec_cb.running)
        {
           if(adpcm_rec_cb.channel_status)
           {
                if(!isEmpty())
                {
                    if(getDATAfrombuffer(tempData,ADPCM_VOICE_DATA_BLOCK_SIZE))
                    {
                        if(UIPC_RTKBT_VR_Send_noblock(UIPC_CH_ID_RTKBT_VR_AUDIO, 0, tempData, ADPCM_VOICE_DATA_BLOCK_SIZE))
                        {
                            BTM_TRACE_DEBUG0("send data sucess");

                            adpcm_voice_data_buffer.ridx ++;
                            adpcm_voice_data_buffer.ridx %= ADPCM_VOICE_DATA_BUFFER_SIZE;

                        } else {
                            BTM_TRACE_ERROR0("send data failed");
                        }
                   }

                }
           }
        } else {
            if(adpcm_rec_cb.channel_status)
            {
                BTM_TRACE_WARNING0("close thread: channel is connected");
                if(isEmpty())
                {
                    BTM_TRACE_WARNING0("the buffer is empty, close socket");
                    resetBuffer();
                    UIPC_Close(UIPC_CH_ID_RTKBT_VR_AUDIO);
                    VOHOG_UNLOCK();
                    break;
                }  else {
                    BTM_TRACE_WARNING0("the buffer is not empty, send data");
                    if(getDATAfrombuffer(tempData,ADPCM_VOICE_DATA_BLOCK_SIZE))
                    {
                        if(UIPC_RTKBT_VR_Send_noblock(UIPC_CH_ID_RTKBT_VR_AUDIO, 0, tempData, ADPCM_VOICE_DATA_BLOCK_SIZE))
                        {
                            BTM_TRACE_DEBUG0("send data sucess");

                            adpcm_voice_data_buffer.ridx ++;
                            adpcm_voice_data_buffer.ridx %= ADPCM_VOICE_DATA_BUFFER_SIZE;

                        } else {
                            BTM_TRACE_ERROR0("send data failed,close socket");
                            resetBuffer();
                            UIPC_Close(UIPC_CH_ID_RTKBT_VR_AUDIO);
                            VOHOG_UNLOCK();
                            break;
                        }
                   }

                }
            }else {
                BTM_TRACE_WARNING0("close thread: the socket is not connected");
                VOHOG_UNLOCK();
                break;
            }

        }
        VOHOG_UNLOCK();
        usleep(1000);
    }
    adpcm_rec_cb.tid = 0;
    BTM_TRACE_WARNING0("VOICE THREAD DONE");
}
AndroidKeyboard::AndroidKeyboard(InputManager* creator)
        :       Keyboard(creator->inputSystemName(), false, 1, 0)
{
        resetBuffer();
}