コード例 #1
0
ファイル: xml.cpp プロジェクト: queile/peca-android-upnp
// ----------------------------------
void XML::writeHTML(Stream &out)
{
	if (!root)
    	throw StreamException("No XML root");

    root->write(out,1);
}
コード例 #2
0
ファイル: file_stream.cpp プロジェクト: snowwlex/university
size_t FileStream::read(char* ptr, size_t count) {
	if (myOpenMode != READ) {
		throw(StreamException(
				"Trying to read a file, that opened not for reading"));
	}
	size_t result = fread(ptr, sizeof( char), count, myFile);
	return result;
}
コード例 #3
0
ファイル: usocket.cpp プロジェクト: crosslink/peercast
// --------------------------------------------------
int UClientSocket::numPending() 
{
	size_t len;

    if (ioctl( sockNum, FIONREAD, (char *)&len ) < 0)
		throw StreamException("numPending");

	return (int)len;
}
コード例 #4
0
ファイル: xml.cpp プロジェクト: amate/PeerCastPX
// ----------------------------------
void XML::write(Stream &out)
{
	if (!root)
    	throw StreamException("No XML root");

	out.writeLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
    root->write(out,1);

}
コード例 #5
0
ファイル: xml.cpp プロジェクト: amate/PeerCastPX
// ----------------------------------
void XML::writeCompact(Stream &out)
{
	if (!root)
    	throw StreamException("No XML root");

	out.writeLine("<?xml ?>");
    root->write(out,1);

}
コード例 #6
0
ファイル: pcp.cpp プロジェクト: PyYoshi/PeerCastIM-Mod
// ------------------------------------------
void PCPStream::readVersion(Stream & in) {
    int len = in.readInt();

    if (len != 4)
        throw StreamException("Invalid PCP");

    int ver = in.readInt();

    LOG_DEBUG("PCP ver: %d", ver);
}
コード例 #7
0
UriInputStream::UriInputStream(FILE *source, Inkscape::URI &uri)
    throw (StreamException): inf(source),
                             uri(uri)
{
    scheme = SCHEME_FILE;
    if (!inf) {
        Glib::ustring err = "UriInputStream passed NULL";
        throw StreamException(err);
    }
    closed = false;
}
コード例 #8
0
ファイル: http.cpp プロジェクト: tempbottle/TestSet
//-----------------------------------------
bool HTTP::checkResponse(int r)
{
	if (readResponse()!=r)
	{
		LOG_ERROR1("Unexpected HTTP: %s",cmdLine);
		throw StreamException("Unexpected HTTP response");
		return false;
	}
	
	return true;
}
コード例 #9
0
/**
 * Temporary kludge
 */
UriOutputStream::UriOutputStream(FILE* fp, Inkscape::URI &destination)
                    throw (StreamException): closed(false),
                                             ownsFile(false),
                                             outf(fp),
                                             uri(destination),
                                             scheme(SCHEME_FILE)
{
    if (!outf) {
        Glib::ustring err = "UriOutputStream given null file ";
        throw StreamException(err);
    }
}
コード例 #10
0
ファイル: default_stream.cpp プロジェクト: elemel/mortified
 std::auto_ptr<Stream>
     createStreamFromFile(const char *file, const char *mode)
 {
     SDL_RWops *rwops = SDL_RWFromFile(file, mode);
     if (rwops == 0) {
         std::stringstream what;
         what << "Failed to open file \"" << file << "\": "
              << SDL_GetError();
         throw StreamException(what.str().c_str());
     }
     return std::auto_ptr<Stream>(new DefaultStream(rwops));
 }
コード例 #11
0
ファイル: ogg.cpp プロジェクト: PyYoshi/PeerCastIM-Mod
// -----------------------------------
void OggSubStream::readHeader(Channel * ch, OggPage & ogg) {
    if ((pack.bodyLen + ogg.bodyLen) >= OggPacket::MAX_BODYLEN)
        throw StreamException("OGG packet too big");

    if (ch->headPack.len + (ogg.bodyLen + ogg.headLen) >= ChanMeta::MAX_DATALEN)
        throw StreamException("OGG packet too big for headMeta");

// copy complete packet into head packet
    memcpy(&ch->headPack.data[ch->headPack.len], ogg.data, ogg.headLen + ogg.bodyLen);
    ch->headPack.len += ogg.headLen + ogg.bodyLen;

    // add body to packet
    memcpy(&pack.body[pack.bodyLen], &ogg.data[ogg.headLen], ogg.bodyLen);
    pack.bodyLen += ogg.bodyLen;

    pack.addLacing(ogg);

    if (pack.numPackets >= maxHeaders)
        procHeaders(ch);

}
コード例 #12
0
ファイル: stream.cpp プロジェクト: rzr/peercast
// -------------------------------------
int FileStream::read(void *ptr, int len)
{
	if (!file)
		return 0;
	if (feof(file))
    	throw StreamException("End of file");

	int r = (int)fread(ptr,1,len,file);

	updateTotals(r, 0);
    return r;
}
コード例 #13
0
ファイル: Streaming.cpp プロジェクト: texwiller204/FtsEngine
	Stream::Stream(const std::string& filename, StreamMode mode)
		: fileStream(), buffer(), streamMode(mode), position(0)
	{
		if (streamMode == SmMemory)
			return;
		std::fstream::openmode openMode = std::fstream::binary;
		if (streamMode == SmRead)
			openMode |= std::fstream::in;
		else
			openMode |= std::fstream::out;
		fileStream.open(filename.c_str(), openMode);
		if (!fileStream)
			throw StreamException("Cannot open file for streaming!");
	}
コード例 #14
0
ファイル: parser.cpp プロジェクト: josekleber/captura
void Parser::setBuffer(string arqName, vector<vector<vector<uint8_t>>> value,
                       int nbSamplesIn, int sampleFormatIn, int sampleRateIn,
                       uint64_t channelLayoutIn, int nbChannelsIn)
{
    int error;

    this->fileName = arqName;
    this->bufFrames = value;

    this->nbSamplesIn = nbSamplesIn;
    this->sampleFormatIn = sampleFormatIn;
    this->sampleRateIn = sampleRateIn;
    this->channelLayoutIn = channelLayoutIn;
    this->nbChannelsIn = nbChannelsIn;

    if (swr_ctx)
        swr_free(&swr_ctx);

    InitResampler();

    if (audioFormat == AUDIOFORMAT::arq)
    {
        AVIOContext **io_ctx = &fmt_ctx_out->pb;

        if (*io_ctx)
            avio_close(*io_ctx);

        error = avio_open(io_ctx, fileName.c_str(), AVIO_FLAG_WRITE);
        if (error < 0)
        {
            char error_buffer[255];
            av_strerror(error, error_buffer, sizeof(error_buffer));
            objLog->mr_printf(MR_LOG_ERROR, idRadio, "Error: %s - %s\n", fileName.c_str(), error_buffer);
            throw ConvertException() << errno_code(MIR_ERR_OPEN_OUTPUT_FILE);
        }

av_dump_format(fmt_ctx_out, 0, fileName.c_str(), 1);

        error = avformat_write_header(fmt_ctx_out, NULL);

        if (error < 0)
        {
            char error_buffer[255];
            av_strerror(error, error_buffer, sizeof(error_buffer));
            objLog->mr_printf(MR_LOG_ERROR, idRadio, "Error: %s - %s\n", fileName.c_str(), error_buffer);
            throw StreamException() << errno_code(MIR_ERR_OPEN_STREAM_3);
        }
    }
}
コード例 #15
0
ファイル: MemoryStream.cpp プロジェクト: lxndr/jkit
void MemoryStream::resize(int64_t length)
{
	if (length == 0) {
		if (mData != nullptr) {
			free(mData);
			mData = nullptr;
			mCurrent = nullptr;
		}
	} else {
		mData = (char*) realloc(mData, (size_t) length);
		if (!mData)
			throw StreamException("Out of memory");
	}
	
	mSize = length;
}
コード例 #16
0
ファイル: file_stream.cpp プロジェクト: snowwlex/university
FileStream::FileStream(const char* filename, Stream::OpenMode openMode) {
	myFile = 0;
	myOpenMode = openMode;
	switch (myOpenMode) {
	case READ:
		myFile = fopen(filename, "rb");
		break;
	case WRITE:
		myFile = fopen(filename, "wb");
		break;
	}
	if (myFile == 0) {
		throw StreamException("Cannot open file!");
	}

}
コード例 #17
0
ファイル: RawInputStream.cpp プロジェクト: coredumped/X-VR2
	bool RawInputStream::ready(int timeout){
		int r;
		bool ret = false;
		struct pollfd d;
		d.fd = fd();
		d.events = POLLIN | POLLPRI;
		errno = 0;
		r = poll(&d, 1, timeout);
		if(r == -1 && !(errno == EAGAIN || errno == EINTR)){
			throw StreamException(errno);
		}
		else if(r > 0){
			if(d.revents & POLLIN == POLLIN || d.revents & POLLPRI == POLLPRI){
				ret = true;
			}
		}
		return ret;
	}
コード例 #18
0
ファイル: xml.cpp プロジェクト: amate/PeerCastPX
// ----------------------------------
int XML::Node::getBinaryContent(void *ptr, int size)
{
	char *in = contData;
    char *out = (char *)ptr;

    int i=0;
    while (*in)
    {
    	if (isWhiteSpace(*in))
        {
        	in++;
        }else
        {
        	if (i >= size)
            	throw StreamException("Too much binary data");
	    	out[i++] = nibsToByte(in[0],in[1]);
	        in+=2;
        }
    }
    return i;
}
コード例 #19
0
ファイル: ogg.cpp プロジェクト: queile/peca-android-upnp
// -----------------------------------
void OggVorbisSubStream::procHeaders(Channel *ch)
{
	unsigned int packPtr=0;

	for(int i=0; i<pack.numPackets; i++)
	{
		MemoryStream vin(&pack.body[packPtr],pack.packetSizes[i]);

		packPtr += pack.packetSizes[i];

		char id[8];

		vin.read(id,7);
		id[7]=0;

		switch (id[0])
		{
			case 1:	// ident
				LOG_CHANNEL("OGG Vorbis Header: Ident (%d bytes)",vin.len);
				readIdent(vin,ch->info);
				break;
			case 3: // comment
				{
					LOG_CHANNEL("OGG Vorbis Header: Comment (%d bytes)",vin.len);
					ChanInfo newInfo = ch->info;
					readComment(vin,newInfo);
					ch->updateInfo(newInfo);
				}
				break;
			case 5: // setup
				LOG_CHANNEL("OGG Vorbis Header: Setup (%d bytes)",vin.len);
				//readSetup(vin);
				break;
			default:
				throw StreamException("Unknown Vorbis packet header type");
				break;
		}
	}

}
コード例 #20
0
UriInputStream::UriInputStream(Inkscape::URI &source)
                    throw (StreamException): uri(source)
{
    //get information from uri
    char const *schemestr = uri.getScheme();
    scheme = SCHEME_FILE;
    if (!schemestr || strncmp("file", schemestr, 4)==0)
        scheme = SCHEME_FILE;
    else if (strncmp("data", schemestr, 4)==0)
        scheme = SCHEME_DATA;
    //printf("in schemestr:'%s' scheme:'%d'\n", schemestr, scheme);
    gchar *cpath = NULL;

    switch (scheme) {

        case SCHEME_FILE:
            cpath = uri.toNativeFilename();
            //printf("in cpath:'%s'\n", cpath);
            inf = fopen_utf8name(cpath, FILE_READ);
            //inf = fopen(cpath, "rb");
            g_free(cpath);
            if (!inf) {
                Glib::ustring err = "UriInputStream cannot open file ";
                err += cpath;
                throw StreamException(err);
            }
        break;

        case SCHEME_DATA:
            data        = (unsigned char *) uri.getPath();
            //printf("in data:'%s'\n", data);
            dataPos     = 0;
            dataLen     = strlen((const char *)data);
        break;

    }
    closed = false;
}
コード例 #21
0
UriOutputStream::UriOutputStream(Inkscape::URI &destination)
                    throw (StreamException): closed(false),
                                             ownsFile(true),
                                             outf(NULL),
                                             uri(destination),
                                             scheme(SCHEME_FILE)
{
    //get information from uri
    char const *schemestr = uri.getScheme();
    if (!schemestr || strncmp("file", schemestr, 4)==0)
        scheme = SCHEME_FILE;
    else if (strncmp("data", schemestr, 4)==0)
        scheme = SCHEME_DATA;
    //printf("out schemestr:'%s' scheme:'%d'\n", schemestr, scheme);
    gchar *cpath = NULL;

    switch (scheme) {

        case SCHEME_FILE:
            cpath = uri.toNativeFilename();
            //printf("out path:'%s'\n", cpath);
            outf = fopen_utf8name(cpath, FILE_WRITE);
            //outf = fopen(cpath, "wb");
            g_free(cpath);
            if (!outf) {
                Glib::ustring err = "UriOutputStream cannot open file ";
                err += cpath;
                throw StreamException(err);
            }
        break;

        case SCHEME_DATA:
            data        = "data:";
        break;

    }//switch
}
コード例 #22
0
ファイル: PecaCore.cpp プロジェクト: amate/PeerCastPX
CFileStream::CFileStream(LPCSTR strFile, LPCSTR mode)
{
	fp = fopen(strFile, mode);
	if (fp == NULL)
		throw StreamException("ファイルのオープンに失敗");
}
コード例 #23
0
ファイル: xml.cpp プロジェクト: amate/PeerCastPX
// ----------------------------------
void XML::read(Stream &in)
{
	const int BUFFER_LEN = 100*1024;
	static char buf[BUFFER_LEN];

    Node *currNode=NULL;
    int tp=0;

    while (!in.eof())
    {
    	char c = in.readChar();

        if (c == '<')
        {
        	if (tp && currNode)	// check for content
            {
            	buf[tp] = 0;
            	currNode->setContent(buf);
            }
            tp = 0;

        	// read to next '>'
            while (!in.eof())
            {
            	c = in.readChar();
                if (c == '>')
                	break;

	        	if (tp >= BUFFER_LEN)
    	        	throw StreamException("Tag too long");

                buf[tp++] = c;
            }
            buf[tp]=0;

            if (buf[0] == '!')					// comment
            {
             	// do nothing
            }else if (buf[0] == '?')			// doc type
            {
            	if (strnicmp(&buf[1],"xml ",4))
                	throw StreamException("Not XML document");
            }else if (buf[0] == '/')			// end tag
            {
            	if (!currNode)
                	throw StreamException("Unexpected end tag");
            	currNode = currNode->parent;
            }else 	// new tag
            {
	            //LOG("tag: %s",buf);

            	bool singleTag = false;

                if (buf[tp-1] == '/')		   	// check for single tag
                {
                	singleTag = true;
                    buf[tp-1] = 0;
                }

				// only add valid tags
				if (strlen(buf))
				{
					Node *n = new Node(buf);

					if (currNode)
                		currNode->add(n);
					else
                		setRoot(n);

					if (!singleTag)
						currNode = n;
				}
            }

            tp = 0;
        } else {

        	if (tp >= BUFFER_LEN)
            	throw StreamException("Content too big");

        	buf[tp++] = c;

        }
    }
}
コード例 #24
0
ファイル: xml.cpp プロジェクト: amate/PeerCastPX
// ----------------------------------
void XML::Node::setAttributes(const char *n)
{
    char c;

	attrData = strdup(n);

    // count maximum amount of attributes
    int maxAttr = 1;		// 1 for tag name
    bool inQ = false;
    int i=0;
    while ((c=attrData[i++])!=0)
    {
    	if (c=='\"')
			inQ ^= true;

		if (!inQ)
			if (c=='=')
				maxAttr++;
    }


    attr = new Attribute[maxAttr];

    attr[0].namePos = 0;
    attr[0].valuePos = 0;

    numAttr=1;

    i=0;

    // skip until whitespace
    while (c=attrData[i++])
    	if (isWhiteSpace(c))
        	break;

    if (!c) return;	// no values

    attrData[i-1]=0;


    while ((c=attrData[i])!=0)
    {
    	if (!isWhiteSpace(c))
        {
			if (numAttr>=maxAttr)
				throw StreamException("Too many attributes");

			// get start of tag name
        	attr[numAttr].namePos = i;


			// skip whitespaces until next '='
			// terminate name on next whitespace or '='
            while (attrData[i])
			{
				c = attrData[i++];

				if ((c == '=') || isWhiteSpace(c))
				{
					attrData[i-1] = 0;	// null term. name
					if (c == '=')
                		break;
				}
			}

			// skip whitespaces
            while (attrData[i])
			{
	            if (isWhiteSpace(attrData[i]))
					i++;
				else
					break;
			}

			// check for valid start of attribute value - '"'
			if (attrData[i++] != '\"')
            	throw StreamException("Bad tag value");

            attr[numAttr++].valuePos = i;

			// terminate attribute value at next '"'

            while (attrData[i])
				if (attrData[i++] == '\"')
                	break;

			attrData[i-1] = 0;	// null term. value


        }else{
	        i++;
    	}
    }
}
コード例 #25
0
ファイル: mms.cpp プロジェクト: PyYoshi/PeerCastIM-Mod
// ------------------------------------------
int MMSStream::readPacket(Stream & in, Channel * ch) {
    {
        ASFChunk chunk;

        chunk.read(in);

        switch (chunk.type) {
            case 0x4824:        // asf header
            {
                MemoryStream mem(ch->headPack.data, sizeof(ch->headPack.data));

                chunk.write(mem);


                MemoryStream asfm(chunk.data, chunk.dataLen);
                ASFObject asfHead;
                asfHead.readHead(asfm);

                ASFInfo asf = parseASFHeader(asfm);
                LOG_DEBUG("ASF Info: pnum=%d, psize=%d, br=%d", asf.numPackets, asf.packetSize, asf.bitrate);
                for (int i = 0; i < ASFInfo::MAX_STREAMS; i++) {
                    ASFStream *s = &asf.streams[i];
                    if (s->id)
                        LOG_DEBUG("ASF Stream %d : %s, br=%d", s->id, s->getTypeName(), s->bitrate);
                }

                ch->info.bitrate = asf.bitrate / 1000;

                ch->headPack.type = ChanPacket::T_HEAD;
                ch->headPack.len = mem.pos;
                ch->headPack.pos = ch->streamPos;
                ch->newPacket(ch->headPack);

                ch->streamPos += ch->headPack.len;

                break;
            }
            case 0x4424:        // asf data
            {

                ChanPacket pack;

                MemoryStream mem(pack.data, sizeof(pack.data));

                chunk.write(mem);

                pack.type = ChanPacket::T_DATA;
                pack.len = mem.pos;
                pack.pos = ch->streamPos;

                ch->newPacket(pack);
                ch->streamPos += pack.len;

                break;
            }
            default:
                throw StreamException("Unknown ASF chunk");

        }

    }
    return 0;
}
コード例 #26
0
ファイル: mms.cpp プロジェクト: PyYoshi/PeerCastIM-Mod
// -----------------------------------
ASFInfo parseASFHeader(Stream & in) {
    ASFInfo asf;

    try {
        int numHeaders = in.readLong();

        in.readChar();
        in.readChar();

        LOG_CHANNEL("ASF Headers: %d", numHeaders);
        for (int i = 0; i < numHeaders; i++) {

            ASFObject obj;

            unsigned int l = obj.readHead(in);
            obj.readData(in, l);


            MemoryStream data(obj.data, obj.lenLo);


            switch (obj.type) {
                case ASFObject::T_FILE_PROP: {
                    data.skip(32);

                    unsigned int dpLo = data.readLong();
                    unsigned int dpHi = data.readLong();

                    data.skip(24);

                    data.readLong();
                    //data.writeLong(1);	// flags = broadcast, not seekable

                    int min = data.readLong();
                    int max = data.readLong();
                    int br = data.readLong();

                    if (min != max)
                        throw StreamException("ASF packetsizes (min/max) must match");

                    asf.packetSize = max;
                    asf.bitrate = br;
                    asf.numPackets = dpLo;
                    break;
                }
                case ASFObject::T_STREAM_BITRATE: {
                    int cnt = data.readShort();
                    for (int i = 0; i < cnt; i++) {
                        unsigned int id = data.readShort();
                        int bitrate = data.readLong();
                        if (id < ASFInfo::MAX_STREAMS)
                            asf.streams[id].bitrate = bitrate;
                    }
                    break;
                }
                case ASFObject::T_STREAM_PROP: {
                    ASFStream s;
                    s.read(data);
                    asf.streams[s.id].id = s.id;
                    asf.streams[s.id].type = s.type;
                    break;
                }
            }

        }
    } catch (StreamException &e) {
        LOG_ERROR("ASF: %s", e.msg);
    }

    return asf;
}
コード例 #27
0
ファイル: pcp.cpp プロジェクト: PyYoshi/PeerCastIM-Mod
// ------------------------------------------
int PCPStream::procAtom(AtomStream &atom, ID4 id, int numc, int dlen, BroadcastState &bcs) {
    int r = 0;
    ChanHit hit;
    int rBan = 0;

    if (id == PCP_CHAN) {
        readChanAtoms(atom, numc, bcs);
    } else if (id == PCP_ROOT) {
        if (servMgr->isRoot)
            throw StreamException("Unauthorized root message");
        else
            readRootAtoms(atom, numc, bcs);

    } else if (id == PCP_HOST) {
        readHostAtoms(atom, numc, bcs, hit);
        Channel *ch = chanMgr->findChannelByID(hit.chanID);
        if (ch && (ch->isBroadcasting() || servMgr->vpDebug)) {
            if (servMgr->autoPort0Kick && (hit.numHops == 1) && (hit.firewalled || (!hit.relay && !hit.numRelays))) {
                char tmp[32];
                hit.host.IPtoStr(tmp);
                LOG_DEBUG("host that can't relay is disconnect: %s", tmp);
                rBan = PCP_ERROR_BANNED;
            }
            if (servMgr->allowOnlyVP && (hit.numHops == 1) && !hit.version_vp) {
                char tmp[32];
                hit.host.IPtoStr(tmp);
                LOG_DEBUG("host that is not VP is disconnect: %s", tmp);
                rBan = PCP_ERROR_BANNED;
            }
        }

    } else if ((id == PCP_MESG_ASCII) || (id == PCP_MESG))        // PCP_MESG_ASCII to be depreciated
    {
        String msg;
        atom.readString(msg.data, sizeof(msg.data), dlen);
        LOG_DEBUG("PCP got text: %s", msg.cstr());
    } else if (id == PCP_BCST) {
        r = readBroadcastAtoms(atom, numc, bcs);
    } else if (id == PCP_HELO) {
        atom.skip(numc, dlen);
        atom.writeParent(PCP_OLEH, 1);
        atom.writeBytes(PCP_HELO_SESSIONID, servMgr->sessionID.id, 16);
    } else if (id == PCP_PUSH) {

        readPushAtoms(atom, numc, bcs);
    } else if (id == PCP_OK) {
        atom.readInt();

    } else if (id == PCP_QUIT) {
        r = atom.readInt();
        if (!r)
            r = PCP_ERROR_QUIT;

    } else if (id == PCP_ATOM) {
        for (int i = 0; i < numc; i++) {
            int nc, nd;
            ID4 aid = atom.read(nc, nd);
            int ar = procAtom(atom, aid, nc, nd, bcs);
            if (ar)
                r = ar;
        }

    } else {
        LOG_CHANNEL("PCP skip: %s", id.getString().str());
        atom.skip(numc, dlen);
    }

    if (!r)
        r = rBan;

    return r;

}
コード例 #28
0
ファイル: pcp.cpp プロジェクト: PyYoshi/PeerCastIM-Mod
// ------------------------------------------
int PCPStream::readPacket(Stream & in, BroadcastState & bcs) {
    int error = PCP_ERROR_GENERAL;
    try {
        AtomStream atom(in);

        ChanPacket pack;
        MemoryStream mem(pack.data, sizeof(pack.data));
        AtomStream patom(mem);


        // send outward packets
        error = PCP_ERROR_WRITE;
        if (outData.numPending()) {
            outData.readPacket(pack);
            pack.writeRaw(in);
        }
        error = PCP_ERROR_GENERAL;

        if (outData.willSkip()) {
            error = PCP_ERROR_WRITE + PCP_ERROR_SKIP;
            throw StreamException("Send too slow");
        }


        error = PCP_ERROR_READ;
        // poll for new downward packet
        if (in.readReady()) {
            int numc, numd;
            ID4 id;

            id = atom.read(numc, numd);

            mem.rewind();
            pack.len = patom.writeAtoms(id, in, numc, numd);
            pack.type = ChanPacket::T_PCP;

            //inData.writePacket(pack);
            //}
            error = PCP_ERROR_GENERAL;

            // process downward packets
            //if (inData.numPending())
            //{
            //inData.readPacket(pack);

            mem.rewind();

            //int numc,numd;
            id = patom.read(numc, numd);

            error = PCPStream::procAtom(patom, id, numc, numd, bcs);

            if (error) {
                throw StreamException("PCP exception");
            }
        }

        error = 0;

    } catch (StreamException &e) {
        LOG_ERROR("PCP readPacket: %s (%d)", e.msg, error);
    }

    return error;
}
コード例 #29
0
ファイル: wme_c.cpp プロジェクト: supertanglang/liveshow
void wme_c::receive(char* ip,WORD port)
{
	Buffer* lpBuf = m_buf;
	SOCKET skt = sys->createSocket(SOCK_STREAM);
	sockaddr_in clientService; 
	clientService.sin_family = AF_INET;
	clientService.sin_addr.s_addr = inet_addr( ip);
	clientService.sin_port = htons( port);
	DWORD e;

	int iReqNum = 1;	//请求次数
	bool bCnnected = false;

	const int BUF_SIZE = 64*1024 +12 ;// 8192; //64KB
	char buf[BUF_SIZE];
	int iGet = 0;
	int iPos = 0;
	bool bInited = false;
	while (true)
	{
		
		if (!bCnnected) //not connected
		{
			if(connect(skt,(SOCKADDR*) &clientService,sizeof(clientService))==SOCKET_ERROR)
			{		
				e=GetLastError();
				throw StreamException("wme_c::getHeader.connect ",e);
				//return NULL;
			}	
			MemoryStream *stream  =new MemoryStream(2048);
			if (iReqNum % 2 != 0) //第一次请求
			{
				memset(stream->buf,0,stream->len);
				stream->write(HTTP_REQ_CMD, static_cast<int>( strlen(HTTP_REQ_CMD)  ));
				stream->write(HTTP_REQ_AGENT,static_cast<int>(strlen(HTTP_REQ_AGENT) ) );
				stream->write(HTTP_REQ_PRAGMA,static_cast<int>(strlen(HTTP_REQ_PRAGMA))  );
				stream->writeChar('\r');
				stream->writeChar('\n');
			} 
			else //第二次请求
			{
				
				memset(stream->buf,0,stream->len);
				stream->write(HTTP_REQ_CMD, static_cast<int>(strlen(HTTP_REQ_CMD)  ));
				stream->write(HTTP_REQ_AGENT,static_cast<int>(strlen(HTTP_REQ_AGENT) ) );
				stream->write(HTTP_REQ_PRAGMA2,static_cast<int>(strlen(HTTP_REQ_PRAGMA2))  ); //第二次请求
				stream->writeChar('\r');
				stream->writeChar('\n');
			}
			if(send(skt,stream->buf,static_cast<int>(strlen(stream->buf)),0)==SOCKET_ERROR)
			{
				e = GetLastError();

				return ;
			}
			delete stream;
		} 
		
		Sleep(10);
lblRecv:
		if (iPos > 0)
		{
			memcpy(buf,buf+iPos,iGet - iPos);
			iGet -= iPos;
			iPos = 0;
		}
		int iRecv = recv(skt,buf+iGet,BUF_SIZE - iGet,0);
		if (0 == iRecv)
		{
			//net workerror
		}
		iGet += iRecv;

		char* HTTP = "HTTP";
		
		char* RNRN = "\r\n\r\n";
		if (memfind(buf,iGet,HTTP,4) != NULL)
		{
			iPos = ( memfind(buf,iGet,RNRN,4)-buf) + 4;
		}
		AsfChunkHeader chkHeader;
		memcpy(&chkHeader,buf+iPos,sizeof(chkHeader));
		if (chkHeader.wConfirmLen != chkHeader.wLen)
		{
			//TODO:error
		}
		if (chkHeader.wLen + 4> iGet - iPos )
		{
			goto lblRecv;
		}

		switch(chkHeader.wCMD)
		{
		case 0x4824://"$H"
			{
				if (!bInited)
				{
					asfHeader *objHeader = new asfHeader(buf+iPos + 4 + 8,chkHeader.wLen);
					dwPacketSize = objHeader->getChunkSize();
					dwBitRate = objHeader->getBitRate();
					delete objHeader;
					int size = ( dwBitRate /8 /dwPacketSize)*dwPacketSize;//(349056 /8 /0x5a4) * 0x5a4;
					Segment::setSegmentSize( size);//试验用 1.06M

					lpBuf->m_Header.lpData = new char[chkHeader.wLen - 8];
					memcpy(lpBuf->m_Header.lpData,buf + iPos + 4 + 8 ,chkHeader.wLen -  8);
					lpBuf->m_Header.len = chkHeader.wLen - 8;
					lpBuf->Init(0);
					bInited = true;
				}
				bCnnected =true;
				iPos +=  chkHeader.wLen + 4;
			}
			break;
		case 0xa444://?D
		case 0x4424://$D
			{
				iPos = processData(lpBuf,buf,iPos,iGet);
				if(iPos<0)
				{
					bCnnected = false;
					closesocket(skt);
				}
			}
		    break;
		
		}
		
	}

}
コード例 #30
0
ファイル: wme_c.cpp プロジェクト: supertanglang/liveshow
char* wme_c::getHeader(char* ip,WORD port)
{
	Buffer* lpBuf = m_buf;
	SOCKET skt = sys->createSocket(SOCK_STREAM);
	sockaddr_in clientService; 
	clientService.sin_family = AF_INET;
	clientService.sin_addr.s_addr = inet_addr( ip);
	clientService.sin_port = htons( port);
	DWORD e ;
	if(connect(skt,(SOCKADDR*) &clientService,sizeof(clientService))==SOCKET_ERROR && GetLastError() == WSAEWOULDBLOCK)
	{		
		e=GetLastError();
		throw StreamException("wme_c::getHeader.connect ",e);
		//return NULL;
	}
	MemoryStream *stream  =new MemoryStream(1024);
	memset(stream->buf,0,1024);
	stream->write(HTTP_REQ_CMD, static_cast<int>( strlen(HTTP_REQ_CMD)  ));
	stream->write(HTTP_REQ_AGENT,static_cast<int>(strlen(HTTP_REQ_AGENT) ) );
	stream->write(HTTP_REQ_PRAGMA,static_cast<int>(strlen(HTTP_REQ_PRAGMA))  );
	stream->writeChar('\r');
	stream->writeChar('\n');

	if(send(skt,stream->buf,static_cast<int>(strlen(stream->buf)),0)==SOCKET_ERROR)
	{
		e = GetLastError();
		throw StreamException("wme_c::getHeader.send ",e);
		//return NULL;
	}
	delete stream;
	 //处理接收
	char buf[8192];
	char *lpRet = NULL;//= new char;
	int iGet= 0,iPos = 0;
	WORD len = 0;
	while(true) //读取数据到尾
	{
		int l =0;
		if( (l = recv(skt,buf+iGet,sizeof(buf) - iGet,0)) == SOCKET_ERROR)
		{
			e = GetLastError();
			throw StreamException("wme_c::getHeader.recv ",e);
		}
		if( 0 == l)
		{
			//throw StreamException("wme_c::getHeader.socetclosed ");
			break;
		}
		iGet +=l ;
	}
		
	if(strstr(buf,"OK") !=NULL) // get ok
	{
		char* pLoc = strstr(buf,"\r\n\r\n");
		pLoc +=4;//移动到\r\n\r\n后边,进入实际的包体

		if( 0x24 == pLoc[0]  && 0x48 == pLoc[1]) //header
		{
			
			pLoc += 2;
			memcpy(&len,pLoc,2);
			len -= 8;
			//&len  pLoc[2] < 8 & pLoc[3]; //get length
			lpRet = new char[len];
			pLoc += 10 ;
			memcpy(lpRet,pLoc,len);

			

			//设置Segment::setSegmentSize;
			//memcpy(&dwPacketSize,pLoc + HDR_ASF_PACKET_SIZE,4);
			//memcpy(&dwBitRate,pLoc + HDR_ASF_BITRATE,4);
			asfHeader *objHeader = new asfHeader(pLoc,len);
			dwPacketSize = objHeader->getChunkSize();
			dwBitRate = objHeader->getBitRate();
			delete objHeader;
			int size = ( dwBitRate /8 /dwPacketSize)*dwPacketSize;//(349056 /8 /0x5a4) * 0x5a4;
			Segment::setSegmentSize( size);//试验用 1.06M
			
			lpBuf->m_Header.lpData = lpRet;
			lpBuf->m_Header.len = len;
			lpBuf->Init(0);
		}
		
		
	}
	else
	{
		//error
		return NULL;
	}
		
	
	closesocket(skt);

	return lpRet;
}