Ejemplo n.º 1
0
qint64 Downloader::read(char* data, qint64 maxlen)
{
    qint64 len = 0;
    mutex_.lock();
    if (!stream_.icy_meta_data || stream_.icy_metaint == 0)
    {
        len = readBuffer(data, maxlen);
    }
    else
    {
        qint64 nread = 0;
        qint64 to_read;
        while (maxlen > nread && stream_.buf_fill > nread)
        {
            to_read = qMin<qint64>(stream_.icy_metaint - meta_count_, maxlen - nread);
            //to_read = (maxlen - nread);
            qint64 res = readBuffer(data + nread, to_read);
            nread += res;
            meta_count_ += res;
            if (meta_count_ == stream_.icy_metaint)
            {
                meta_count_ = 0;
                mutex_.unlock();
                readICYMetaData();
                mutex_.lock();
            }

        }
        len = nread;

    }
    mutex_.unlock();
    return len;
}
Ejemplo n.º 2
0
Archivo: recorder.cpp Proyecto: aox/aox
void RecorderClient::react( Event e )
{
    EString tmp;
    switch( e ) {
    case Read:
        tmp = readBuffer()->string( readBuffer()->size() );
        d->toClient.append( tmp );
        d->server->enqueue( tmp );
        readBuffer()->remove( tmp.length() );
        if ( d->toClient.find( '\n' ) )
            d->dump( RecorderData::ToServer );
        break;
    case Close:
        d->dump( RecorderData::ToServer );
        d->dump( RecorderData::ToClient );
        d->assertEmpty();
        d->server->close();
        delete d->log;
        d->log = 0;
        break;
    default:
        {
            // an error of some sort
        }
        break;
    }

}
Ejemplo n.º 3
0
int8 RingBuffer::read(uint8 *dat)
{
    uint32 bufsize = 0;
    uint32 tmprp = 0;
    
    if (g_wcounter <= (g_rcounter+1))
    {
        tmprp = 0;
    }
    if (checkReadData() < 0)
    {
        return -1;
    }
    g_rcounter++;
    tmprp = readBuffer(sizeof(bufsize), this->m_rp, (uint8 *)&bufsize);
    
    //没到结尾处,直接取
    if (bufsize + this->m_rp < this->m_size)
    {
        std::string ret = std::string(this->m_buffer[tmprp], bufsize);
        dat = (uint8 *)ret.c_str();
        tmprp = (tmprp + bufsize) % this->m_size;
     }
    else
        tmprp = readBuffer(bufsize, tmprp, dat);
    
    setReadPoint(tmprp);
    
    return 0;
}
Ejemplo n.º 4
0
OperationResult Enc28j60::receiveFrame(uint8_t* buffer, uint32_t* length)
{
    uint32_t payloadLength = 0;

    if (readRegisterByte(EPKTCNT) > 0)
    {
        writeRegister(ERDPT, nextPacketPtr);

        struct {
            uint16_t nextPacket;
            uint16_t byteCount;
            uint16_t status;
        } receiveHeader;

        // Read the header
        readBuffer((uint8_t*) &receiveHeader, sizeof(receiveHeader));

        // Update the pointer to the next packet
        nextPacketPtr = receiveHeader.nextPacket;

         // Remove the CRC count
        payloadLength = receiveHeader.byteCount - 4;

        // Check for buffer overflow
        if (payloadLength > *length - 1)
        {
            payloadLength = *length - 1;
        }

        // Check for CRC errors
        if ((receiveHeader.status & 0x0080) == 0)
        {
            return ResultError;
        }
        else
        {
            // Copy the packet to the buffer
            readBuffer(buffer, payloadLength);
        }

        // Clear last buffer position
        buffer[payloadLength] = 0;

        // Errata #14: Receive hardware may corrupt receive buffer
        if (nextPacketPtr - 1 > RXSTOP_INIT)
        {
            writeRegister(ERXRDPT, RXSTOP_INIT);
        }
        else
        {
            writeRegister(ERXRDPT, nextPacketPtr - 1);
        }

        // Decrement the number of packets
        writeOperation(ENC28J60_BIT_FIELD_SET, ECON2, ECON2_PKTDEC);
    }

    return ResultSuccess;
}
Ejemplo n.º 5
0
	void BinaryFileReader::readString(core::stringc &str)
	{
		str = "";
		c8 c;
		readBuffer(&c,sizeof(char));
		while(c != 0)
		{
			str += c;
			readBuffer(&c,sizeof(char));
		}
	}
Ejemplo n.º 6
0
void ZDvidBufferReader::read(const QString &url, bool outputingUrl)
{
  if (outputingUrl) {
    qDebug() << url;
  }

  m_buffer.clear();

#if defined(_ENABLE_LIBDVIDCPP_)
//  qDebug() << "Using libdvidcpp";

  ZDvidTarget target;
  target.setFromUrl(url.toStdString());

  if (target.isValid()) {
    try {
      libdvid::DVIDNodeService service(
            target.getAddressWithPort(), target.getUuid());
      std::string endPoint = ZDvidUrl::GetEndPoint(url.toStdString());
      libdvid::BinaryDataPtr data = service.custom_request(
            endPoint, libdvid::BinaryDataPtr(), libdvid::GET, m_tryingCompress);

      m_buffer.append(data->get_data().c_str(), data->length());
      m_status = READ_OK;
    } catch (std::exception &e) {
      std::cout << e.what() << std::endl;
      m_status = READ_FAILED;
    }
  } else {
    startReading();

    m_networkReply = m_networkManager->get(QNetworkRequest(url));
    connect(m_networkReply, SIGNAL(finished()), this, SLOT(finishReading()));
    connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(readBuffer()));
    connect(m_networkReply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(handleError(QNetworkReply::NetworkError)));

    waitForReading();
  }

#else
  startReading();

  m_networkReply = m_networkManager->get(QNetworkRequest(url));
  connect(m_networkReply, SIGNAL(finished()), this, SLOT(finishReading()));
  connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(readBuffer()));
  connect(m_networkReply, SIGNAL(error(QNetworkReply::NetworkError)),
          this, SLOT(handleError(QNetworkReply::NetworkError)));

  waitForReading();
#endif
}
status_t NuPlayer::GenericSource::seekTo(int64_t seekTimeUs) {
    if (mVideoTrack.mSource != NULL) {
        int64_t actualTimeUs;
        readBuffer(false /* audio */, seekTimeUs, &actualTimeUs);

        seekTimeUs = actualTimeUs;
    }

    if (mAudioTrack.mSource != NULL) {
        readBuffer(true /* audio */, seekTimeUs);
    }

    return OK;
}
Ejemplo n.º 8
0
int MSAConnection::doSyncRead(MSA &result_)
{
  MSBuffer *hb=headBuffer();
  MSBuffer *db=readBuffer();
  int s,n;

  if (isSet(MSProtocolConnection<MSA>::Reset)==MSTrue) return 0;
  if ((s=hb->put()-hb->get())<4)
   {
     if ((n=readTheBuffer(hb,4-s))<0) return 0;
     if((s=hb->put()-hb->get())<4) return 0;
     _bytesToNextMessage=MSA::longAt(hb->get());
   }
  if((n=readTheBuffer(db,_bytesToNextMessage))<0) return 0;
  if((_bytesToNextMessage-=n)==0)
   {
     result_=MSA::importAObject((char *) db->get(), db->put()-db->get(), (char *)0);
     hb->reset();
     db->clear();
     unset(MSProtocolConnection<MSA>::Read);
     if((result_.aStructPtr())==(MSAStruct *)0){resetWithError(MSProtocolConnection<MSA>::Read);return 0;}
   }
  
  return 1;
}
Ejemplo n.º 9
0
MSA MSAConnection::getAobjectFromBuffer(MSBuffer *buf_)
{
  MSBuffer *hb=headBuffer();
  MSBuffer *db=readBuffer();
  int s,n;
  if (isSet(MSProtocolConnection<MSA>::Reset)==MSTrue) return MSA();
  if((s=hb->put()-hb->get())<4)
   {
     if((n=MSBuffer::buffToBuff(buf_,hb,4-s))<0) return MSA();
     if((s=hb->put()-hb->get())<4) return MSA();
     _bytesToNextMessage=MSA::longAt(hb->get());
     if (_bytesToNextMessage<=0) 
      {
	hb->reset();
        unset(MSProtocolConnection<MSA>::Read);
	return MSA();
      }
   }
  if((n=MSBuffer::buffToBuff(buf_,db,_bytesToNextMessage))<0) return MSA();
  if((_bytesToNextMessage-=n)==0)
   {
     MSA d=MSA::importAObject( (char *) db->get(), db->put()-db->get(), (char *)0);
     hb->reset();
     db->clear();
     unset(MSProtocolConnection<MSA>::Read);
     if(d.isNullMSA()==MSTrue)
      {
        resetWithError(MSProtocolConnection<MSA>::Read);return MSA();
      }
     return d;
   }
  return MSA(); 
}
Ejemplo n.º 10
0
char *getCurrentList(ListItem *list) {
	char *ret;
	char buffer[READ_LENGTH+1];
	int fileHandle;
	char *cursor;
	int attempt, goodPass;
	const int MAX_ATTEMPTS = 3;
	
	buffer[READ_LENGTH] = '\0';
	if (list->currentFilePosition == -1) {
		list->currentFilePosition = 0;		
		for (attempt=0,goodPass=0;attempt < MAX_ATTEMPTS;attempt++) {
			fileHandle = openList(list,NULL);
			readBuffer(fileHandle,buffer,READ_LENGTH);
			if (goodString(buffer,1)) {
				goodPass = 1;
				break;
			}
			close(fileHandle);
			logException(30,0,0); // log failed attempt
		}
		if (!goodPass)
			logException(30,0,RESET);
		buffer[READ_LENGTH] = '\0'; //prevents readLine from searching for \n past buffer
		for (cursor = buffer;*cursor != 0x0a && *cursor != 0x0d && *cursor != 0x00;cursor++);
		*cursor = 0x00;
		close(fileHandle);
		strcpy(list->currentString,buffer);
	}
	ret = list->currentString;
	return ret;
}
Ejemplo n.º 11
0
void Apex::LoadDynamicTriangleMesh(int numVerts, PxVec3* verts, ObjectInfo info)
{
	PxRigidDynamic* meshActor = mPhysics->createRigidDynamic(PxTransform::createIdentity());
	PxShape* meshShape, *convexShape;
	if(meshActor)
	{
		//meshActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true);

		PxTriangleMeshDesc meshDesc;
		meshDesc.points.count           = numVerts;
		meshDesc.points.stride          = sizeof(PxVec3);
		meshDesc.points.data            = verts;

		//meshDesc.triangles.count        = numInds/3.;
		//meshDesc.triangles.stride       = 3*sizeof(int);
		//meshDesc.triangles.data         = inds;

		PxToolkit::MemoryOutputStream writeBuffer;
		bool status = mCooking->cookTriangleMesh(meshDesc, writeBuffer);
		if(!status)
			return;

		PxToolkit::MemoryInputData readBuffer(writeBuffer.getData(), writeBuffer.getSize());

		PxTriangleMeshGeometry triGeom;
		triGeom.triangleMesh = mPhysics->createTriangleMesh(readBuffer);
		//triGeom.scale = PxMeshScale(PxVec3(info.sx,info.sy,info.sz),physx::PxQuat::createIdentity());
		
		meshShape = meshActor->createShape(triGeom, *defaultMaterial);
		//meshShape->setLocalPose(PxTransform(PxVec3(info.x,info.y,info.z)));
		meshShape->setFlag(PxShapeFlag::eUSE_SWEPT_BOUNDS, true);

		PxConvexMeshDesc convexDesc;
		convexDesc.points.count     = numVerts;
		convexDesc.points.stride    = sizeof(PxVec3);
		convexDesc.points.data      = verts;
		convexDesc.flags            = PxConvexFlag::eCOMPUTE_CONVEX;

		if(!convexDesc.isValid())
			return;
		PxToolkit::MemoryOutputStream buf;
		if(!mCooking->cookConvexMesh(convexDesc, buf))
			return;
		PxToolkit::MemoryInputData input(buf.getData(), buf.getSize());
		PxConvexMesh* convexMesh = mPhysics->createConvexMesh(input);
		PxConvexMeshGeometry convexGeom = PxConvexMeshGeometry(convexMesh);
		convexShape = meshActor->createShape(convexGeom, *defaultMaterial);
		//convexShape->setLocalPose(PxTransform(PxVec3(info.x,info.y,info.z)));
		//convexShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false);

		
		convexShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true);
		meshShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false);
		meshActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, false);

		meshActor->setGlobalPose(PxTransform(PxVec3(info.x,info.y,info.z), PxQuat(info.ry, PxVec3(0.0f,1.0f,0.0f))));
		mScene[mCurrentScene]->addActor(*meshActor);
		dynamicActors.push_back(meshActor);
	}
}
Ejemplo n.º 12
0
uint16_t
Enc28J60Network::readPacket(memhandle handle, memaddress position, uint8_t* buffer, uint16_t len)
{
  len = setReadPtr(handle, position, len);
  readBuffer(len, buffer);
  return len;
}
Ejemplo n.º 13
0
void CommsProcessor::serverCallback() {
	string sourceAddress;								// Address of datagram source
	unsigned short sourcePort;					// Port of datagram source
	listenSocket.setLocalPort( svrPort );

	// set up the listening socket
	this->listenSocket.setRecvTimeout( 500 ); // 500 ms

	while( running ) {
		int bytesRcvd;

		bytesRcvd = this->listenSocket.recvFrom( recvBuf, maxMsgSize, sourceAddress, sourcePort );

		// if recieve call timedout then just start loop over
		if( bytesRcvd == 0 )
			continue;

		Message *buf = (Message*)recvBuf;
		switch( MessageType(buf->header.msgType) ) {
			case MessageType::CLIENT_EVENT:
			{
				BufferReader readBuffer( buf->payload, buf->header.len);
				EventType type = Event::getType( readBuffer );
				Event* event = owner->eventCtors->invoke(readBuffer);
				handoffQ->push( event );

				break;
			}
			default:
				break;
		}
	}
}
Ejemplo n.º 14
0
void XMLParser::loadXMLBuffer(const QString &xml_buf)
{
    try
    {
        int pos1=-1, pos2=-1, tam=0;

        if(xml_buf.isEmpty())
            throw Exception(ERR_ASG_EMPTY_XML_BUFFER,__PRETTY_FUNCTION__,__FILE__,__LINE__);

        pos1=xml_buf.indexOf("<?xml");
        pos2=xml_buf.indexOf("?>");
        xml_buffer=xml_buf;

        if(pos1 >= 0 && pos2 >= 0)
        {
            tam=(pos2-pos1)+3;
            xml_decl=xml_buffer.mid(pos1, tam);
            xml_buffer.replace(pos1,tam,"");
        }
        else
            xml_decl="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

        removeDTD();
        readBuffer();
    }
    catch(Exception &e)
    {
        throw Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
    }
}
Ejemplo n.º 15
0
void BinaryDataHandler::pullBuffer()
{
    readBuffer();

    _currentReadBuffer    = readBufBegin();
    _currentReadBufferPos = 0;
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Read an Huffman code
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
imbxUint32 huffmanTable::readHuffmanCode(streamReader* pStream)
{
	PUNTOEXE_FUNCTION_START(L"huffmanTable::readHuffmanCode");

	// Read initial number of bits
	imbxUint32 readBuffer(pStream->readBits(m_firstValidLength));

	// Validate the current Huffman code. If it's OK, then
	//  return the ordered value
	///////////////////////////////////////////////////////////
	if(readBuffer<=m_maxValuePerLength[m_firstValidLength])
	{
		return m_orderedValues[readBuffer - m_minValuePerLength[m_firstValidLength]];
	}

	imbxUint32 orderedValue(m_valuesPerLength[m_firstValidLength]);

	// Scan all the codes sizes
	///////////////////////////////////////////////////////////
	for(imbxUint8 scanSize(m_firstValidLength + 1), missingBits(0); scanSize != sizeof(m_valuesPerLength)/sizeof(m_valuesPerLength[0]); ++scanSize)
	{
		++missingBits;

		// If the active length is empty, then continue the loop
		///////////////////////////////////////////////////////////
		if(m_valuesPerLength[scanSize] == 0)
		{
			continue;
		}

		readBuffer <<= missingBits;
		if(missingBits == 1)
		{
			readBuffer |= pStream->readBit();
		}
		else
		{
			readBuffer |= pStream->readBits(missingBits);
		}

		// Validate the current Huffman code. If it's OK, then
		//  return the ordered value
		///////////////////////////////////////////////////////////
		if(readBuffer<=m_maxValuePerLength[scanSize])
		{
			return m_orderedValues[orderedValue + readBuffer - m_minValuePerLength[scanSize]];
		}

		orderedValue += m_valuesPerLength[scanSize];

		// Reset the number of bits to read in one go
		///////////////////////////////////////////////////////////
		missingBits = 0;

	}

	PUNTOEXE_THROW(huffmanExceptionRead, "Invalid huffman code found while reading from a stream");

	PUNTOEXE_FUNCTION_END();
}
Ejemplo n.º 17
0
AMF0DataTypes RtmpParser::peekAMF0DataType(RtmpMsgHeaderPtr& mh)
{
    if(mh->length < 0)
    {
        throw RtmpBadProtocalData("body length should >= 0");
    }

    ReadBufferPtr readBuffer(new ReadBuffer(mh->length));
    readBuffer->appendData(mh->body, mh->length);

    AMF0ParserPtr ap(new AMF0Parser(readBuffer));

    try
    {
        string cmd = ap->parseAsString();    

        if(cmd.compare("@setDataFrame") == 0)
        {
            return AMF0_DATA_SetDataFrame;
        }
        else
        {
            throw RtmpNotSupported(cmd.c_str());
        }
    }
    catch(RtmpNoEnoughData& e)
    {
        throw RtmpBadProtocalData("length and body do not match");
    }
    catch(RtmpInvalidAMFData& ae)
    {
        throw RtmpBadProtocalData("peekAMF0DataType, data is corrupted");
    }
}
void ossimPlanetSocketNetworkConnection::receive()
{
#if 1
    if(theSocket.valid())
    {
       attemptToFlushOutBuffer();
       std::vector<char> readBuffer(4096);
       int bytesRead = theSocket->recv(&readBuffer.front(), readBuffer.size());
       if (bytesRead > 0)
       {
          inBuffer_.append(readBuffer.begin(), readBuffer.begin() + bytesRead);
       }
       else if (bytesRead == -1)
       {
          //std::cerr << "ossimPlanetSocketNetworkConnection::receive() failed to read data. NetworkConnection::name() = " << name_ << std::endl;
       }

       for (ossim_int64 eoc = inBuffer_.find(actionDelimiter_); eoc != std::string::npos; eoc = inBuffer_.find(actionDelimiter_))
       {
          ossimPlanetDestinationCommandAction(inBuffer_.substr(0, eoc), 
                                              "ossimPlanetSocketNetworkConnection-" + name_).execute();
          inBuffer_.erase(0, eoc + 1);
       }
    }
#endif
}
Ejemplo n.º 19
0
void MSAConnection::doRead(void)
{
  MSBuffer *hb=headBuffer() ;
  MSBuffer *db=readBuffer() ;
  int s,n;
  
  if (isSet(MSProtocolConnection<MSA>::Reset)==MSTrue) return;
  if((s=hb->put()-hb->get())<4)
   {
     if((n=readTheBuffer(hb,4-s))<0) return;
     if((s=hb->put()-hb->get())<4) return;
     _bytesToNextMessage=MSA::longAt(hb->get());
     if (_bytesToNextMessage<=0) 
      {
	hb->reset();
        unset(MSProtocolConnection<MSA>::Read);
	return;
      }
   }
  if((n=readTheBuffer(db,_bytesToNextMessage))<0) return;
  if((_bytesToNextMessage-=n)==0)
   {
     MSA d=MSA::importAObject( (char *) db->get(), db->put()-db->get(), (char *)0);
     hb->reset();
     db->clear();
     unset(MSProtocolConnection<MSA>::Read);
     if(d.isNullMSA()==MSTrue){resetWithError(MSProtocolConnection<MSA>::Read);return;}
     readNotify(d);
   }
  return; 
}
Ejemplo n.º 20
0
bool LoaderNifti::load()
{
    QString hdrPath = m_fileName.path();
    QString fn = m_fileName.path();
    if ( fn.endsWith( ".ima" ) || fn.endsWith( ".img" ) )
    {
        hdrPath.replace( hdrPath.size() - 3, 3, "hdr" );
    }

    if ( !loadNiftiHeader( hdrPath ) )
    {
        return false;
    }

    if ( !loadData( fn ) )
    {
        return false;
    }

    if( m_header->ext_list )
    {
        char* extData = reinterpret_cast<char*>( m_header->ext_list[0].edata );
        QByteArray ba( extData, m_header->ext_list[0].esize );

        QBuffer readBuffer( &ba );
        readBuffer.open( QIODevice::ReadOnly );
        QDataStream in( &readBuffer );

        in >> m_propStates;
    }
Ejemplo n.º 21
0
size_t LoopingAudioStream::readBuffer(int16 *buffer, const size_t numSamples) {
	if ((_loops && _completeIterations == _loops) || !numSamples)
		return 0;

	const size_t samplesRead = _parent->readBuffer(buffer, numSamples);
	if (samplesRead == kSizeInvalid)
		return kSizeInvalid;

	if (_parent->endOfStream()) {
		++_completeIterations;
		if (_completeIterations == _loops)
			return samplesRead;

		const size_t remainingSamples = numSamples - samplesRead;

		if (!_parent->rewind()) {
			// TODO: Properly indicate error
			_loops = _completeIterations = 1;
			return samplesRead;
		}

		const size_t samplesReadNext = readBuffer(buffer + samplesRead, remainingSamples);
		if (samplesReadNext == kSizeInvalid)
			return kSizeInvalid;

		return samplesRead + samplesReadNext;
	}

	return samplesRead;
}
JNIEXPORT jint JNICALL Java_com_badlogic_gdx_audio_io_Mpg123Decoder_skipSamples(JNIEnv* env, jobject object, jlong handle, jint numSamples) {


//@line:189

		Mp3File* mp3 = (Mp3File*)handle;
	
		int idx = 0;
		while( idx != numSamples )
		{
			if( mp3->leftSamples > 0 )
			{
				for( ; idx < numSamples && mp3->offset < mp3->buffer_size / 2; mp3->leftSamples--, mp3->offset++, idx++ );
			}
			else
			{
				int result = readBuffer( mp3 );
				if( result == 0 )
					return 0;
			}
	
		}
	
		if( idx > numSamples )
			return 0;
	
		return idx;
	

}
Ejemplo n.º 23
0
void transmitIfBufferNotEmpty(char** pTransmit, char* pBufferHead, char* pBuffer, int* write) {
	if(*load) {
		  *load = 0;
	  }

	  char c = '\0';
	  if(*write) {
		  c = readBuffer(pTransmit, pBufferHead, pBuffer);
		  if(c != '\0' && c != 0x60 ) {
			  alt_putstr("writing: ");
			  alt_putchar(c);
			  alt_putstr("\n");
			  *write = 0;
			  *data_bus_output = c;
			  usleep(1000);
			  *load = 1;
			  *transmit_enable = 1;
			  //alt_putchar(c);
			  *data_bus_LEDs = (*load) | (*transmit_enable << 1) | (*character_sent << 2) | (*character_received << 3);
			  //*data_bus_LEDs = c;
			  usleep(500);
		  }
	  }
	  if(*character_sent) {
		  alt_putstr("char sent\n");
		  *write = 1;
		  *transmit_enable = 0;
	  }
}
Ejemplo n.º 24
0
bool WorkerProtocolImpl::claimProblems(const std::vector<ProblemID>& problems)
{
#ifdef DEBUG
    std::cout << "Requesting " << problems.size() << " problems\n";
    std::cout << "They are:\n";
    for( unsigned i = 0; i < problems.size(); ++i )
        std::cout << "\t" << problems[i].idnum << "\n";
#endif
    msgpack::sbuffer sbuf;
    message_id_t msg_id = PROBLEM_CLAIM_REQUEST_ID;
    msgpack::pack(&sbuf, msg_id);
    msgpack::pack(&sbuf, problems);
    sendBuffer(socket, sbuf);
    
    msgpack::unpacker unpack;
    readBuffer(socket, unpack);
    read(unpack, msg_id);
	if( msg_id != PROBLEM_CLAIM_RESPONSE_ID )
	{
		std::cout << "Attempted to claim problems, but got back message type " << msg_id << " instead.";
		throw std::runtime_error("Error in protocol talking to leader.  See logs");
	}
	
    bool result;
    read(unpack, result);
    
	return result;
}
Ejemplo n.º 25
0
int SubLoopingAudioStream::readBuffer(int16 *buffer, const int numSamples) {
	if (_done)
		return 0;

	int framesLeft = MIN(_loopEnd.frameDiff(_pos), numSamples);
	int framesRead = _parent->readBuffer(buffer, framesLeft);
	_pos = _pos.addFrames(framesRead);

	if (framesRead < framesLeft && _parent->endOfData()) {
		// TODO: Proper error indication.
		_done = true;
		return framesRead;
	} else if (_pos == _loopEnd) {
		if (_loops != 0) {
			--_loops;
			if (!_loops) {
				_done = true;
				return framesRead;
			}
		}

		if (!_parent->seek(_loopStart)) {
			// TODO: Proper error indication.
			_done = true;
			return framesRead;
		}

		_pos = _loopStart;
		framesLeft = numSamples - framesLeft;
		return framesRead + readBuffer(buffer + framesRead, framesLeft);
	} else {
		return framesRead;
	}
}
Ejemplo n.º 26
0
int LoopingAudioStream::readBuffer(int16 *buffer, const int numSamples) {
	if ((_loops && _completeIterations == _loops) || !numSamples)
		return 0;

	int samplesRead = _parent->readBuffer(buffer, numSamples);

	if (_parent->endOfStream()) {
		++_completeIterations;
		if (_completeIterations == _loops)
			return samplesRead;

		const int remainingSamples = numSamples - samplesRead;

		if (!_parent->rewind()) {
			// TODO: Properly indicate error
			_loops = _completeIterations = 1;
			return samplesRead;
		}
		if (_parent->endOfStream()) {
			// Apparently this is an empty stream
			_loops = _completeIterations = 1;
		}

		return samplesRead + readBuffer(buffer + samplesRead, remainingSamples);
	}

	return samplesRead;
}
static inline jint wrapped_Java_com_badlogic_gdx_audio_io_Mpg123Decoder_readSamples
(JNIEnv* env, jobject object, jlong handle, jshortArray obj_buffer, jint offset, jint numSamples, short* buffer) {

//@line:159
	
		Mp3File* mp3 = (Mp3File*)handle;
		short* target = buffer + offset;
	
		int idx = 0;
		while( idx != numSamples )
		{
			if( mp3->leftSamples > 0 )
			{
				short* src = ((short*)mp3->buffer) + mp3->offset;
				for( ; idx < numSamples && mp3->offset < mp3->buffer_size / 2; mp3->leftSamples--, mp3->offset++, target++, src++, idx++ )
				{
					*target = *src;
				}
			}
			else
			{
				int result = readBuffer( mp3 );
				if( result == 0 )
					return 0;
			}
	
		}
	
		if( idx > numSamples )
			return 0;
	
		return idx;
	
}
Ejemplo n.º 28
0
void *PCHRead( void *p, unsigned size )
/*************************************/
{
    unsigned aligned_size;
    unsigned left;
    char *buff_ptr;
    void *retn;

    PCHTrashAlreadyRead();
    retn = p;
    buff_ptr = pch_buff_cur;
    left = pch_buff_eob - buff_ptr;
    aligned_size = _pch_align_size( size );
    for( ; aligned_size > left; ) {
        p = memcpy( p, buff_ptr, left );
        p = (char *)p + left;
        size -= left;
        aligned_size -= left;
        left = readBuffer( 0 );
        buff_ptr = ioBuffer;
        DbgAssert( ( aligned_size % PCH_ALIGN ) == 0 );
    }
    memcpy( p, buff_ptr, size );
    pch_buff_cur = buff_ptr + aligned_size;
    return retn;
}
Ejemplo n.º 29
0
void GzipDecompressTask::run() {
    taskLog.details(tr("Start decompression '%1'").arg(zippedUrl.getURLString()));

    SAFE_POINT_EXT(AppContext::getIOAdapterRegistry() != NULL, setError(tr("IOAdapterRegistry is NULL!")), );

    IOAdapterFactory* inFactory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::GZIPPED_LOCAL_FILE);
    SAFE_POINT_EXT(inFactory != NULL, setError(tr("IOAdapterFactory is NULL!")), );
    IOAdapterFactory* outFactory = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE);
    SAFE_POINT_EXT(outFactory != NULL, setError(tr("IOAdapterFactory is NULL!")), );

    QScopedPointer<IOAdapter> in(inFactory->createIOAdapter());
    SAFE_POINT_EXT(!in.isNull(), setError(tr("Can not create IOAdapter!")), );

    QScopedPointer<IOAdapter> out(outFactory->createIOAdapter());
    SAFE_POINT_EXT(!out.isNull(), setError(tr("Can not create IOAdapter!")), );

    if (unzippedUrl.isEmpty()) {
        QString unzippedUrlString = zippedUrl.dirPath() + "/" + QFileInfo(zippedUrl.getURLString()).completeBaseName();
        if (unzippedUrlString == zippedUrl.getURLString()) {
            unzippedUrlString.append("_decompressed");
        }
        unzippedUrl = GUrl(unzippedUrlString);
    }

    bool res = out->open( unzippedUrl, IOAdapterMode_Write);
    if (!res) {
        Task::setError(tr("Can not open output file '%1'").arg(unzippedUrl.getURLString()));
        return;
    }

    res = in->open( zippedUrl, IOAdapterMode_Read);
    if (!res) {
        Task::setError(tr("Can not open input file '%1'").arg(zippedUrl.getURLString()));
        return;
    }

    const int BUFFER_SIZE = 2097152;
    QByteArray readBuffer(BUFFER_SIZE, '\0');
    char* buffer = readBuffer.data();

    do {
        if ( isCanceled() ) {
            return;
        }

        int len = in->readBlock(buffer, BUFFER_SIZE);
        if (len == -1) {
            stateInfo.setError(tr("Error reading file"));
            return;
        }

        int written = out->writeBlock(buffer, len);
        if (written == -1) {
            stateInfo.setError(tr("Error writing to file"));
            return;
        }
    } while ( !in->isEof() );

    taskLog.details(tr("Decompression finished"));
}
Ejemplo n.º 30
0
JNIEXPORT jint JNICALL Java_com_axelby_podax_player_MPG123_readSamples
	(JNIEnv *env, jclass c, jlong handle, jshortArray obj_buffer, jint offset, jint numSamples)
{
    MP3File *mp3 = (MP3File *)handle;
	short* buffer = (short*)(*env)->GetPrimitiveArrayCritical(env, obj_buffer, 0);
    short* target = buffer + offset;

	int idx = 0;
    while (idx != numSamples)
    {
        if (mp3->leftSamples > 0) {
            short* src = ((short*)mp3->buffer) + mp3->offset;
            while (idx < numSamples && mp3->offset < mp3->buffer_size / 2) {
                *target = *src;
				mp3->leftSamples--;
				mp3->offset++;
				target++;
				src++;
				idx++;
			}
        } else if (readBuffer(mp3) == 0) {
			(*env)->ReleasePrimitiveArrayCritical(env, obj_buffer, buffer, 0);
			return 0;
		}
    }

	(*env)->ReleasePrimitiveArrayCritical(env, obj_buffer, buffer, 0);
    return idx > numSamples ? 0 : idx;
}