示例#1
0
void AudioDecoderThread::handleSeekDone(AVPacket* pPacket)
{
    m_MsgQ.clear();
    m_LastFrameTime = float(pPacket->dts*av_q2d(m_pStream->time_base))
            - m_AudioStartTimestamp;

   if (fabs(m_LastFrameTime - m_SeekTime) < 0.01) {
        pushSeekDone(m_LastFrameTime, m_SeekSeqNum);
        decodePacket(pPacket);
        m_State = DECODING;
    } else {
        if (m_LastFrameTime-0.01f < m_SeekTime) {
            // Received frame that's earlier than the destination, so throw away frames
            // until the time is correct.
            m_State = DISCARDING;
        } else {
            // Received frame that's too late, so insert a buffer of silence to 
            // compensate.
            insertSilence(m_LastFrameTime - m_SeekTime);
            m_LastFrameTime = m_SeekTime;
            pushSeekDone(m_LastFrameTime, m_SeekSeqNum);
            decodePacket(pPacket);
            m_State = DECODING;
        }
    }
}
int readPacket(Client* c, Timer* timer) 
{
    int rc = FAILURE;
    MQTTHeader header = {0};
    int len = 0;
    int rem_len = 0;

    /* 1. read the header byte.  This has the packet type in it */
    if (c->ipstack->mqttread(c->ipstack, c->readbuf, 1, left_ms(timer)) != 1)
        goto exit;

    len = 1;
    /* 2. read the remaining length.  This is variable in itself */
    decodePacket(c, &rem_len, left_ms(timer));

    // if the buffer is too big then the message will be dropped silently
    if(rem_len >= c->readbuf_size){
    	goto exit;
    }
    len += MQTTPacket_encode(c->readbuf + 1, rem_len); /* put the original remaining length back into the buffer */

    /* 3. read the rest of the buffer using a callback to supply the rest of the data */
    if (rem_len > 0 && (c->ipstack->mqttread(c->ipstack, c->readbuf + len, rem_len, left_ms(timer)) != rem_len))
        goto exit;

    header.byte = c->readbuf[0];
    rc = header.bits.type;
exit:
    return rc;
}
示例#3
0
Packet::Packet(const Packet &other, QObject *parent) :
	QObject(parent)
{
    memcpy(&packet, &other.packet, sizeof(packet));
	decodePacket();
	setIndex(other.packetIndex);
}
static int readPacket(MQTTClient* c, Timer* timer)
{
	int rc = FAILURE;
	MQTTHeader header = {0};
	int len = 0;
	int rem_len = 0;

#ifdef CONFIG_AXTLS
	if(!(len = c->ipstack->mqttread(c->ipstack, c->readbuf, c->readbuf_size, TimerLeftMS(timer))))
		goto exit;
#else
	/* 1. read the header byte.  This has the packet type in it */
	if (c->ipstack->mqttread(c->ipstack, c->readbuf, 1, TimerLeftMS(timer)) != 1)
		goto exit;

	len = 1;
	/* 2. read the remaining length.  This is variable in itself */
	decodePacket(c, &rem_len, TimerLeftMS(timer));

	len += MQTTPacket_encode(c->readbuf + 1, rem_len); /* put the original remaining length back into the buffer */

	/* 3. read the rest of the buffer using a callback to supply the rest of the data */
	if (rem_len > 0 && (c->ipstack->mqttread(c->ipstack, c->readbuf + len, rem_len, TimerLeftMS(timer)) != rem_len))
		goto exit;
#endif

	header.byte = c->readbuf[0];
	rc = header.bits.type;
exit:
	return rc;
}
示例#5
0
static int readPacket(MQTTClient* c, Timer* timer)
{
    int rc = MQTT_FAILURE;
    MQTTHeader header = {0};
    int len = 0;
    int rem_len = 0;

    /* 1. read the header byte.  This has the packet type in it */
	int read_bytes = platform_network_read(c->ipstack, c->readbuf, 1, platform_timer_left(timer));

	if (read_bytes != 1) 
	{
		if (read_bytes == 0) 
			rc = MQTT_CONNECTION_LOST;
        goto exit;
	}

    len = 1;
    /* 2. read the remaining length.  This is variable in itself */
    decodePacket(c, &rem_len, platform_timer_left(timer));
    len += MQTTPacket_encode(c->readbuf + 1, rem_len); /* put the original remaining length back into the buffer */

    /* 3. read the rest of the buffer using a callback to supply the rest of the data */
    if (rem_len > 0 && (platform_network_read(c->ipstack, c->readbuf + len, rem_len, platform_timer_left(timer)) != rem_len))
        goto exit;

    header.byte = c->readbuf[0];
    rc = header.bits.type;
exit:
    return rc;
}
示例#6
0
bool VideoDecoderThread::work() 
{
    ScopeTimer timer(DecoderProfilingZone);
    if (m_bProcessingLastFrames) {
        // EOF received, but last frames still need to be decoded.
        handleEOF();
    } else {
        // Standard decoding.
        VideoMsgPtr pMsg;
        {
            ScopeTimer timer(PacketWaitProfilingZone);
            pMsg = m_PacketQ.pop(true);
        }
        switch (pMsg->getType()) {
            case VideoMsg::PACKET:
                decodePacket(pMsg->getPacket());
                break;
            case VideoMsg::END_OF_FILE:
                handleEOF();
                m_bProcessingLastFrames = true;
                break;
            case VideoMsg::SEEK_DONE:
                handleSeekDone(pMsg);
                break;
            case VideoMsg::CLOSED:
                close();
                break;
            default:
                pMsg->dump();
                AVG_ASSERT(false);
        }
    }
    ThreadProfiler::get()->reset();
    return true;
}
示例#7
0
文件: Capture.cpp 项目: joekr552/sgct
bool Capture::poll()
{
	if (!mInited)
		return false;
	
	int ret;
	int gotVideoFrame;

	bool all_ok = true;

	if (av_read_frame(mFMTContext, &mPkt) >= 0)
	{
		AVPacket orig_pkt = mPkt;

		do
		{
			ret = decodePacket(&gotVideoFrame);
			if (ret < 0)
			{
				sgct::MessageHandler::instance()->print(sgct::MessageHandler::NOTIFY_ERROR, "Failed to decode package!\n");
				all_ok = false;
				break;
			}

			mPkt.data += ret;
			mPkt.size -= ret;

		} while (mPkt.size > 0);

		av_free_packet(&orig_pkt);
	}

	return all_ok;
}
示例#8
0
void DdeFaceTracker::readPendingDatagrams() {
    QByteArray buffer;
    while (_udpSocket.hasPendingDatagrams()) {
        buffer.resize(_udpSocket.pendingDatagramSize());
        _udpSocket.readDatagram(buffer.data(), buffer.size());
    }
    decodePacket(buffer);
}
示例#9
0
Packet::Packet(QByteArray &data, QObject *parent) :
	QObject(parent)
{
	memset(&packet, 0, sizeof(packet));
	size_t size = data.length();
	if (size > sizeof(packet))
		size = sizeof(packet);
	memcpy(&packet, data, size);
	decodePacket();
}
示例#10
0
    void onMessage(const struct mosquitto_message *msg) {
        char *payloadStr = strndup((const char *)msg->payload, msg->payloadlen);
        const Packet pkg = decodePacket(std::string(payloadStr));
        LOG("got MQTT message on topic %s: %s", msg->topic, payloadStr);
        free(payloadStr);

        const Port *port = findPortByTopic(options.info.inports, msg->topic);
        if (port) {
            LOG("sending to %d %d \n", port->node, port->port);
            network->sendMessageTo(port->node, port->port, pkg);
        } else {
            LOG("Failed to find port for MQTT topic: %s", msg->topic);
        }
    }
示例#11
0
AlgorithmStatus AudioLoader::process() {
    if (!parameter("filename").isConfigured()) {
        throw EssentiaException("AudioLoader: Trying to call process() on an AudioLoader algo which hasn't been correctly configured.");
    }

    // read frames until we get a good one
    do {
        int result = av_read_frame(_demuxCtx, &_packet);
        //E_DEBUG(EAlgorithm, "AudioLoader: called av_read_frame(), got result = " << result);
        if (result != 0) {
            // 0 = OK, < 0 = error or EOF
            if (result != AVERROR_EOF) {
                char errstring[1204];
                av_strerror(result, errstring, sizeof(errstring));
                ostringstream msg;
                msg << "AudioLoader: Error reading frame: " << errstring;
                E_WARNING(msg.str());
            }
            // TODO: should try reading again on EAGAIN error?
            //       https://github.com/FFmpeg/FFmpeg/blob/master/ffmpeg.c
            shouldStop(true);
            flushPacket();
            closeAudioFile();
            if (_computeMD5) {
                av_md5_final(_md5Encoded, _checksum);
                _md5.push(uint8_t_to_hex(_checksum, 16));
            }
            else {
                string md5 = "";
                _md5.push(md5);
            }
            return FINISHED;
        }
    } while (_packet.stream_index != _streamIdx);

    // compute md5 first
    if (_computeMD5) {
        av_md5_update(_md5Encoded, _packet.data, _packet.size);
    }

    // decode frames in packet
    while(_packet.size > 0) {
        if (!decodePacket()) break;
        copyFFmpegOutput();
    }
    // neds to be freed !!
    av_free_packet(&_packet);
    
    return OK;
}
	bool feedOne(const uint16_t sample)
	{
		//XXX: _ringbuffer.increment();
		//_ringbuffer.put((int)sample);
		RB_inc();
		RB(0) = (int)sample;

		if (--_skip < 1) {
			if (decodePacket(++_samples)) {
				_skip = 20;
				return true;
			}
		}
		return false;
	}
示例#13
0
////////////////////////////////////////////////////
// process the packets payload, decoding if necessary
void EQPacketStream::processPayload(uint8_t* data, size_t len)
{
  uint16_t opCode = *(uint16_t*)data;
  
  data += 2;
  len -= 2;
  
  if (opCode & FLAG_DECODE)
    decodePacket(data, len, opCode);
  else
  {
    emit rawPacket(data, len, m_dir, opCode);

    dispatchPacket(data, len, opCode, m_opcodeDB.find(opCode));
  }
}
示例#14
0
bool AudioDecoderThread::work() 
{
    ScopeTimer timer(DecoderProfilingZone);
    VideoMsgPtr pMsg;
    {
        ScopeTimer timer(PacketWaitProfilingZone);
        pMsg = m_PacketQ.pop(true);
    }
    switch (pMsg->getType()) {
        case VideoMsg::PACKET: {
            AVPacket* pPacket = pMsg->getPacket();
            switch(m_State) {
                case DECODING:
                    decodePacket(pPacket);
                    break;
                case SEEK_DONE:
                    handleSeekDone(pPacket);
                    break;
                case DISCARDING:
                    discardPacket(pPacket);
                    break;
                default:
                    AVG_ASSERT(false);
            }
            av_free_packet(pPacket);
            delete pPacket;
            break;
        }
        case VideoMsg::SEEK_DONE:
            m_State = SEEK_DONE;
            m_SeekSeqNum = pMsg->getSeekSeqNum();
            m_SeekTime = pMsg->getSeekTime();
            break;
        case VideoMsg::END_OF_FILE:
            pushEOF();
            break;
        case VideoMsg::CLOSED:
            m_MsgQ.clear();
            stop();
            break;
        default:
            pMsg->dump();
            AVG_ASSERT(false);
    }
    ThreadProfiler::get()->reset();
    return true;
}
示例#15
0
Packet::Packet(QIODevice &source, QObject *parent) :
	QObject(parent)
{
	qint64 bytesRead;

	memset(&packet, 0, sizeof(packet));
	bytesRead = streamReadData(source, (char *)(&packet.header), sizeof(packet.header));
	if (bytesRead != sizeof(packet.header)) {
		qDebug() << "Read an unexpected number of bytes:" << bytesRead << "vs" << sizeof(packet.header);
	}
	if (_ntohs(packet.header.size) > sizeof(packet)) {
		qDebug() << "Header size is VERY wrong:" << _ntohs(packet.header.size);
	}

	bytesRead = streamReadData(source, (char *)(&packet.data), _ntohs(packet.header.size) - sizeof(packet.header));
	decodePacket();
}
示例#16
0
	bool decodeFrame(StreamFrameMap& streamFrames)
	{
		bool done = false;

		while(!done)
		{
			// demux
			PacketPtr packet = demuxPacket();
			if(packet == 0){
				FlogE("demuxing failed");
				return 0;
			}

			// decode
			decodePacket(packet, streamFrames);

			// check if any frames finished
			for(auto pair : streamFrames){
				FramePtr frame = pair.second;
				if(frame->finished != 0){
					// set timestamp and break out of loop
					int64_t pts = av_frame_get_best_effort_timestamp(frame->GetAvFrame());

					if(pair.first == videoStream){
						if(firstDts == AV_NOPTS_VALUE){
							firstDts = frame->GetAvFrame()->pkt_dts;
							FlogD("setting firstDts to: " << firstDts);
						}

						if(firstPts == AV_NOPTS_VALUE){
							firstPts = pts;
							FlogD("setting firstPts to: " << firstPts);
						}
					}
					
					frame->SetPts(pts);
					done = true;
				}
			}
		}
		
		// successfully decoded frame, reset retry counter
		ResetRetries();

		return true;
	}
示例#17
0
int main(int argc, char** argv) {
    VictoryConnect::Client* client = new VictoryConnect::Client("test-id","Test");
    std::cout<<"----- VictoryConnect Test Client Info -----" << std::endl;
    std::cout<<"Client ID: \t" << client->getId()<<std::endl;
    std::cout<<"Client Name: \t" << client->getName()<<std::endl;

    client->subscribe("test/path", [](Packet packet) -> void {
        std::cout << "\t Packet: \t " << packet.getPath() << std::endl;
    });

    client->enableTCP("127.0.0.1", 5000);

    char sender = 12;
    char recvier = 4;
    char type     = 1;
    char protocol = 4;
    char* path = "test/path";
    uint8_t path_len = strlen(path);
    char* data = "test;test;test;test";
    uint32_t data_len = strlen(data);
    
    

    char packet[1+1+1+1+path_len+data_len+1];
    
    memcpy(packet,    (char*) &sender,  1);
    memcpy(packet + 1,(char*) &recvier, 1);
    memcpy(packet + 2,(char*) &type, 1);
    memcpy(packet + 3,(char*) &protocol, 1);

    memcpy(packet + 4,(char*) &path_len, 1);
    memcpy(packet + 5, path, path_len);

    memcpy(packet + 5 + path_len + 1,(char*) &data_len, 4);
    memcpy(packet + 5 + path_len + 2, data, data_len);
    memset(packet + sizeof(packet) -1, 0x00,1);


    ////////////////////////////////////////
    decodePacket(packet);

    
    
    return 0;
}
示例#18
0
void MulticastServer::run(void) {
	socketMsg *socketMessage;
	int returnCode;

#ifdef DEBUGOUTPUT
	systemLog->sysLog(DEBUG, "Multicast server is running and waiting for packets");
#endif
	for (;;) {
		socketMessage = recvMessage(sd);
#ifdef DEBUGOUTPUT
		systemLog->sysLog(DEBUG, "multicast packet size is %d", socketMessage->brecv);
#endif
		if (socketMessage) {
			returnCode = decodePacket(socketMessage->recvmsg);
			free(socketMessage);
			socketMessage = NULL;
		}
	}
}
void ClusterMembership::HandleMessage()
{
	char buf[1024];
	// Read message from sock
	struct sockaddr_in sender;
	socklen_t senderlen = sizeof(sender);
	int len = recvfrom(sock, buf, sizeof(buf),
			0 /* flags */ ,
			(struct sockaddr *) &sender, &senderlen);
	// If we get EAGAIN, ignore
	if (len == -1) {
		if (errno == EAGAIN) {
			return;
		}
		throw std::runtime_error("recv failed");
	}
	// decide what to do with it etc
	decodePacket(buf,len, IpAddress(& sender.sin_addr));
}
示例#20
0
int NetherNetlink::callback(struct nfq_q_handle *, struct nfgenmsg *, struct nfq_data *nfa, void *data)
{
	NetherNetlink *me = static_cast<NetherNetlink *>(data);
	NetherPacket packet;
	unsigned char *secctx;
	int secctxSize = 0;
	struct nfqnl_msg_packet_hdr *ph;
	unsigned char *payload;

	if((ph = nfq_get_msg_packet_hdr(nfa)))
	{
		packet.id = ntohl(ph->packet_id);
	}
	else
	{
		LOGI("Failed to get packet id");
		return (1);
	}

	/* get interface information if requested */
	me->getInterfaceInfo(nfa, packet);

	if(nfq_get_uid(nfa, &packet.uid) == 0)
		LOGW("Failed to get uid for packet id=" << packet.id);

	nfq_get_gid(nfa, &packet.gid);

	secctxSize = nfq_get_secctx(nfa, &secctx);

	if(secctxSize > 0)
		packet.securityContext = std::string((char *)secctx, secctxSize);
	else
		LOGD("Failed to get security context for packet id=" << packet.id);

	if(me->netherConfig.copyPackets && nfq_get_payload(nfa, &payload) > 0)
		decodePacket(packet, payload);

	me->processNetherPacket(packet);  /* this call if from the NetherPacketProcessor class */

	return (0);
}
示例#21
0
static int readPacket(MQTTClient *c, Timer *timer)
{
    MQTTHeader header = {0};
    int len = 0;
    int rem_len = 0;

    /* 1. read the header byte.  This has the packet type in it */
    int rc = c->ipstack->mqttread(c->ipstack, c->readbuf, 1, TimerLeftMS(timer));

    if (rc != 1) {
        goto exit;
    }

    len = 1;
    /* 2. read the remaining length.  This is variable in itself */
    decodePacket(c, &rem_len, TimerLeftMS(timer));
    len += MQTTPacket_encode(c->readbuf + 1, rem_len); /* put the original remaining length back into the buffer */

    if (rem_len > (c->readbuf_size - len)) {
        rc = BUFFER_OVERFLOW;
        goto exit;
    }

    /* 3. read the rest of the buffer using a callback to supply the rest of the data */
    if (rem_len > 0 && (rc = c->ipstack->mqttread(c->ipstack, c->readbuf + len, rem_len, TimerLeftMS(timer)) != rem_len)) {
        rc = 0;
        goto exit;
    }

    header.byte = c->readbuf[0];
    rc = header.bits.type;

    if (c->keepAliveInterval > 0) {
        TimerCountdown(&c->last_received, c->keepAliveInterval);    // record the fact that we have successfully received a packet
    }

exit:
    return rc;
}
示例#22
0
AlgorithmStatus AudioLoader::process() {
    if (!parameter("filename").isConfigured()) {
        throw EssentiaException("AudioLoader: Trying to call process() on an AudioLoader algo which hasn't been correctly configured.");
    }

    // read frames until we get a good one
    do {
        int result = av_read_frame(_demuxCtx, &_packet);
        //E_DEBUG(EAlgorithm, "AudioLoader: called av_read_frame(), got result = " << result);

        if (result != 0) {
            shouldStop(true);
            flushPacket();
            closeAudioFile();
            return FINISHED;
        }
    } while (_packet.stream_index != _streamIdx);

    decodePacket();
    copyFFmpegOutput();

    return OK;
}
示例#23
0
void vrpn_nVidia_shield::on_data_received(size_t bytes, vrpn_uint8 *buffer)
{
  decodePacket(bytes, buffer);
}
示例#24
0
void vrpn_Griffin::on_data_received(size_t bytes, vrpn_uint8 *buffer)
{
  decodePacket(bytes, buffer);
}
示例#25
0
void vrpn_Logitech_Controller_Raw::on_data_received(size_t bytes, vrpn_uint8 *buffer)
{
	decodePacket(bytes, buffer);
}
示例#26
0
void vrpn_Retrolink::on_data_received(size_t bytes, vrpn_uint8 *buffer)
{
  decodePacket(bytes, buffer);
}
示例#27
0
void vrpn_Contour::on_data_received(size_t bytes, vrpn_uint8 *buffer)
{
  decodePacket(bytes, buffer);
}
示例#28
0
int main(int argn, char **argc){
	if(argn != 3){
		printf("usage: convert infile.bin outfile.mat\n"); 
		exit(0); 
	} else {
		FILE* in = fopen(argc[1], "r"); 
		if(!in) {
			printf("could not open %s\n", argc[1]); 
			exit(0); 
		}
		mat_t *mat;
		mat = Mat_Create(argc[2],NULL);
		if(!mat){
			printf("could not open for writing %s\n", argc[2]); 
			exit(0); 
		}
		//this is (for now) a two-stage process: 
		//have to scan through the file, 
		//determine what's there, allocate memory appropritately, 
		//then fill those structures up and write *that* out.
		unsigned int u; 
		unsigned int pos = 0;
		unsigned int rxpackets = 0; 
		unsigned int txpackets = 0; 
		unsigned int msgpackets = 0; 
		bool done = false; 
		while(!done){
			fread((void*)&u,4,1,in);
			if(ferror(in) || feof(in)) done = true; 
			else {
				if(u == 0xdecafbad){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					rxpackets += (siz-4)/(32+4); 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				}else if(u == 0xc0edfad0){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					txpackets++; 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				}else if(u == 0xb00a5c11){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					msgpackets += 1; 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				} else {
					printf("magic number seems off, is 0x%x, %d bytes, %d packets\n",
						   u,pos,rxpackets);
					exit(0); 
				}
				if(ferror(in) || feof(in)) done = true; 
			}
		}
		printf("total %d rxpackets, %d txpackets, %d messages\n", 
			   rxpackets, txpackets, msgpackets); 
		fseek(in,0, SEEK_SET);
		//okay, allocate appropriate data structs: 
		// time (double), analog(i8), channel (i8), 
		// spike_time (double), spikes(i32)
		double* time; 
		mat_uint32_t* mstimer; 
		mat_int8_t* analog;
		mat_int8_t* channel;
		mat_uint32_t* spike_ts; 
		mat_int8_t* spike_ch; 
		mat_int8_t* spike_unit;
		// store timestamp (in samples), rx time (not necessarily accurate) - one per pkt
		// store channel # and sample 
		// store channel & timestamp for spikes.
		// just ignore dropped packets for now.
		time = (double*)malloc(rxpackets * sizeof(double)); 
		  if(!time){ printf("could not allocate time variable."); exit(0);}
		mstimer = (mat_uint32_t*)malloc(rxpackets * sizeof(int) ); 
		 if(!mstimer){ printf("could not allocate mstimer variable."); exit(0);}
		analog = (mat_int8_t*)malloc(rxpackets * 24 ); 
		  if(!analog){ printf("could not allocate analog variable."); exit(0);}
		channel = (mat_int8_t*)malloc(rxpackets * 24 ); 
		  if(!channel){ printf("could not allocate channel variable."); exit(0);}
		
		spike_ts = (mat_uint32_t*)malloc(rxpackets * sizeof(int)*32); 
		  if(!spike_ts){ printf("could not allocate spike_ts variable."); exit(0);}
		spike_ch = (mat_int8_t*)malloc(rxpackets * 32); 
		  if(!spike_ch){ printf("could not allocate spike_ch variable."); exit(0);}
		spike_unit = (mat_int8_t*)malloc(rxpackets * 32); 
		  if(!spike_unit){ printf("could not allocate spike_unit variable."); exit(0);}
		//also need to inspect the messages, to see exactly when the channels changed.
		rxpackets = 0;
		int tp = 0; // packet position (index time, aka timestamp)
		int sp = 0; // spike position (index spike variables)
		char msgs[16][128]; //use this to save messages ; appy them when their echo appears.
		for(int i=0; i<16*128; i++){
			msgs[0][i] = 0; //yes, you can do that in c! 
		}
		int chans[4] = {0,32,64,96}; 
		done = false; 
		while(!done){
			fread((void*)&u,4,1,in);
			if(ferror(in) || feof(in)) done = true; 
			else {
				if(u == 0xdecafbad){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					int npak = (siz-4)/(4+32);
					//first 4 is for dropped packet count
					//second 4 is for 4 byte bridge milisecond counter
					//printf("npak %d siz %d\n",npak,siz); 
					double rxtime = 0.0; 
					unsigned int dropped = 0; 
					fread((void*)&rxtime,8,1,in); //rx time in seconds. 
					fread((void*)&dropped,4,1,in); 
	
					int channels[32]; char match[32]; 
					for(int i=0;i<npak; i++){
						packet p; 
						fread((void*)&p,sizeof(p),1,in);
						if(ferror(in) || feof(in)) done = true; 
						else{
							/*int headecho = ((p.flag) >> 4) & 0xf; 
							//check to see if we can apply the command that was echoed.
							char m = msgs[headecho][0]; 
							if(m >= 'A' && m <= 'A' + 15){
								printf("applying %s\n", msgs[headecho]); 
								msgs[headecho][0] = 0; 
							}*/
							time[tp] = rxtime + (double)i * 6.0 / 31250.0; 
							mstimer[tp] = p.ms; 
							for(int j=0; j<6; j++){
								for(int k=0; k<4; k++){
									char samp = p.data[j*4+k]; 
									analog[tp*24+j*4+k] = samp; 
									channel[tp*24+j*4+k] = chans[k]; 
								}
							}
							decodePacket(&p, channels, match);
							for(int j=0; j<32; j++){
								if(match[j]){
									spike_ts[sp] = tp; 
									spike_ch[sp] = channel[j]; 
									spike_unit[sp] = match[j]; 
									sp++;
								}
							}
							tp++; 
						}
					}
					pos += 16+siz; 
				} else if( u == 0xc0edfad0){
					//ignore tx packets (for now?)
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					txpackets += (siz)/32; 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				} else if(u == 0xb00a5c11){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					double rxtime = 0.0; 
					fread((void*)&rxtime,8,1,in);
					char buf[128]; 
					fread((void*)buf,siz,1,in); 
					buf[siz] = 0; 
					//really need to wait for the echo here.
					//bummish.
					printf("message: %s\n", buf); 
					//first char: A-P (0-15, corresponds to echo); second space
					char* b = buf; b+=2; 
					if(strncmp(b, "chan", 4) == 0){
						int ii = b[5] - 'A'; 
						if(ii >= 0 && ii < 4){
							b += 7;
							chans[ii] = atoi(b); 
							//printf(" chan %d changed to %d\n", ii, chans[ii]); 
						}
					}
					pos += 16+siz; 
				} else {
					printf("magic number seems off, is 0x%x, %d bytes\n",
						u,pos);
					exit(0); 
				}
			}
		}
		printf("finished reading in data file, now writing matlab file.\n"); 
		
		matvar_t *matvar;
		matvar = Mat_VarCreate("time",MAT_C_DOUBLE,MAT_T_DOUBLE,
							   1,&tp,time,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(time); //I wish I had more. 
		
		matvar = Mat_VarCreate("mstimer",MAT_C_UINT32,MAT_T_UINT32,
							   1,&tp,mstimer,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(mstimer); 
		
		int m = tp * 24; 
		matvar = Mat_VarCreate("analog",MAT_C_INT8,MAT_T_INT8,
							   1,&m,analog,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(analog); 
		
		matvar = Mat_VarCreate("channel",MAT_C_INT8,MAT_T_INT8,
							   1,&m,channel,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(channel); 
		
		matvar = Mat_VarCreate("spike_ts",MAT_C_UINT32,MAT_T_UINT32,
							   1,&sp,spike_ts,0); 
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(spike_ts); 
		
		matvar = Mat_VarCreate("spike_ch",MAT_C_UINT32,MAT_T_UINT32,
							   1,&sp,spike_ch,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(spike_ch); 
		
		matvar = Mat_VarCreate("spike_unit",MAT_C_UINT32,MAT_T_UINT32,
							   1,&sp,spike_unit,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(spike_unit); 
		
		Mat_Close(mat); 
		fclose(in); 
	}
}
示例#29
0
KeyFinder::AudioData* LibAvDecoder::decodeFile(const QString& filePath, const int maxDuration){

  QMutexLocker codecMutexLocker(&codecMutex); // mutex the preparatory section of this method

  AVCodec *codec = NULL;
  AVFormatContext *fCtx = NULL;
  AVCodecContext *cCtx = NULL;
  AVDictionary* dict = NULL;

  // convert filepath
#ifdef Q_OS_WIN
  const wchar_t* filePathWc = reinterpret_cast<const wchar_t*>(filePath.constData());
  const char* filePathCh = utf16_to_utf8(filePathWc);
#else
  QByteArray encodedPath = QFile::encodeName(filePath);
  const char* filePathCh = encodedPath;
#endif

  // open file
  int openInputResult = avformat_open_input(&fCtx, filePathCh, NULL, NULL);
  if(openInputResult != 0){
    throw KeyFinder::Exception(GuiStrings::getInstance()->libavCouldNotOpenFile(openInputResult).toLocal8Bit().constData());
  }

  if(avformat_find_stream_info(fCtx, NULL) < 0){
    av_close_input_file(fCtx);
    throw KeyFinder::Exception(GuiStrings::getInstance()->libavCouldNotFindStreamInformation().toLocal8Bit().constData());
  }
  int audioStream = -1;
  for(int i=0; i<(signed)fCtx->nb_streams; i++){
    if(fCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO){
      audioStream = i;
      break;
    }
  }
  if(audioStream == -1){
    av_close_input_file(fCtx);
    throw KeyFinder::Exception(GuiStrings::getInstance()->libavCouldNotFindAudioStream().toLocal8Bit().constData());
  }

  // Determine duration
  int durationSeconds = fCtx->duration / AV_TIME_BASE;
  int durationMinutes = durationSeconds / 60;
  // First condition is a hack for bizarre overestimation of some MP3s
  if(durationMinutes < 720 && durationSeconds > maxDuration * 60){
    av_close_input_file(fCtx);
    throw KeyFinder::Exception(GuiStrings::getInstance()->durationExceedsPreference(durationMinutes, durationSeconds % 60, maxDuration).toLocal8Bit().constData());
  }

  // Determine stream codec
  cCtx = fCtx->streams[audioStream]->codec;
  codec = avcodec_find_decoder(cCtx->codec_id);
  if(codec == NULL){
    av_close_input_file(fCtx);
    throw KeyFinder::Exception(GuiStrings::getInstance()->libavUnsupportedCodec().toLocal8Bit().constData());
  }

  // Open codec
  int codecOpenResult = avcodec_open2(cCtx, codec, &dict);
  if(codecOpenResult < 0){
    av_close_input_file(fCtx);
    throw KeyFinder::Exception(GuiStrings::getInstance()->libavCouldNotOpenCodec(codec->long_name, codecOpenResult).toLocal8Bit().constData());
  }

  ReSampleContext* rsCtx = av_audio_resample_init(
        cCtx->channels, cCtx->channels,
        cCtx->sample_rate, cCtx->sample_rate,
        AV_SAMPLE_FMT_S16, cCtx->sample_fmt,
        0, 0, 0, 0);
  if(rsCtx == NULL){
    avcodec_close(cCtx);
    av_close_input_file(fCtx);
    throw KeyFinder::Exception(GuiStrings::getInstance()->libavCouldNotCreateResampleContext().toLocal8Bit().constData());
  }

  qDebug("Decoding %s (%s, %d)", filePathCh, av_get_sample_fmt_name(cCtx->sample_fmt), cCtx->sample_rate);

  codecMutexLocker.unlock();

  // Prep buffer
  KeyFinder::AudioData *audio = new KeyFinder::AudioData();
  audio->setFrameRate(cCtx->sample_rate);
  audio->setChannels(cCtx->channels);
  // Decode stream
  AVPacket avpkt;
  int badPacketCount = 0;
  int badPacketThreshold = 100;
  while(true){
    av_init_packet(&avpkt);
    if(av_read_frame(fCtx, &avpkt) < 0)
      break;
    if(avpkt.stream_index == audioStream){
      try{
        int result = decodePacket(cCtx, rsCtx, &avpkt, audio);
        if(result != 0){
          if(badPacketCount < badPacketThreshold){
            badPacketCount++;
          }else{
            avcodec_close(cCtx);
            av_close_input_file(fCtx);
            throw KeyFinder::Exception(GuiStrings::getInstance()->libavTooManyBadPackets(badPacketThreshold).toLocal8Bit().constData());
          }
        }
      }catch(KeyFinder::Exception& e){
        throw e;
      }
    }
    av_free_packet(&avpkt);
  }

  codecMutexLocker.relock();
  audio_resample_close(rsCtx);
  int codecCloseResult = avcodec_close(cCtx);
  if(codecCloseResult < 0){
    qCritical("Error closing audio codec: %s (%d)", codec->long_name, codecCloseResult);
  }
  codecMutexLocker.unlock();

  av_close_input_file(fCtx);
  return audio;
}
示例#30
0
void vrpn_DreamCheeky::on_data_received(size_t bytes, vrpn_uint8 *buffer)
{
  decodePacket(bytes, buffer);
}