Esempio n. 1
0
int init_decoder(void) {
    alac_file *alac;

    frame_size = fmtp[1]; // stereo samples
    sampling_rate = fmtp[11];

    int sample_size = fmtp[3];
    if (sample_size != 16)
        die("only 16-bit samples supported!");

    alac = create_alac(sample_size, 2);
    if (!alac)
        return 1;
    decoder_info = alac;

    alac->setinfo_max_samples_per_frame = frame_size;
    alac->setinfo_7a =      fmtp[2];
    alac->setinfo_sample_size = sample_size;
    alac->setinfo_rice_historymult = fmtp[4];
    alac->setinfo_rice_initialhistory = fmtp[5];
    alac->setinfo_rice_kmodifier = fmtp[6];
    alac->setinfo_7f =      fmtp[7];
    alac->setinfo_80 =      fmtp[8];
    alac->setinfo_82 =      fmtp[9];
    alac->setinfo_86 =      fmtp[10];
    alac->setinfo_8a_rate = fmtp[11];
    allocate_buffers(alac);
    return 0;
}
Esempio n. 2
0
static LPMIDIHDR get_free_output_buffer(PmInternal *midi)
{
    LPMIDIHDR r = NULL;
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    if (!m->buffers) {
        if (allocate_buffers(m, PM_DEFAULT_SYSEX_BUFFER_SIZE, 2)) {
            return NULL;
        }
    }
    /* busy wait until we find a free buffer */
    while (TRUE) {
        int i;
        for (i = 0; i < m->num_buffers; i++) {
            m->next_buffer++;
            if (m->next_buffer >= m->num_buffers) m->next_buffer = 0;
            r = m->buffers[m->next_buffer];
            if ((r->dwFlags & MHDR_PREPARED) == 0) goto found_buffer;
        }
        /* after scanning every buffer and not finding anything, block */
        WaitForSingleObject(m->buffer_signal, INFINITE);
    }
found_buffer:
    r->dwBytesRecorded = 0;
    m->error = midiOutPrepareHeader(m->handle.out, r, sizeof(MIDIHDR));
    return r;
}
Esempio n. 3
0
static int alac_set_info(ALACContext *alac)
{
    const unsigned char *ptr = alac->avctx->extradata;

    ptr += 4; /* size */
    ptr += 4; /* alac */
    ptr += 4; /* 0 ? */

    if(AV_RB32(ptr) >= UINT_MAX/4){
        av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
        return -1;
    }

    /* buffer size / 2 ? */
    alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
    alac->setinfo_7a                    = *ptr++;
    alac->setinfo_sample_size           = *ptr++;
    alac->setinfo_rice_historymult      = *ptr++;
    alac->setinfo_rice_initialhistory   = *ptr++;
    alac->setinfo_rice_kmodifier        = *ptr++;
    /* channels? */
    alac->setinfo_7f                    = *ptr++;
    alac->setinfo_80                    = bytestream_get_be16(&ptr);
    /* max coded frame size */
    alac->setinfo_82                    = bytestream_get_be32(&ptr);
    /* bitrate ? */
    alac->setinfo_86                    = bytestream_get_be32(&ptr);
    /* samplerate */
    alac->setinfo_8a_rate               = bytestream_get_be32(&ptr);

    allocate_buffers(alac);

    return 0;
}
Esempio n. 4
0
static av_cold int flac_decode_init(AVCodecContext *avctx)
{
    enum FLACExtradataFormat format;
    uint8_t *streaminfo;
    int ret;
    FLACContext *s = avctx->priv_data;
    s->avctx = avctx;

    /* for now, the raw FLAC header is allowed to be passed to the decoder as
       frame data instead of extradata. */
    if (!avctx->extradata)
        return 0;

    if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
        return AVERROR_INVALIDDATA;

    /* initialize based on the demuxer-supplied streamdata header */
    ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
    ret = allocate_buffers(s);
    if (ret < 0)
        return ret;
    flac_set_bps(s);
    ff_flacdsp_init(&s->dsp, avctx->sample_fmt, s->bps);
    s->got_streaminfo = 1;

    return 0;
}
Esempio n. 5
0
static av_cold int flac_decode_init(AVCodecContext *avctx)
{
    enum FLACExtradataFormat format;
    uint8_t *streaminfo;
    FLACContext *s = avctx->priv_data;
    s->avctx = avctx;

    /* for now, the raw FLAC header is allowed to be passed to the decoder as
       frame data instead of extradata. */
    if (!avctx->extradata)
        return 0;

    if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
        return -1;

    /* initialize based on the demuxer-supplied streamdata header */
    avpriv_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
    allocate_buffers(s);
    flac_set_bps(s);
    ff_flacdsp_init(&s->dsp, avctx->sample_fmt, s->bps);
    s->got_streaminfo = 1;

    avcodec_get_frame_defaults(&s->frame);
    avctx->coded_frame = &s->frame;

    if (avctx->channels <= FF_ARRAY_ELEMS(flac_channel_layouts))
        avctx->channel_layout = flac_channel_layouts[avctx->channels - 1];

    return 0;
}
Esempio n. 6
0
static av_cold int flac_decode_init(AVCodecContext *avctx)
{
    enum FLACExtradataFormat format;
    uint8_t *streaminfo;
    FLACContext *s = avctx->priv_data;
    s->avctx = avctx;

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    /* for now, the raw FLAC header is allowed to be passed to the decoder as
       frame data instead of extradata. */
    if (!avctx->extradata)
        return 0;

    if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
        return -1;

    /* initialize based on the demuxer-supplied streamdata header */
    ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
    if (s->bps > 16)
        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
    else
        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
    allocate_buffers(s);
    s->got_streaminfo = 1;

    return 0;
}
Esempio n. 7
0
void renderer_cool::reshape_graphics()
{
    float tsx = (float)size_x / gps->dimx, tsy = (float)size_y / gps->dimy;

    int32_t w = gps->dimx, h = gps->dimy;

    int cx = *df::global::window_x + gdimx / 2;
    int cy = *df::global::window_y + gdimy / 2;

    df::viewscreen *ws = Gui::getCurViewscreen();
    if (df::viewscreen_dwarfmodest::_identity.is_direct_instance(ws))
    {
        gsize_x = (size_x - tsx * (gmenu_w + 1 + 1));
        gsize_y = (size_y - tsy * 2);
        goff_x = off_x + roundf(tsx);
        goff_y = off_y + roundf(tsy);        
    }
    else //Adv. mode
    {
        *out2 << "reshape_graphics" << std::endl;
        gsize_x = size_x;
        gsize_y = size_y;
        goff_x = off_x;
        goff_y = goff_y_gl = off_y;
    }

    float dimx = std::min(gsize_x / gdispx, 256.0f);
    float dimy = std::min(gsize_y / gdispy, 256.0f);
    gdimx = ceilf(dimx);
    gdimy = ceilf(dimy);
    gdimxfull = floorf(dimx);
    gdimyfull = floorf(dimy);

    if (df::viewscreen_dwarfmodest::_identity.is_direct_instance(ws))
        goff_y_gl = goff_y - (gdimy == gdimyfull ? 0 : roundf(gdispy - (gsize_y - gdispy * gdimyfull)));                

    *df::global::window_x = std::max(0, cx - gdimx / 2);
    *df::global::window_y = std::max(0, cy - gdimy / 2);

    int tiles = gdimx * gdimy;

    // Recreate tile buffers
    allocate_buffers(tiles);

    // Recreate OpenGL buffers
    gvertexes = (GLfloat*)realloc(gvertexes, sizeof(GLfloat) * tiles * 2 * 6);
    gfg = (GLfloat*)realloc(gfg, sizeof(GLfloat) * tiles * 4 * 6);
    gbg = (GLfloat*)realloc(gbg, sizeof(GLfloat) * tiles * 4 * 6);
    gtex = (GLfloat*)realloc(gtex, sizeof(GLfloat) * tiles * 2 * 6);

    // Initialise vertex coords
    int tile = 0;   
    for (GLfloat x = 0; x < gdimx; x++)
        for (GLfloat y = 0; y < gdimy; y++, tile++)
            write_tile_vertexes(x, y, gvertexes + 6 * 2 * tile);

    needs_full_update = true;
}
Esempio n. 8
0
static int init_thread_copy(AVCodecContext *avctx)
{
    FLACContext *s = avctx->priv_data;
    s->decoded_buffer = NULL;
    s->decoded_buffer_size = 0;
    if (s->max_blocksize)
        return allocate_buffers(s);
    return 0;
}
Esempio n. 9
0
void
fixed_gap_arena_init(FixedGapArena *arena, memi count)
{
    // TODO: Buffer pool.
    vector_init(&arena->buffers);
    allocate_buffers(arena, 0, 1);

    arena->size = 0;
}
Esempio n. 10
0
void alac_set_info(alac_file *alac, char *inputbuffer)
{
  char *ptr = inputbuffer;
  ptr += 4; /* size */
  ptr += 4; /* frma */
  ptr += 4; /* alac */
  ptr += 4; /* size */
  ptr += 4; /* alac */

  ptr += 4; /* 0 ? */

  alac->setinfo_max_samples_per_frame = *(uint32_t*)ptr; /* buffer size / 2 ? */
  if (!host_bigendian)
      _Swap32(alac->setinfo_max_samples_per_frame);
  ptr += 4;
  alac->setinfo_7a = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_sample_size = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_rice_historymult = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_rice_initialhistory = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_rice_kmodifier = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_7f = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_80 = *(uint16_t*)ptr;
  if (!host_bigendian)
      _Swap16(alac->setinfo_80);
  ptr += 2;
  alac->setinfo_82 = *(uint32_t*)ptr;
  if (!host_bigendian)
      _Swap32(alac->setinfo_82);
  ptr += 4;
  alac->setinfo_86 = *(uint32_t*)ptr;
  if (!host_bigendian)
      _Swap32(alac->setinfo_86);
  ptr += 4;
  alac->setinfo_8a_rate = *(uint32_t*)ptr;
  if (!host_bigendian)
      _Swap32(alac->setinfo_8a_rate);
  ptr += 4;

  allocate_buffers(alac);

}
Esempio n. 11
0
/**
 * @brief Define a buffer pool. If the pool has already been defined, no action
 * is taken. A valid handle is returned. The status will be BPOOL_OPENED_RW
 * to indicate the pool has been opened for read/write.
 *
 * @param name Symbolic name of the pool
 * @param bp_id Buffer pool ID assigned by the caller.
 * @param max_data_size Max number of user bytes to be written to these buffers
 * @param rqst_capacity Min number of buffers to allocate.
 * @return Pointer to buffer pool handle.
 */
BPOOL_HANDLE* mmpool_define_pool(
	char name[MMPOOL_MAX_POOL_NAME],	// Symbolic name of the buffer pool
	unsigned short bp_id,		// Buffer pool ID
	size_t max_data_size,		// max number of user bytes to be written to these buffers
	unsigned short rqst_capacity	// min number of buffers to allocate
) {
	MMA_HANDLE* bpmf_mmahp = NULL;		// mmatom handle to BPMF object
	MMFOR_HANDLE* bpcf_mmafhp = NULL;		// MM File of Records handle to BPCF object
	BPMF_REC*  bpmf_recp;
	BPOOL_HANDLE* bphp;

	init();
	if (mmpool_bpfiles_exist(name)) {
		return mmpool_open(name);
	}	
	bpmf_mmahp = new_bpmf(name, bp_id, max_data_size, rqst_capacity);
	if (NULL == bpmf_mmahp) {
		return NULL;
	}
	
	// Get ptr to memory mapped BPMF_REC 
	bpmf_recp = (BPMF_REC*)mma_data_pointer(bpmf_mmahp);
	bpcf_mmafhp = new_bpcf(name, max_data_size, bpmf_recp->stats.capacity);

	if (NULL == bpcf_mmafhp) {
		// TODO: Need to destroy the mmahp here.
		return NULL;
	}
	
	// We have the Buffer Pool Management File setup ... we have
	// the Buffer Pool Contents File setup. Now all we have to do
	// is divide the bytes in the BPCF into buffers and allocate
	// them to the pool.
	
	allocate_buffers(bpmf_mmahp, bpcf_mmafhp);
	
	// Construct a BPOOL_HANDLE structure 
	bphp = (BPOOL_HANDLE*)calloc(1, sizeof(BPOOL_HANDLE));
	strncpy(bphp->pool_name, name, MMPOOL_MAX_POOL_NAME);
	bphp->bpmfp = bpmf_mmahp;
	bphp->bpcfp = bpcf_mmafhp;
	bphp->bpmf_recp = bpmf_recp;
			
	return bphp;	
}
Esempio n. 12
0
/**
 * Parse the STREAMINFO from an inline header.
 * @param s the flac decoding context
 * @param buf input buffer, starting with the "fLaC" marker
 * @param buf_size buffer size
 * @return non-zero if metadata is invalid
 */
static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
{
    int metadata_type, metadata_size;

    if (buf_size < FLAC_STREAMINFO_SIZE+8) {
        /* need more data */
        return 0;
    }
    ff_flac_parse_block_header(&buf[4], NULL, &metadata_type, &metadata_size);
    if (metadata_type != FLAC_METADATA_TYPE_STREAMINFO ||
        metadata_size != FLAC_STREAMINFO_SIZE) {
        return AVERROR_INVALIDDATA;
    }
    ff_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s, &buf[8]);
    allocate_buffers(s);
    s->got_streaminfo = 1;

    return 0;
}
Esempio n. 13
0
/**
 * Parse the STREAMINFO from an inline header.
 * @param s the flac decoding context
 * @param buf input buffer, starting with the "fLaC" marker
 * @param buf_size buffer size
 * @return non-zero if metadata is invalid
 */
static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
{
    int metadata_type, metadata_size, ret;

    if (buf_size < FLAC_STREAMINFO_SIZE+8) {
        /* need more data */
        return 0;
    }
    flac_parse_block_header(&buf[4], NULL, &metadata_type, &metadata_size);
    if (metadata_type != FLAC_METADATA_TYPE_STREAMINFO ||
        metadata_size != FLAC_STREAMINFO_SIZE) {
        return AVERROR_INVALIDDATA;
    }
    ff_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s, &buf[8]);
    ret = allocate_buffers(s);
    if (ret < 0)
        return ret;
    flac_set_bps(s);
    ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt, s->bps);
    s->got_streaminfo = 1;

    return 0;
}
Esempio n. 14
0
PyObject *databuf_alloc(PyObject *obj)
{
    DataBufObj *self;

    self = PyObject_NEW(DataBufObj, &DataBufType);
    if (self == NULL)
	return NULL;

    SY_LEAK_REG(self);
    self->buff = NULL;
    self->copied = NULL;
    self->indicator = NULL;
    self->serial = databuf_serial++;

    if (CS_DATAFMT_Check(obj)) {
	self->strip = ((CS_DATAFMTObj*)obj)->strip;
	self->fmt = ((CS_DATAFMTObj*)obj)->fmt;
	if (self->fmt.count == 0)
	    self->fmt.count = 1;

	/* Seems like FreeTDS reports the wrong maxlength in
	 * ct_describe() - fix this when binding to a buffer.
	 */
	/* Seems like Sybase's blk_describe has the same problem - PCP */ 
	if (self->fmt.datatype == CS_NUMERIC_TYPE
	    || self->fmt.datatype == CS_DECIMAL_TYPE)
	    self->fmt.maxlength = sizeof(CS_NUMERIC);

	if (allocate_buffers(self) == NULL) {
	    Py_DECREF(self);
	    return NULL;
	}
    } else {
	if (PyInt_Check(obj) || obj == Py_None)
	    /* if (PyInt_AsLong(obj) <= INT32_MAX && PyInt_AsLong(obj) >= INT32_MIN) */
	    int_datafmt(&self->fmt);
	else if (PyLong_Check(obj))
	    numeric_datafmt(&self->fmt, CS_SRC_VALUE, 0);
	else if (PyFloat_Check(obj))
	    float_datafmt(&self->fmt);
	else if (Numeric_Check(obj))
	    numeric_datafmt(&self->fmt, CS_SRC_VALUE, CS_SRC_VALUE);
	else if (DateTime_Check(obj))
	    datetime_datafmt(&self->fmt, ((DateTimeObj*)obj)->type);
#ifdef CS_DATE_TYPE
	else if (Date_Check(obj))
	    date_datafmt(&self->fmt);
#endif
	else if (Money_Check(obj))
	    money_datafmt(&self->fmt, ((MoneyObj*)obj)->type);
	else if (PyString_Check(obj)) {
	    char_datafmt(&self->fmt);
	    self->fmt.maxlength = PyString_Size(obj) + 1;
#ifdef HAVE_DATETIME
	} else if (pydatetime_check(obj)) {
	    datetime_datafmt(&self->fmt, CS_DATETIME_TYPE);
	} else if (pydate_check(obj)) {
#ifdef CS_DATE_TYPE
	    date_datafmt(&self->fmt);
#else
	    datetime_datafmt(&self->fmt, CS_DATETIME_TYPE);
#endif
#endif
#ifdef HAVE_DECIMAL
	} else if (pydecimal_check(obj)) {
	    numeric_datafmt(&self->fmt, CS_SRC_VALUE, CS_SRC_VALUE);
#endif
	} else {
	    PyErr_SetString(PyExc_TypeError, "unsupported parameter type");
	    Py_DECREF(self);
	    return NULL;
	}
	self->fmt.status = CS_INPUTVALUE;
	self->fmt.count = 1;

	if (allocate_buffers(self) == NULL
	    || DataBuf_ass_item((PyObject*)self, 0, obj) < 0) {
	    Py_DECREF(self);
	    return NULL;
	}
    }

    return (PyObject*)self;
}
Esempio n. 15
0
static int decode_frame(FLACContext *s)
{
    int i, ret;
    GetBitContext *gb = &s->gb;
    FLACFrameInfo fi;

    if ((ret = ff_flac_decode_frame_header(s->avctx, gb, &fi, 0)) < 0) {
        av_log(s->avctx, AV_LOG_ERROR, "invalid frame header\n");
        return ret;
    }

    if (s->channels && fi.channels != s->channels && s->got_streaminfo) {
        s->channels = s->avctx->channels = fi.channels;
        ff_flac_set_channel_layout(s->avctx);
        ret = allocate_buffers(s);
        if (ret < 0)
            return ret;
    }
    s->channels = s->avctx->channels = fi.channels;
    if (!s->avctx->channel_layout)
        ff_flac_set_channel_layout(s->avctx);
    s->ch_mode = fi.ch_mode;

    if (!s->bps && !fi.bps) {
        av_log(s->avctx, AV_LOG_ERROR, "bps not found in STREAMINFO or frame header\n");
        return AVERROR_INVALIDDATA;
    }
    if (!fi.bps) {
        fi.bps = s->bps;
    } else if (s->bps && fi.bps != s->bps) {
        av_log(s->avctx, AV_LOG_ERROR, "switching bps mid-stream is not "
                                       "supported\n");
        return AVERROR_INVALIDDATA;
    }

    if (!s->bps) {
        s->bps = s->avctx->bits_per_raw_sample = fi.bps;
        flac_set_bps(s);
    }

    if (!s->max_blocksize)
        s->max_blocksize = FLAC_MAX_BLOCKSIZE;
    if (fi.blocksize > s->max_blocksize) {
        av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", fi.blocksize,
               s->max_blocksize);
        return AVERROR_INVALIDDATA;
    }
    s->blocksize = fi.blocksize;

    if (!s->samplerate && !fi.samplerate) {
        av_log(s->avctx, AV_LOG_ERROR, "sample rate not found in STREAMINFO"
                                        " or frame header\n");
        return AVERROR_INVALIDDATA;
    }
    if (fi.samplerate == 0)
        fi.samplerate = s->samplerate;
    s->samplerate = s->avctx->sample_rate = fi.samplerate;

    if (!s->got_streaminfo) {
        ret = allocate_buffers(s);
        if (ret < 0)
            return ret;
        ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt, s->bps);
        s->got_streaminfo = 1;
        dump_headers(s->avctx, (FLACStreaminfo *)s);
    }

//    dump_headers(s->avctx, (FLACStreaminfo *)s);

    /* subframes */
    for (i = 0; i < s->channels; i++) {
        if ((ret = decode_subframe(s, i)) < 0)
            return ret;
    }

    align_get_bits(gb);

    /* frame footer */
    skip_bits(gb, 16); /* data crc */

    return 0;
}
Esempio n. 16
0
// add by zhangyan 2008-08-25
//发送ICMP包进行路由跟踪
int TraceReader::TraceRouteICMP(const char * cHost, int ttl)
{
	//用在发送和接受的ICMP包头中
    int seq_no = 0;
    ICMPHeader* send_buf = 0;
    IPHeader* recv_buf = 0;
    int rtn;
    int iCount = 0;
    int packet_size = DEFAULT_PACKET_SIZE;
    
    //packet_size = max(sizeof(ICMPHeader), min(MAX_PING_DATA_SIZE, (unsigned int)packet_size));

    // 启动 Winsocket
    WSAData wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        //winsocket版本错误
		//cout<<"winsocket版本错误\n");
        return SYSERROR;
    }

    SOCKET sd; // RAW Socket句柄
    sockaddr_in dest, source;

    // 三个任务(创建sd, 设置ttl, 初试dest的值)
    rtn = setup_for_ping( cHost, ttl, sd, dest, timeout);
    if ( rtn < 0)
    {
		//cout<<"创建 ping 错误\n");
        goto cleanup; //释放资源并退出
    }

	destMachine = dest;
	
    // 为send_buf和recv_buf分配内存
    rtn = allocate_buffers(send_buf, recv_buf, packet_size);
    if ( rtn < 0)
    {
		//cout<<"分配发送和接收缓冲错误\n");
        goto cleanup;
    }

    // 初始化IMCP数据包(type=8,code=0)
    init_ping_packet(send_buf, packet_size, seq_no);

    // 发送ICMP数据包
    rtn = send_ping(sd, dest, send_buf, packet_size);

	//cout<<"rtn: "<<rtn<<endl;	
    if ( rtn >= 0)
    {        		
        while(1)
        {
            // 接受回应包
            rtn = recv_ping(sd, source, recv_buf, MAX_PING_PACKET_SIZE);
            if ( rtn <= 0)
            {				
                if( ++iCount < retrys)
				{
					// (在重试次数内)发送ICMP数据包
					send_ping(sd, dest, send_buf, packet_size);					
					continue;
				}
				else
				{			
					//cout<<"超过重试次数\n");
					oneRoutePath.push_back("*");
					goto cleanup;
				}
                
            }
					
			char szSourceIP[16];				
                        strncpy(szSourceIP, inet_ntoa(source.sin_addr), 16);
			//cout<<szSourceIP<<endl;
			//{
			//	mutex::scoped_lock lock(m_tracert_mutex);
			//	oneRoutePath.push_back(szSourceIP);
			//}	
			oneRoutePath.push_back(szSourceIP);
			if (strcmp(szSourceIP, cHost) == 0)
			{
				//路由跟踪完成
				rtn = 11;
			}
		
            //if( GetTickCount() - send_buf->timestamp >= iTimeOut )
			//	rtn = OVERTIME;

			goto cleanup;
        }
   }

cleanup:
    delete[]send_buf;	//释放分配的内存
    delete[]recv_buf;
    WSACleanup();		// 清理winsock

    return rtn;
}
Esempio n. 17
0
static PmError winmm_out_open(PmInternal *midi, void *driverInfo)
{
    DWORD dwDevice;
    int i = midi->device_id;
    midiwinmm_type m;
    MIDIPROPTEMPO propdata;
    MIDIPROPTIMEDIV divdata;
    int max_sysex_len = midi->buffer_len * 4;
    int output_buffer_len;
    int num_buffers;
    dwDevice = (DWORD) descriptors[i].descriptor;

    /* create system dependent device data */
    m = (midiwinmm_type) pm_alloc(sizeof(midiwinmm_node)); /* create */
    midi->descriptor = m;
    if (!m) goto no_memory;
    m->handle.out = NULL;
    m->buffers = NULL;
    m->num_buffers = 0;
    m->max_buffers = 0;
    m->buffers_expanded = FALSE;
    m->next_buffer = 0;
    m->last_time = 0;
    m->first_message = TRUE; /* we treat first message as special case */
    m->sysex_mode = FALSE;
    m->sysex_word = 0;
    m->sysex_byte_count = 0;
    m->hdr = NULL;
    m->sync_time = 0;
    m->delta = 0;
    m->error = MMSYSERR_NOERROR;

    /* create a signal */
    m->buffer_signal = CreateEvent(NULL, FALSE, FALSE, NULL);

    /* this should only fail when there are very serious problems */
    assert(m->buffer_signal);

    /* open device */
    if (midi->latency == 0) {
        /* use simple midi out calls */
        pm_hosterror = midiOutOpen(
                (LPHMIDIOUT) & m->handle.out,  /* device Handle */
		dwDevice,  /* device ID  */
		/* note: same callback fn as for StreamOpen: */
		(DWORD_PTR) winmm_streamout_callback, /* callback fn */
		(DWORD_PTR) midi,  /* callback instance data */
		CALLBACK_FUNCTION); /* callback type */
    } else {
        /* use stream-based midi output (schedulable in future) */
        pm_hosterror = midiStreamOpen(
	        &m->handle.stream,  /* device Handle */
		(LPUINT) & dwDevice,  /* device ID pointer */
		1,  /* reserved, must be 1 */
		(DWORD_PTR) winmm_streamout_callback,
		(DWORD_PTR) midi,  /* callback instance data */
		CALLBACK_FUNCTION);
    }
    if (pm_hosterror != MMSYSERR_NOERROR) {
        goto free_descriptor;
    }

    if (midi->latency == 0) {
        num_buffers = NUM_SIMPLE_SYSEX_BUFFERS;
        output_buffer_len = max_sysex_len / num_buffers;
        if (output_buffer_len < MIN_SIMPLE_SYSEX_LEN)
            output_buffer_len = MIN_SIMPLE_SYSEX_LEN;
    } else {
        long dur = 0;
        num_buffers = max(midi->buffer_len, midi->latency / 2);
        if (num_buffers < MIN_STREAM_BUFFERS)
            num_buffers = MIN_STREAM_BUFFERS;
        output_buffer_len = STREAM_BUFFER_LEN;

        propdata.cbStruct = sizeof(MIDIPROPTEMPO);
        propdata.dwTempo = 480000; /* microseconds per quarter */
        pm_hosterror = midiStreamProperty(m->handle.stream,
                                          (LPBYTE) & propdata,
                                          MIDIPROP_SET | MIDIPROP_TEMPO);
        if (pm_hosterror) goto close_device;

        divdata.cbStruct = sizeof(MIDIPROPTEMPO);
        divdata.dwTimeDiv = 480;   /* divisions per quarter */
        pm_hosterror = midiStreamProperty(m->handle.stream,
                                          (LPBYTE) & divdata,
                                          MIDIPROP_SET | MIDIPROP_TIMEDIV);
        if (pm_hosterror) goto close_device;
    }
    /* allocate buffers */
    if (allocate_buffers(m, output_buffer_len, num_buffers)) 
        goto free_buffers;
    /* start device */
    if (midi->latency != 0) {
        pm_hosterror = midiStreamRestart(m->handle.stream);
        if (pm_hosterror != MMSYSERR_NOERROR) goto free_buffers;
    }
    return pmNoError;

free_buffers:
    /* buffers are freed below by winmm_out_delete */
close_device:
    midiOutClose(m->handle.out);
free_descriptor:
    midi->descriptor = NULL;
    winmm_out_delete(midi); /* frees buffers and m */
no_memory:
    if (pm_hosterror) {
        int err = midiOutGetErrorText(pm_hosterror, (char *) pm_hosterror_text,
                                      PM_HOST_ERROR_MSG_LEN);
        assert(err == MMSYSERR_NOERROR);
        return pmHostError;
    }
    return pmInsufficientMemory;
}
Esempio n. 18
0
void MainWindow::on_pushButton_clicked()
{
    if (ui->ipEdit->text().compare("") == 0) {
        showError("Не все поля заполнены!");
        return;
    }

    ui->textBrowser->setText("");

    int seq_no = 0;
    ICMPHeader* send_buf = 0;
    IPHeader* recv_buf = 0;

    int packet_size = DEFAULT_PACKET_SIZE;
    int ttl = DEFAULT_TTL;

    packet_size = max(sizeof(ICMPHeader),
                      min(MAX_PING_DATA_SIZE, (unsigned int)packet_size));

    WSAData wsaData;
    if (WSAStartup(MAKEWORD(2, 1), &wsaData) != 0) {
        showError("Failed to find Winsock 2.1 or better.");
        return;
    }

    rawping = new RawPing();
    connect(rawping,SIGNAL(error(QString)),this,SLOT(showError(QString)));
    connect(rawping,SIGNAL(message(QString)),this,SLOT(showMessage(QString)));

    SOCKET sd;
    sockaddr_in dest, source;
    if (rawping->setup_for_ping(ui->ipEdit->text().toLocal8Bit().data(), ttl, sd, dest) < 0) {
        goto cleanup;
    }
    if (allocate_buffers(send_buf, recv_buf, packet_size) < 0) {
        goto cleanup;
    }
    rawping->init_ping_packet(send_buf, packet_size, seq_no);

    if (rawping->send_ping(sd, dest, send_buf, packet_size) >= 0) {
        while (1) {
            if (rawping->recv_ping(sd, source, recv_buf, MAX_PING_PACKET_SIZE) <
                    0) {
                unsigned short header_len = recv_buf->h_len * 4;
                ICMPHeader* icmphdr = (ICMPHeader*)
                                      ((char*)recv_buf + header_len);
                if (icmphdr->seq != seq_no) {
                    showError("bad sequence number!");
                    continue;
                }
                else {
                    break;
                }
            }
            if (rawping->decode_reply(recv_buf, packet_size, &source) != -2) {
                break;
            }
        }
    }

cleanup:
    delete[]send_buf;
    delete[]recv_buf;
    WSACleanup();
    return;
}
Esempio n. 19
0
int main(int argc, char **argv)
{
	SOCKET PingSocket;
	ICMP_HDR *SendBuf = NULL;
	IPV4_HDR *RecvBuf = NULL;		// ICMP + IP buffer

	// 입력 값 확인
	if (argc < 2)
	{
		printf("usage:\n");
		printf("%s <host> [data_size]", argv[0]);
		printf("\tdata_size can be up to %d bytes. Default is %d\n", 
			MAX_PING_DATA_SIZE, DEFAULT_PACKET_SIZE);

		return 1;
	}

	// Initialize Winsock 
	WSADATA wsaData;
	int result;

	result = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (result != 0)
	{
		printf("WSAStartup failed with error: %d\n", WSAGetLastError());
		return -1;
	}

	//
	SOCKADDR_IN srcAddr, destAddr;
	int packet_size = DEFAULT_PACKET_SIZE;
	setup_for_ping(argv[1], PingSocket, destAddr);

	packet_size = max(sizeof(ICMP_HDR), 
						min(MAX_PING_DATA_SIZE, (unsigned int)packet_size));
	// SendBuf / RecvBuf Memory allocation
 	allocate_buffers(SendBuf, RecvBuf, packet_size);

	// set up ping packet
	init_ping_packet(SendBuf, packet_size);

	// Send the ping request and Receive the reply
	send_ping(PingSocket, destAddr, SendBuf, packet_size);
	while (1)
	{
		if (recv_ping(PingSocket, srcAddr, RecvBuf, MAX_PING_PACKET_SIZE) < 0)
		{
			unsigned short header_len = RecvBuf->ip_header_length * 4;
			ICMP_HDR* icmphdr = (ICMP_HDR *)((char *)RecvBuf + header_len);

		}
		else
		{
			break;
		}
	}

	// Cleanup
	WSACleanup();
	free(SendBuf);
	free(RecvBuf);

	return 0;
}
Esempio n. 20
0
void init( dcp_info_t * info, unsigned long alloc_size ) {

    int wsize;
    MPI_Comm_size(MPI_COMM_WORLD, &wsize);
    MPI_Comm_rank(MPI_COMM_WORLD, &grank);
    
    dictionary* ini;

    if (access("config.fti", R_OK) == 0) {
        ini = iniparser_load("config.fti");
        if (ini == NULL) {
            WARN_MSG("failed to parse FTI config file!");
            exit(EXIT_FAILURE);
        }
    } else {
        EXIT_STD_ERR("cannot access FTI config file!");
    }

    finalTag = (int)iniparser_getint(ini, "Advanced:final_tag", 3107);
    numHeads = (int)iniparser_getint(ini, "Basic:head", 0);
    int nodeSize = (int)iniparser_getint(ini, "Basic:node_size", -1);

    headRank = grank - grank%nodeSize;

    char* env = getenv( "TEST_MODE" );
    if( env ) {
        if( strcmp( env, "ICP" ) == 0 ) {
            info->test_mode = TEST_ICP;
            INFO_MSG("TEST MODE -> ICP");
        } else if ( strcmp( env, "NOICP") == 0 ) {
            info->test_mode = TEST_NOICP;
            INFO_MSG("TEST MODE -> NOICP");
        } else {
            info->test_mode = TEST_NOICP;
            INFO_MSG("TEST MODE -> NOICP");
        }
    } else {
        info->test_mode = TEST_NOICP;
        INFO_MSG("TEST MODE -> NOICP");
    }

    //DBG_MSG("alloc_size: %lu",0,alloc_size);
    init_share();
    
    // init pattern
    pat = (uint32_t) rand();
    
    // protect pattern and xor_info
    FTI_InitType( &FTI_UI, UI_UNIT ); 
    FTI_Protect( PAT_ID, &pat, 1, FTI_UI );  
    FTI_InitType( &FTI_XOR_INFO, sizeof(xor_info_t) ); 
    FTI_Protect( XOR_INFO_ID, info->xor_info, NUM_DCKPT, FTI_XOR_INFO );  
    FTI_Protect( NBUFFER_ID, &info->nbuffer,  1, FTI_INTG );  

    // check if alloc_size is sufficiant large
    if ( alloc_size < 101 ) EXIT_CFG_ERR("insufficiant allocation size"); 
    
    // determine number of buffers
    usleep(5000*grank);
    srand(get_seed());
    if ( FTI_Status() == 0 ) {
        info->nbuffer = rand()%10+1;
    } else {
        FTI_RecoverVar( NBUFFER_ID );
    }

    // initialize structure
    info->buffer = (void**) malloc(info->nbuffer*sizeof(void*));
    info->size = (unsigned long*) malloc(info->nbuffer*sizeof(unsigned long));
    info->oldsize = (unsigned long*) malloc(info->nbuffer*sizeof(unsigned long));
    info->hash = (unsigned char**) malloc(info->nbuffer*sizeof(unsigned char*));
    int idx;
    for ( idx=0; idx<info->nbuffer; ++idx ) {
        info->buffer[idx] = NULL;
        info->hash[idx] = (unsigned char*) malloc(MD5_DIGEST_LENGTH);
    }
    allocate_buffers( info, alloc_size );
    generate_data( info );
    init_srand();
}
Esempio n. 21
0
hale_internal
void
insert_non_crit_branch(FixedGapArena *arena,
                       memi offset,
                       const ch8 *data,
                       memi size,
                       Buf *it0)
{
    requirement_check_buf(it0);

    Buf *it1 = NULL;

    // TODO: Merge the `it` with next and previous buffers.

    // [...**]
    //     ^^----suffix----vv
    // [..+++] [+++++] [+++**]
    //    ^^^   ^^^^^   ^^^
    //    +++   +++++   +++**
    //    p0      p1     p2 ^-sx

    // http://cpp.sh/9yp22

    // Copy to first (possible split)
    memi p0 = hale_minimum(buf_capacity - offset, size);
    // Copy to new buffers (full)
    memi p1 = (size-p0) & ~buf_align_mask;
    // Copy to last (partial)
    memi p2 = (size-p0) &  buf_align_mask; // same as (data_size - r.p1 - r.p0);
    // Split size (won't underflow, as offset must be within the block (or == buf_length))
    memi sx = buf_length(it0) - offset;

    hale_assert(p0 + p1 + p2 == size);

    // TODO: Check if we can put part of `p1`, `p2` into sx.
    // - `p1` probably makes no sense to be merged with sx, as it's already calculated to be full.

    memi n = 0;
    // if (p0 && sx) { n += 1; }
    n += p0 && sx;
    // if (p1)       { n += p1 >> buf_capacity_shift; }
    n += p1 >> buf_align_shift;
    // if (p2)       { n += 1; }
    n += !!p2;

    if (n) {
        it1 = allocate_buffers(arena, buf_index(arena, it0) + 1, n);
        // TODO: This wouldn't be needed if allocate_buffers wouldn't
        // invalidate the pointers. (deque?)
        it0 = it1 - 1;
    }

    if (p0) {
        if (sx) {
            hale_assert_requirement(n != 0)
            buf_move_suffix(it0, offset, it0 + n); // same as `it1 + n - 1`
        }
        buf_insert(it0, offset, data, p0);

        // `data` and `size` is used in `p1` and `p2`,
        // so we update he right away.
        data += p0;
        size -= p0;
    }

    if (p1)
    {
        hale_assert_debug(it1);

        while (size != p2)
        {
            // TODO: buf_set
            buf_insert(it1, 0, data, buf_capacity);
            data += buf_capacity;
            size -= buf_capacity;
            ++it1;
        }
    }

    if (p2) {
        hale_assert_requirement(it1);
        hale_assert_requirement(p2 == size);
        // TODO: buf_set
        buf_insert(it1, 0, data, p2);
    }
}