Пример #1
0
/* caller must ensure we're at the movi chunk level */
int avi_writer_emit_opendml_indexes(avi_writer *w) {
    unsigned long long chunk_ofs=0,chunk_max;
    riff_indx_AVISUPERINDEX_entry suie;
    avi_writer_stream_index *si;
    unsigned int chunk,chks,out_chunks;
    riff_indx_AVISTDINDEX_entry *stdie;
    unsigned long long superindex;
    riff_indx_AVISTDINDEX stdh;
    avi_writer_stream *s;
    riff_chunk newchunk;
    int stream,in1,in2;
    long long offset;

    if (w == NULL) return 0;
    if (!w->enable_opendml_index) return 0;
    if (avi_io_buffer_init(sizeof(*stdie)) == NULL) return 0;

    for (stream=0;stream < w->avi_stream_max;stream++) {
        s = w->avi_stream + stream;
        if (s->indx_entryofs != 0) break;
        if (s->sample_index == NULL) continue;
        in1 = ((stream / 10) % 10) + '0';
        in2 = (stream % 10) + '0';

        for (chunk=0;chunk < s->sample_index_max;) {
            /* scan up to 2000 samples, and determine a good base offset for them */
            si = s->sample_index + chunk;
            chunk_ofs = chunk_max = si->offset;
            chks = chunk + 1; si++;
            while (chks < (chunk + 2000) && chks < s->sample_index_max) {
                if (chunk_max < si->offset) {
                    if (si->offset > (chunk_ofs + 0x7FFF0000ULL))
                        break;

                    chunk_max = si->offset;
                }
                else if (chunk_ofs > si->offset) {
                    if ((si->offset + 0x7FFF0000ULL) <= chunk_max)
                        break;

                    chunk_ofs = si->offset;
                }

                chks++;
                si++;
            }

            /* make sure the above loop does it's job */
            assert((chunk_ofs + 0x7FFF0000ULL) > chunk_max);

            /* start an AVISUPERINDEX */
            out_chunks = 0;
            if ((superindex = avi_writer_stream_alloc_superindex(w,s)) == 0ULL) {
                fprintf(stderr,"Cannot alloc superindex for %u\n",s->index);
                break;
            }

            /* start an index chunk */
            assert(riff_stack_begin_new_chunk_here(w->riff,&newchunk));
            assert(riff_stack_set_chunk_data_type(&newchunk,riff_fourcc_const('i','x',in1,in2)));
            assert(riff_stack_push(w->riff,&newchunk)); /* NTS: we can reuse chunk, the stack copies it here */

            memset(&stdh,0,sizeof(stdh));
            stdh.wLongsPerEntry = 2;
            stdh.bIndexType = riff_indx_type_AVI_INDEX_OF_CHUNKS;
            stdh.dwChunkId = s->chunk_fourcc;
            stdh.qwBaseOffset = chunk_ofs;
            assert(riff_stack_write(w->riff,riff_stack_top(w->riff),&stdh,sizeof(stdh)) == (int)sizeof(stdh));

            avi_io_write = avi_io_buf;
            while (chunk < s->sample_index_max) {
                si = s->sample_index + chunk;

                offset = (long long)si->offset - (long long)chunk_ofs;
                if (offset < 0LL || offset >= 0x7FFF0000LL)
                    break;

                if ((avi_io_write+sizeof(*stdie)) > avi_io_fence) {
                    size_t sz = (size_t)(avi_io_write - avi_io_buf);
                    /* flush to disk */
                    assert(riff_stack_write(w->riff,riff_stack_top(w->riff),avi_io_buf,sz) == (int)sz);
                    /* reset pointer */
                    avi_io_write = avi_io_buf;
                }

                stdie = (riff_indx_AVISTDINDEX_entry*)avi_io_write;
                avi_io_write += sizeof(*stdie);

                stdie->dwOffset = (uint32_t)offset;
                stdie->dwSize = si->length;
                if ((si->dwFlags & riff_idx1_AVIOLDINDEX_flags_KEYFRAME) == 0) stdie->dwSize |= (1UL << 31UL);
                out_chunks++;
                chunk++;
            }

            if (avi_io_write != avi_io_fence) {
                size_t sz = (size_t)(avi_io_write - avi_io_buf);
                /* flush to disk */
                assert(riff_stack_write(w->riff,riff_stack_top(w->riff),avi_io_buf,sz) == (int)sz);
                /* reset pointer */
                avi_io_write = avi_io_buf;
            }

            assert(out_chunks != 0);
            stdh.nEntriesInUse = out_chunks;
            assert(riff_stack_seek(w->riff,riff_stack_top(w->riff),0) == 0);
            assert(riff_stack_write(w->riff,riff_stack_top(w->riff),&stdh,sizeof(stdh)) == (int)sizeof(stdh));

            newchunk = *riff_stack_top(w->riff);
            riff_stack_pop(w->riff); /* end ix## */

            suie.qwOffset = (uint64_t)newchunk.absolute_header_offset;
            suie.dwDuration = out_chunks;
            suie.dwSize = newchunk.data_length + 8;
            assert(riff_stack_seek(w->riff,NULL,(int64_t)superindex) == (int64_t)superindex);
            assert(riff_stack_write(w->riff,NULL,&suie,sizeof(suie)) == (int)sizeof(suie));
        }
    }

    avi_io_buffer_free();
    return 1;
}
Пример #2
0
int CalcMeleeDamage(LPCHARACTER pkAttacker, LPCHARACTER pkVictim, bool bIgnoreDefense, bool bIgnoreTargetRating)
{
	LPITEM pWeapon = pkAttacker->GetWear(WEAR_WEAPON);
	bool bPolymorphed = pkAttacker->IsPolymorphed();

	if (pWeapon && !(bPolymorphed && !pkAttacker->IsPolyMaintainStat()))
	{
		if (pWeapon->GetType() != ITEM_WEAPON)
			return 0;

		switch (pWeapon->GetSubType())
		{
			case WEAPON_SWORD:
			case WEAPON_DAGGER:
			case WEAPON_TWO_HANDED:
			case WEAPON_BELL:
			case WEAPON_FAN:
			case WEAPON_MOUNT_SPEAR:
				break;

			case WEAPON_BOW:
				sys_err("CalcMeleeDamage should not handle bows (name: %s)", pkAttacker->GetName());
				return 0;

			default:
				return 0;
		}
	}

	int iDam = 0;
	float fAR = CalcAttackRating(pkAttacker, pkVictim, bIgnoreTargetRating);
	int iDamMin = 0, iDamMax = 0;

	// TESTSERVER_SHOW_ATTACKINFO
	int DEBUG_iDamCur = 0;
	int DEBUG_iDamBonus = 0;
	// END_OF_TESTSERVER_SHOW_ATTACKINFO

	if (bPolymorphed && !pkAttacker->IsPolyMaintainStat())
	{
		// MONKEY_ROD_ATTACK_BUG_FIX
		Item_GetDamage(pWeapon, &iDamMin, &iDamMax);
		// END_OF_MONKEY_ROD_ATTACK_BUG_FIX

		DWORD dwMobVnum = pkAttacker->GetPolymorphVnum();
		const CMob * pMob = CMobManager::instance().Get(dwMobVnum);

		if (pMob)
		{
			int iPower = pkAttacker->GetPolymorphPower();
			iDamMin += pMob->m_table.dwDamageRange[0] * iPower / 100;
			iDamMax += pMob->m_table.dwDamageRange[1] * iPower / 100;
		}
	}
	else if (pWeapon)
	{
		// MONKEY_ROD_ATTACK_BUG_FIX
		Item_GetDamage(pWeapon, &iDamMin, &iDamMax);
		// END_OF_MONKEY_ROD_ATTACK_BUG_FIX
	}
	else if (pkAttacker->IsNPC())
	{
		iDamMin = pkAttacker->GetMobDamageMin();
		iDamMax = pkAttacker->GetMobDamageMax();
	}

	iDam = number(iDamMin, iDamMax) * 2;

	// TESTSERVER_SHOW_ATTACKINFO
	DEBUG_iDamCur = iDam;
	// END_OF_TESTSERVER_SHOW_ATTACKINFO
	//
	int iAtk = 0;

	// level must be ignored when multiply by fAR, so subtract it before calculation.
	iAtk = pkAttacker->GetPoint(POINT_ATT_GRADE) + iDam - (pkAttacker->GetLevel() * 2);
	iAtk = (int) (iAtk * fAR);
	iAtk += pkAttacker->GetLevel() * 2; // and add again

	if (pWeapon)
	{
		iAtk += pWeapon->GetValue(5) * 2;

		// 2004.11.12.myevan.TESTSERVER_SHOW_ATTACKINFO
		DEBUG_iDamBonus = pWeapon->GetValue(5) * 2;
		///////////////////////////////////////////////
	}

	iAtk += pkAttacker->GetPoint(POINT_PARTY_ATTACKER_BONUS); // party attacker role bonus
	iAtk = (int) (iAtk * (100 + (pkAttacker->GetPoint(POINT_ATT_BONUS) + pkAttacker->GetPoint(POINT_MELEE_MAGIC_ATT_BONUS_PER))) / 100);

	iAtk = CalcAttBonus(pkAttacker, pkVictim, iAtk);

	int iDef = 0;

	if (!bIgnoreDefense)
	{
		iDef = (pkVictim->GetPoint(POINT_DEF_GRADE) * (100 + pkVictim->GetPoint(POINT_DEF_BONUS)) / 100);

		if (!pkAttacker->IsPC())
			iDef += pkVictim->GetMarriageBonus(UNIQUE_ITEM_MARRIAGE_DEFENSE_BONUS);
	}

	if (pkAttacker->IsNPC())
		iAtk = (int) (iAtk * pkAttacker->GetMobDamageMultiply());

	iDam = MAX(0, iAtk - iDef);

	if (test_server)
	{
		int DEBUG_iLV = pkAttacker->GetLevel()*2;
		int DEBUG_iST = int((pkAttacker->GetPoint(POINT_ATT_GRADE) - DEBUG_iLV) * fAR);
		int DEBUG_iPT = pkAttacker->GetPoint(POINT_PARTY_ATTACKER_BONUS);
		int DEBUG_iWP = 0;
		int DEBUG_iPureAtk = 0;
		int DEBUG_iPureDam = 0;
		char szRB[32] = "";
		char szGradeAtkBonus[32] = "";

		DEBUG_iWP = int(DEBUG_iDamCur * fAR);
		DEBUG_iPureAtk = DEBUG_iLV + DEBUG_iST + DEBUG_iWP+DEBUG_iDamBonus;
		DEBUG_iPureDam = iAtk - iDef;

		if (pkAttacker->IsNPC())
		{
			snprintf(szGradeAtkBonus, sizeof(szGradeAtkBonus), "=%d*%.1f", DEBUG_iPureAtk, pkAttacker->GetMobDamageMultiply());
			DEBUG_iPureAtk = int(DEBUG_iPureAtk * pkAttacker->GetMobDamageMultiply());
		}

		if (DEBUG_iDamBonus != 0)
			snprintf(szRB, sizeof(szRB), "+RB(%d)", DEBUG_iDamBonus);

		char szPT[32] = "";

		if (DEBUG_iPT != 0)
			snprintf(szPT, sizeof(szPT), ", PT=%d", DEBUG_iPT);

		char szUnknownAtk[32] = "";

		if (iAtk != DEBUG_iPureAtk)
			snprintf(szUnknownAtk, sizeof(szUnknownAtk), "+?(%d)", iAtk-DEBUG_iPureAtk);

		char szUnknownDam[32] = "";

		if (iDam != DEBUG_iPureDam)
			snprintf(szUnknownDam, sizeof(szUnknownDam), "+?(%d)", iDam-DEBUG_iPureDam);

		char szMeleeAttack[128];

		snprintf(szMeleeAttack, sizeof(szMeleeAttack), 
				"%s(%d)-%s(%d)=%d%s, ATK=LV(%d)+ST(%d)+WP(%d)%s%s%s, AR=%.3g%s", 
				pkAttacker->GetName(),
				iAtk,
				pkVictim->GetName(),
				iDef,
				iDam,
				szUnknownDam,
				DEBUG_iLV, 
				DEBUG_iST,
				DEBUG_iWP, 
				szRB,
				szUnknownAtk,
				szGradeAtkBonus,
				fAR,
				szPT);

		pkAttacker->ChatPacket(CHAT_TYPE_TALKING, "%s", szMeleeAttack);
		pkVictim->ChatPacket(CHAT_TYPE_TALKING, "%s", szMeleeAttack);
	}

	return CalcBattleDamage(iDam, pkAttacker->GetLevel(), pkVictim->GetLevel());
}
Пример #3
0
cibar_t *cibar_open(FILE *f)
{
  cibar_internal_file_entry_t *entries;
  char *strings;
  uint8_t *data;
  cibar_internal_t cb;
  cibar_t *out;
  int i;

  if (!f)
    return NULL;

  /* Read the header */
  fread(&cb, sizeof(cibar_internal_t), 1, f);

  if (cb.magic != 0x12344321)
    {
      printf("cibar: Wrong magic: 0x%08x\n", cb.magic);
      goto error_1;
    }

  /* Allocate structures */
  if ( !(entries = (cibar_internal_file_entry_t*)malloc(sizeof(cibar_internal_file_entry_t) * cb.n_file_entries)) )
    goto error_1;
  if ( !(strings = (char*)malloc( cb.strtab_length )) )
    goto error_2;
  if ( !(data = (uint8_t*)malloc( cb.data_length )) )
    goto error_3;
  if ( !(out = (cibar_t*)malloc( sizeof(cibar_t) + sizeof(cibar_file_entry_t) * cb.n_file_entries)) )
    goto error_4;

  /* Read the rest of the file */
  if (fread(entries, 1, sizeof(cibar_internal_file_entry_t) * cb.n_file_entries, f) !=
      sizeof(cibar_internal_file_entry_t) * cb.n_file_entries)
    goto error_4;
  if (fread(strings, 1, cb.strtab_length, f) != cb.strtab_length)
    goto error_4;
  if (fread(data, 1, cb.data_length, f) != cb.data_length)
    goto error_4;

  /* Fill in the out stucture */
  out->n_files = cb.n_file_entries;
  out->strings = strings;
  out->data = data;
  for (i = 0; i < cb.n_file_entries; i++)
    {
      cibar_file_entry_t *p = &out->files[i];

      p->cibar = out;
      p->data = data + entries[i].data_offset;
      p->data_size = entries[i].data_size;
      p->name = strings + entries[i].strtab_offset;
    }

  free(entries);

  return out;
 error_4:
  free(data);
 error_3:
  free(strings);
 error_2:
  free(entries);
 error_1:
  return NULL;
}
Пример #4
0
static netdev_tx_t ibmveth_start_xmit(struct sk_buff *skb,
				      struct net_device *netdev)
{
	struct ibmveth_adapter *adapter = netdev_priv(netdev);
	unsigned int desc_flags;
	union ibmveth_buf_desc descs[6];
	int last, i;
	int force_bounce = 0;
	dma_addr_t dma_addr;

	/*
	 * veth handles a maximum of 6 segments including the header, so
	 * we have to linearize the skb if there are more than this.
	 */
	if (skb_shinfo(skb)->nr_frags > 5 && __skb_linearize(skb)) {
		netdev->stats.tx_dropped++;
		goto out;
	}

	/* veth can't checksum offload UDP */
	if (skb->ip_summed == CHECKSUM_PARTIAL &&
	    ((skb->protocol == htons(ETH_P_IP) &&
	      ip_hdr(skb)->protocol != IPPROTO_TCP) ||
	     (skb->protocol == htons(ETH_P_IPV6) &&
	      ipv6_hdr(skb)->nexthdr != IPPROTO_TCP)) &&
	    skb_checksum_help(skb)) {

		netdev_err(netdev, "tx: failed to checksum packet\n");
		netdev->stats.tx_dropped++;
		goto out;
	}

	desc_flags = IBMVETH_BUF_VALID;

	if (skb->ip_summed == CHECKSUM_PARTIAL) {
		unsigned char *buf = skb_transport_header(skb) +
						skb->csum_offset;

		desc_flags |= (IBMVETH_BUF_NO_CSUM | IBMVETH_BUF_CSUM_GOOD);

		/* Need to zero out the checksum */
		buf[0] = 0;
		buf[1] = 0;
	}

retry_bounce:
	memset(descs, 0, sizeof(descs));

	/*
	 * If a linear packet is below the rx threshold then
	 * copy it into the static bounce buffer. This avoids the
	 * cost of a TCE insert and remove.
	 */
	if (force_bounce || (!skb_is_nonlinear(skb) &&
				(skb->len < tx_copybreak))) {
		skb_copy_from_linear_data(skb, adapter->bounce_buffer,
					  skb->len);

		descs[0].fields.flags_len = desc_flags | skb->len;
		descs[0].fields.address = adapter->bounce_buffer_dma;

		if (ibmveth_send(adapter, descs)) {
			adapter->tx_send_failed++;
			netdev->stats.tx_dropped++;
		} else {
			netdev->stats.tx_packets++;
			netdev->stats.tx_bytes += skb->len;
		}

		goto out;
	}

	/* Map the header */
	dma_addr = dma_map_single(&adapter->vdev->dev, skb->data,
				  skb_headlen(skb), DMA_TO_DEVICE);
	if (dma_mapping_error(&adapter->vdev->dev, dma_addr))
		goto map_failed;

	descs[0].fields.flags_len = desc_flags | skb_headlen(skb);
	descs[0].fields.address = dma_addr;

	/* Map the frags */
	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
		const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];

		dma_addr = skb_frag_dma_map(&adapter->vdev->dev, frag, 0,
					    skb_frag_size(frag), DMA_TO_DEVICE);

		if (dma_mapping_error(&adapter->vdev->dev, dma_addr))
			goto map_failed_frags;

		descs[i+1].fields.flags_len = desc_flags | skb_frag_size(frag);
		descs[i+1].fields.address = dma_addr;
	}

	if (ibmveth_send(adapter, descs)) {
		adapter->tx_send_failed++;
		netdev->stats.tx_dropped++;
	} else {
		netdev->stats.tx_packets++;
		netdev->stats.tx_bytes += skb->len;
	}

	dma_unmap_single(&adapter->vdev->dev,
			 descs[0].fields.address,
			 descs[0].fields.flags_len & IBMVETH_BUF_LEN_MASK,
			 DMA_TO_DEVICE);

	for (i = 1; i < skb_shinfo(skb)->nr_frags + 1; i++)
		dma_unmap_page(&adapter->vdev->dev, descs[i].fields.address,
			       descs[i].fields.flags_len & IBMVETH_BUF_LEN_MASK,
			       DMA_TO_DEVICE);

out:
	dev_kfree_skb(skb);
	return NETDEV_TX_OK;

map_failed_frags:
	last = i+1;
	for (i = 0; i < last; i++)
		dma_unmap_page(&adapter->vdev->dev, descs[i].fields.address,
			       descs[i].fields.flags_len & IBMVETH_BUF_LEN_MASK,
			       DMA_TO_DEVICE);

map_failed:
	if (!firmware_has_feature(FW_FEATURE_CMO))
		netdev_err(netdev, "tx: unable to map xmit buffer\n");
	adapter->tx_map_failed++;
	skb_linearize(skb);
	force_bounce = 1;
	goto retry_bounce;
}
Пример #5
0
    return (vm->heap.next + size + sizeof(size_t) < vm->heap.end);
}

void* allocate(VM* vm, size_t size, int outerlock) {
//    return malloc(size);
    int lock = vm->processes > 0 && !outerlock;

    if (lock) { // not message passing
       pthread_mutex_lock(&vm->alloc_lock); 
    }

    if ((size & 7)!=0) {
	size = 8 + ((size >> 3) << 3);
    }
    
    size_t chunk_size = size + sizeof(size_t);

    if (vm->heap.next + chunk_size < vm->heap.end) {
        STATS_ALLOC(vm->stats, chunk_size)
        void* ptr = (void*)(vm->heap.next + sizeof(size_t));
        *((size_t*)(vm->heap.next)) = chunk_size;
        vm->heap.next += chunk_size;

        assert(vm->heap.next <= vm->heap.end);

        memset(ptr, 0, size);

        if (lock) { // not message passing
           pthread_mutex_unlock(&vm->alloc_lock); 
        }
        return ptr;
Пример #6
0
void quadrotor::State::save(const std::list<State> & states, std::string path)
{
	MATFile *result;

	mxArray *R;
	mxArray *xq;
	mxArray *omega;
	mxArray *vq;

	void *p;
	
	mwSize *dims=new mwSize[3];
	
	result=matOpen(path.c_str(),"w");

	std::list<State>::const_iterator it_state;

	it_state=states.cbegin();
	dims[0]=3;
	dims[1]=3;
	dims[2]=states.size();

	R=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);


	for(p=mxGetPr(R);it_state!=states.cend();it_state++)
	{
		Mat3 R=it_state->g.block(0,0,3,3);
		memcpy(p,R.data(),sizeof(double)*dims[0]*dims[1]);
		p+=sizeof(double)*dims[0]*dims[1];
	}

	matPutVariable(result,"R",R);
	mxDestroyArray(R);

	it_state=states.cbegin();
	dims[0]=3;
	dims[1]=1;
	dims[2]=states.size();

	xq=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);


	for(p=mxGetPr(xq);it_state!=states.cend();it_state++)
	{
		memcpy(p,it_state->g.block(0,3,3,1).data(),sizeof(double)*dims[0]*dims[1]);
		p+=sizeof(double)*dims[0]*dims[1];
	}

	matPutVariable(result,"xq",xq);
	mxDestroyArray(xq);

	it_state=states.cbegin();
	dims[0]=3;
	dims[1]=1;
	dims[2]=states.size();

	vq=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);


	for(p=mxGetPr(vq);it_state!=states.cend();it_state++)
	{
		memcpy(p,it_state->v.tail(3).data(),sizeof(double)*dims[0]*dims[1]);
		p+=sizeof(double)*dims[0]*dims[1];
	}

	matPutVariable(result,"vq",vq);
	mxDestroyArray(vq);

	it_state=states.cbegin();
	dims[0]=3;
	dims[1]=1;
	dims[2]=states.size();

	omega=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);


	for(p=mxGetPr(omega);it_state!=states.cend();it_state++)
	{
		memcpy(p,it_state->v.head(3).data(),sizeof(double)*dims[0]*dims[1]);
		p+=sizeof(double)*dims[0]*dims[1];
	}

	matPutVariable(result,"omega",omega);
	mxDestroyArray(omega);
}
Пример #7
0
static int ibmveth_open(struct net_device *netdev)
{
	struct ibmveth_adapter *adapter = netdev_priv(netdev);
	u64 mac_address;
	int rxq_entries = 1;
	unsigned long lpar_rc;
	int rc;
	union ibmveth_buf_desc rxq_desc;
	int i;
	struct device *dev;

	netdev_dbg(netdev, "open starting\n");

	napi_enable(&adapter->napi);

	for(i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++)
		rxq_entries += adapter->rx_buff_pool[i].size;

	adapter->buffer_list_addr = (void*) get_zeroed_page(GFP_KERNEL);
	adapter->filter_list_addr = (void*) get_zeroed_page(GFP_KERNEL);

	if (!adapter->buffer_list_addr || !adapter->filter_list_addr) {
		netdev_err(netdev, "unable to allocate filter or buffer list "
			   "pages\n");
		rc = -ENOMEM;
		goto err_out;
	}

	dev = &adapter->vdev->dev;

	adapter->rx_queue.queue_len = sizeof(struct ibmveth_rx_q_entry) *
						rxq_entries;
	adapter->rx_queue.queue_addr =
		dma_alloc_coherent(dev, adapter->rx_queue.queue_len,
				   &adapter->rx_queue.queue_dma, GFP_KERNEL);
	if (!adapter->rx_queue.queue_addr) {
		rc = -ENOMEM;
		goto err_out;
	}

	adapter->buffer_list_dma = dma_map_single(dev,
			adapter->buffer_list_addr, 4096, DMA_BIDIRECTIONAL);
	adapter->filter_list_dma = dma_map_single(dev,
			adapter->filter_list_addr, 4096, DMA_BIDIRECTIONAL);

	if ((dma_mapping_error(dev, adapter->buffer_list_dma)) ||
	    (dma_mapping_error(dev, adapter->filter_list_dma))) {
		netdev_err(netdev, "unable to map filter or buffer list "
			   "pages\n");
		rc = -ENOMEM;
		goto err_out;
	}

	adapter->rx_queue.index = 0;
	adapter->rx_queue.num_slots = rxq_entries;
	adapter->rx_queue.toggle = 1;

	mac_address = ibmveth_encode_mac_addr(netdev->dev_addr);

	rxq_desc.fields.flags_len = IBMVETH_BUF_VALID |
					adapter->rx_queue.queue_len;
	rxq_desc.fields.address = adapter->rx_queue.queue_dma;

	netdev_dbg(netdev, "buffer list @ 0x%p\n", adapter->buffer_list_addr);
	netdev_dbg(netdev, "filter list @ 0x%p\n", adapter->filter_list_addr);
	netdev_dbg(netdev, "receive q   @ 0x%p\n", adapter->rx_queue.queue_addr);

	h_vio_signal(adapter->vdev->unit_address, VIO_IRQ_DISABLE);

	lpar_rc = ibmveth_register_logical_lan(adapter, rxq_desc, mac_address);

	if (lpar_rc != H_SUCCESS) {
		netdev_err(netdev, "h_register_logical_lan failed with %ld\n",
			   lpar_rc);
		netdev_err(netdev, "buffer TCE:0x%llx filter TCE:0x%llx rxq "
			   "desc:0x%llx MAC:0x%llx\n",
				     adapter->buffer_list_dma,
				     adapter->filter_list_dma,
				     rxq_desc.desc,
				     mac_address);
		rc = -ENONET;
		goto err_out;
	}

	for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++) {
		if (!adapter->rx_buff_pool[i].active)
			continue;
		if (ibmveth_alloc_buffer_pool(&adapter->rx_buff_pool[i])) {
			netdev_err(netdev, "unable to alloc pool\n");
			adapter->rx_buff_pool[i].active = 0;
			rc = -ENOMEM;
			goto err_out;
		}
	}

	netdev_dbg(netdev, "registering irq 0x%x\n", netdev->irq);
	rc = request_irq(netdev->irq, ibmveth_interrupt, 0, netdev->name,
			 netdev);
	if (rc != 0) {
		netdev_err(netdev, "unable to request irq 0x%x, rc %d\n",
			   netdev->irq, rc);
		do {
			lpar_rc = h_free_logical_lan(adapter->vdev->unit_address);
		} while (H_IS_LONG_BUSY(lpar_rc) || (lpar_rc == H_BUSY));

		goto err_out;
	}

	adapter->bounce_buffer =
	    kmalloc(netdev->mtu + IBMVETH_BUFF_OH, GFP_KERNEL);
	if (!adapter->bounce_buffer) {
		rc = -ENOMEM;
		goto err_out_free_irq;
	}
	adapter->bounce_buffer_dma =
	    dma_map_single(&adapter->vdev->dev, adapter->bounce_buffer,
			   netdev->mtu + IBMVETH_BUFF_OH, DMA_BIDIRECTIONAL);
	if (dma_mapping_error(dev, adapter->bounce_buffer_dma)) {
		netdev_err(netdev, "unable to map bounce buffer\n");
		rc = -ENOMEM;
		goto err_out_free_irq;
	}

	netdev_dbg(netdev, "initial replenish cycle\n");
	ibmveth_interrupt(netdev->irq, netdev);

	netif_start_queue(netdev);

	netdev_dbg(netdev, "open complete\n");

	return 0;

err_out_free_irq:
	free_irq(netdev->irq, netdev);
err_out:
	ibmveth_cleanup(adapter);
	napi_disable(&adapter->napi);
	return rc;
}
Пример #8
0
int main(int argc, char *const *argv)
{
    char *fname = NULL;
    int rc, ch;
    char data[1000];
    char pat[500];
    FILE *fd;
    bool match_only = true;
    int lineno;
    bool no_linenos = false;
    int ic = 0;


    setlocale(LC_ALL, "");
    bindtextdomain("bareos", LOCALEDIR);
    textdomain("bareos");

    while ((ch = getopt(argc, argv, "d:f:in?")) != -1) {
        switch (ch) {
        case 'd':                       /* set debug level */
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
                debug_level = 1;
            }
            break;

        case 'f':                       /* data */
            fname = optarg;
            break;

        case 'i':                       /* ignore case */
            ic = FNM_CASEFOLD;
            break;

        case 'l':
            no_linenos = true;
            break;

        case 'n':
            match_only = false;
            break;

        case '?':
        default:
            usage();

        }
    }
    argc -= optind;
    argv += optind;

    if (!fname) {
        printf("A data file must be specified.\n");
        usage();
    }

    OSDependentInit();

    for ( ;; ) {
        printf("Enter a wild-card: ");
        if (fgets(pat, sizeof(pat)-1, stdin) == NULL) {
            break;
        }
        strip_trailing_newline(pat);
        if (pat[0] == 0) {
            exit(0);
        }
        fd = fopen(fname, "r");
        if (!fd) {
            printf(_("Could not open data file: %s\n"), fname);
            exit(1);
        }
        lineno = 0;
        while (fgets(data, sizeof(data)-1, fd)) {
            strip_trailing_newline(data);
            lineno++;
            rc = fnmatch(pat, data, ic);
            if ((match_only && rc == 0) || (!match_only && rc != 0)) {
                if (no_linenos) {
                    printf("%s\n", data);
                } else {
                    printf("%5d: %s\n", lineno, data);
                }
            }
        }
        fclose(fd);
    }
    exit(0);
}
Пример #9
0
int main(int argc, char **argv)
{
  burrow_st *burrow;
  client_st client;
  msg_st *msg;
  int use_http = 0;

  argc--;
  argv++;

  if (strcmp(argv[0], "http") == 0) {
    use_http = 1;
    argc--;
    argv++;
  }

  if (argc < 4 || argc % 2 != 0)
    return -1;

  client.account = argv[0];
  client.queue = argv[1];
  argc -= 2;
  argv += 2;

  client.messages = NULL;
  client.message_count = 0;

  while (argc) {
    msg = malloc(sizeof(msg_st));
    if (!msg)
      return -2;

    msg->msg_id = argv[0];
    msg->body = (uint8_t *)argv[1];
    msg->body_size = strlen(argv[1]);
    msg->next = client.messages;
    client.messages = msg;
    client.message_count++;

    argc -= 2;
    argv += 2;
  }

  client.return_code = 0;
  client.current_message = client.messages;

  if (use_http == 0) {
    burrow = burrow_create(NULL, "dummy");
    printf("burrow = %p\n", burrow);
  } else {
    burrow = burrow_create(NULL, "http");
    printf("burrow = %p\n", burrow);
    burrow_backend_set_option(burrow, "server", "localhost");
    burrow_backend_set_option(burrow, "port", "8080");
  }

  burrow_set_context(burrow, &client);
  burrow_set_complete_fn(burrow, &_complete);
  burrow_set_log_fn(burrow, &_log);

  /* Insert the first one here to kick the loop off. This only sets start state,
     it doesn't run the loop. */
  msg = client.current_message;
  burrow_create_message(burrow, client.account, client.queue,
    msg->msg_id, msg->body, msg->body_size, NULL);

  /* This runs until there are no more tasks. */
  burrow_process(burrow);
  burrow_destroy(burrow);

  return client.return_code;
}
Пример #10
0
/*
============
Cvar_Validate
============
*/
static const char *Cvar_Validate( cvar_t *var,
    const char *value, qboolean warn )
{
	static char s[ MAX_CVAR_VALUE_STRING ];
	float valuef;
	qboolean changed = qfalse;

	if( !var->validate )
		return value;

	if( !value )
		return value;

	if( Q_isanumber( value ) )
	{
		valuef = atof( value );

		if( var->integral )
		{
			if( !Q_isintegral( valuef ) )
			{
				if( warn )
					Com_Printf( "WARNING: cvar '%s' must be integral", var->name );

				valuef = (int)valuef;
				changed = qtrue;
			}
		}
	}
	else
	{
		if( warn )
			Com_Printf( "WARNING: cvar '%s' must be numeric", var->name );

		valuef = atof( var->resetString );
		changed = qtrue;
	}

	if( valuef < var->min )
	{
		if( warn )
		{
			if( changed )
				Com_Printf( " and is" );
			else
				Com_Printf( "WARNING: cvar '%s'", var->name );

			if( Q_isintegral( var->min ) )
				Com_Printf( " out of range (min %d)", (int)var->min );
			else
				Com_Printf( " out of range (min %f)", var->min );
		}

		valuef = var->min;
		changed = qtrue;
	}
	else if( valuef > var->max )
	{
		if( warn )
		{
			if( changed )
				Com_Printf( " and is" );
			else
				Com_Printf( "WARNING: cvar '%s'", var->name );

			if( Q_isintegral( var->max ) )
				Com_Printf( " out of range (max %d)", (int)var->max );
			else
				Com_Printf( " out of range (max %f)", var->max );
		}

		valuef = var->max;
		changed = qtrue;
	}

	if( changed )
	{
		if( Q_isintegral( valuef ) )
		{
			Com_sprintf( s, sizeof( s ), "%d", (int)valuef );

			if( warn )
				Com_Printf( ", setting to %d\n", (int)valuef );
		}
		else
		{
			Com_sprintf( s, sizeof( s ), "%f", valuef );

			if( warn )
				Com_Printf( ", setting to %f\n", valuef );
		}

		return s;
	}
	else
		return value;
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrPipelineDynamicStateTest, reporter, ctxInfo) {
    GrContext* const context = ctxInfo.grContext();
    GrResourceProvider* rp = context->resourceProvider();

    sk_sp<GrRenderTargetContext> rtc(
        context->makeDeferredRenderTargetContext(SkBackingFit::kExact, kScreenSize, kScreenSize,
                                                 kRGBA_8888_GrPixelConfig, nullptr));
    if (!rtc) {
        ERRORF(reporter, "could not create render target context.");
        return;
    }

    constexpr float d = (float) kScreenSize;
    Vertex vdata[kNumMeshes * 4] = {
        {0, 0, kMeshColors[0]},
        {0, d, kMeshColors[0]},
        {d, 0, kMeshColors[0]},
        {d, d, kMeshColors[0]},

        {0, 0, kMeshColors[1]},
        {0, d, kMeshColors[1]},
        {d, 0, kMeshColors[1]},
        {d, d, kMeshColors[1]},

        {0, 0, kMeshColors[2]},
        {0, d, kMeshColors[2]},
        {d, 0, kMeshColors[2]},
        {d, d, kMeshColors[2]},

        {0, 0, kMeshColors[3]},
        {0, d, kMeshColors[3]},
        {d, 0, kMeshColors[3]},
        {d, d, kMeshColors[3]}
    };

    sk_sp<const GrBuffer> vbuff(rp->createBuffer(sizeof(vdata), kVertex_GrBufferType,
                                                 kDynamic_GrAccessPattern,
                                                 GrResourceProvider::kNoPendingIO_Flag |
                                                 GrResourceProvider::kRequireGpuMemory_Flag,
                                                 vdata));
    if (!vbuff) {
        ERRORF(reporter, "vbuff is null.");
        return;
    }

    uint32_t resultPx[kScreenSize * kScreenSize];

    for (ScissorState scissorState : {ScissorState::kEnabled, ScissorState::kDisabled}) {
        rtc->clear(nullptr, 0xbaaaaaad, true);
        rtc->priv().testingOnly_addDrawOp(
            skstd::make_unique<GrPipelineDynamicStateTestOp>(scissorState, vbuff));
        rtc->readPixels(SkImageInfo::Make(kScreenSize, kScreenSize,
                                          kRGBA_8888_SkColorType, kPremul_SkAlphaType),
                        resultPx, 4 * kScreenSize, 0, 0, 0);
        for (int y = 0; y < kScreenSize; ++y) {
            for (int x = 0; x < kScreenSize; ++x) {
                int expectedColorIdx;
                if (ScissorState::kEnabled == scissorState) {
                    expectedColorIdx = (x < kScreenSplitX ? 0 : 2) + (y < kScreenSplitY ? 0 : 1);
                } else {
                    expectedColorIdx = kNumMeshes - 1;
                }
                uint32_t expected = kMeshColors[expectedColorIdx];
                uint32_t actual = resultPx[y * kScreenSize + x];
                if (expected != actual) {
                    ERRORF(reporter, "[scissor=%s] pixel (%i,%i): got 0x%x expected 0x%x",
                           ScissorState::kEnabled == scissorState ? "enabled" : "disabled", x, y,
                           actual, expected);
                    return;
                }
            }
        }
    }
}
Пример #12
0
void *
uthread_alloc(task_t task, thread_t thread, int noinherit)
{
	proc_t p;
	uthread_t uth;
	uthread_t uth_parent;
	void *ut;

	if (!uthread_zone_inited)
		uthread_zone_init();

	ut = (void *)zalloc(uthread_zone);
	bzero(ut, sizeof(struct uthread));

	p = (proc_t) get_bsdtask_info(task);
	uth = (uthread_t)ut;
	uth->uu_kwe.kwe_uth = uth;

	/*
	 * Thread inherits credential from the creating thread, if both
	 * are in the same task.
	 *
	 * If the creating thread has no credential or is from another
	 * task we can leave the new thread credential NULL.  If it needs
	 * one later, it will be lazily assigned from the task's process.
	 */
	uth_parent = (uthread_t)get_bsdthread_info(current_thread());
	if ((noinherit == 0) && task == current_task() && 
	    uth_parent != NULL &&
	    IS_VALID_CRED(uth_parent->uu_ucred)) {
		/*
		 * XXX The new thread is, in theory, being created in context
		 * XXX of parent thread, so a direct reference to the parent
		 * XXX is OK.
		 */
		kauth_cred_ref(uth_parent->uu_ucred);
		uth->uu_ucred = uth_parent->uu_ucred;
		/* the credential we just inherited is an assumed credential */
		if (uth_parent->uu_flag & UT_SETUID)
			uth->uu_flag |= UT_SETUID;
	} else {
		/* sometimes workqueue threads are created out task context */
		if ((task != kernel_task) && (p != PROC_NULL))
			uth->uu_ucred = kauth_cred_proc_ref(p);
		else
			uth->uu_ucred = NOCRED;
	}

	
	if ((task != kernel_task) && p) {
		
		proc_lock(p);
		if (noinherit != 0) {
			/* workq threads will not inherit masks */
			uth->uu_sigmask = ~workq_threadmask;
		} else if (uth_parent) {
			if (uth_parent->uu_flag & UT_SAS_OLDMASK)
				uth->uu_sigmask = uth_parent->uu_oldmask;
			else
				uth->uu_sigmask = uth_parent->uu_sigmask;
		}
		uth->uu_context.vc_thread = thread;
		TAILQ_INSERT_TAIL(&p->p_uthlist, uth, uu_list);
		proc_unlock(p);

#if CONFIG_DTRACE
		if (p->p_dtrace_ptss_pages != NULL) {
			uth->t_dtrace_scratch = dtrace_ptss_claim_entry(p);
		}
#endif
	}

	return (ut);
}
Пример #13
0
/*
 * forkproc
 *
 * Description:	Create a new process structure, given a parent process
 *		structure.
 *
 * Parameters:	parent_proc		The parent process
 *
 * Returns:	!NULL			The new process structure
 *		NULL			Error (insufficient free memory)
 *
 * Note:	When successful, the newly created process structure is
 *		partially initialized; if a caller needs to deconstruct the
 *		returned structure, they must call forkproc_free() to do so.
 */
proc_t
forkproc(proc_t parent_proc)
{
	proc_t child_proc;	/* Our new process */
	static int nextpid = 0, pidwrap = 0, nextpidversion = 0;
	static uint64_t nextuniqueid = 0;
	int error = 0;
	struct session *sessp;
	uthread_t parent_uthread = (uthread_t)get_bsdthread_info(current_thread());

	MALLOC_ZONE(child_proc, proc_t , sizeof *child_proc, M_PROC, M_WAITOK);
	if (child_proc == NULL) {
		printf("forkproc: M_PROC zone exhausted\n");
		goto bad;
	}
	/* zero it out as we need to insert in hash */
	bzero(child_proc, sizeof *child_proc);

	MALLOC_ZONE(child_proc->p_stats, struct pstats *,
			sizeof *child_proc->p_stats, M_PSTATS, M_WAITOK);
	if (child_proc->p_stats == NULL) {
		printf("forkproc: M_SUBPROC zone exhausted (p_stats)\n");
		FREE_ZONE(child_proc, sizeof *child_proc, M_PROC);
		child_proc = NULL;
		goto bad;
	}
	MALLOC_ZONE(child_proc->p_sigacts, struct sigacts *,
			sizeof *child_proc->p_sigacts, M_SIGACTS, M_WAITOK);
	if (child_proc->p_sigacts == NULL) {
		printf("forkproc: M_SUBPROC zone exhausted (p_sigacts)\n");
		FREE_ZONE(child_proc->p_stats, sizeof *child_proc->p_stats, M_PSTATS);
		FREE_ZONE(child_proc, sizeof *child_proc, M_PROC);
		child_proc = NULL;
		goto bad;
	}

	/* allocate a callout for use by interval timers */
	child_proc->p_rcall = thread_call_allocate((thread_call_func_t)realitexpire, child_proc);
	if (child_proc->p_rcall == NULL) {
		FREE_ZONE(child_proc->p_sigacts, sizeof *child_proc->p_sigacts, M_SIGACTS);
		FREE_ZONE(child_proc->p_stats, sizeof *child_proc->p_stats, M_PSTATS);
		FREE_ZONE(child_proc, sizeof *child_proc, M_PROC);
		child_proc = NULL;
		goto bad;
	}


	/*
	 * Find an unused PID.  
	 */

	proc_list_lock();

	nextpid++;
retry:
	/*
	 * If the process ID prototype has wrapped around,
	 * restart somewhat above 0, as the low-numbered procs
	 * tend to include daemons that don't exit.
	 */
	if (nextpid >= PID_MAX) {
		nextpid = 100;
		pidwrap = 1;
	}
	if (pidwrap != 0) {

		/* if the pid stays in hash both for zombie and runniing state */
		if  (pfind_locked(nextpid) != PROC_NULL) {
			nextpid++;
			goto retry;
		}

		if (pgfind_internal(nextpid) != PGRP_NULL) {
			nextpid++;
			goto retry;
		}	
		if (session_find_internal(nextpid) != SESSION_NULL) {
			nextpid++;
			goto retry;
		}	
	}
	nprocs++;
	child_proc->p_pid = nextpid;
	child_proc->p_idversion = nextpidversion++;
	/* kernel process is handcrafted and not from fork, so start from 1 */
	child_proc->p_uniqueid = ++nextuniqueid;
#if 1
	if (child_proc->p_pid != 0) {
		if (pfind_locked(child_proc->p_pid) != PROC_NULL)
			panic("proc in the list already\n");
	}
#endif
	/* Insert in the hash */
	child_proc->p_listflag |= (P_LIST_INHASH | P_LIST_INCREATE);
	LIST_INSERT_HEAD(PIDHASH(child_proc->p_pid), child_proc, p_hash);
	proc_list_unlock();


	/*
	 * We've identified the PID we are going to use; initialize the new
	 * process structure.
	 */
	child_proc->p_stat = SIDL;
	child_proc->p_pgrpid = PGRPID_DEAD;

	/*
	 * The zero'ing of the proc was at the allocation time due to need
	 * for insertion to hash.  Copy the section that is to be copied
	 * directly from the parent.
	 */
	bcopy(&parent_proc->p_startcopy, &child_proc->p_startcopy,
	    (unsigned) ((caddr_t)&child_proc->p_endcopy - (caddr_t)&child_proc->p_startcopy));

	/*
	 * Some flags are inherited from the parent.
	 * Duplicate sub-structures as needed.
	 * Increase reference counts on shared objects.
	 * The p_stats and p_sigacts substructs are set in vm_fork.
	 */
	child_proc->p_flag = (parent_proc->p_flag & (P_LP64 | P_TRANSLATED | P_AFFINITY | P_DISABLE_ASLR));
	if (parent_proc->p_flag & P_PROFIL)
		startprofclock(child_proc);
	/*
	 * Note that if the current thread has an assumed identity, this
	 * credential will be granted to the new process.
	 */
	child_proc->p_ucred = kauth_cred_get_with_ref();
	/* update cred on proc */
	PROC_UPDATE_CREDS_ONPROC(child_proc);
	/* update audit session proc count */
	AUDIT_SESSION_PROCNEW(child_proc);

#if CONFIG_FINE_LOCK_GROUPS
	lck_mtx_init(&child_proc->p_mlock, proc_mlock_grp, proc_lck_attr);
	lck_mtx_init(&child_proc->p_fdmlock, proc_fdmlock_grp, proc_lck_attr);
#if CONFIG_DTRACE
	lck_mtx_init(&child_proc->p_dtrace_sprlock, proc_lck_grp, proc_lck_attr);
#endif
	lck_spin_init(&child_proc->p_slock, proc_slock_grp, proc_lck_attr);
#else /* !CONFIG_FINE_LOCK_GROUPS */
	lck_mtx_init(&child_proc->p_mlock, proc_lck_grp, proc_lck_attr);
	lck_mtx_init(&child_proc->p_fdmlock, proc_lck_grp, proc_lck_attr);
#if CONFIG_DTRACE
	lck_mtx_init(&child_proc->p_dtrace_sprlock, proc_lck_grp, proc_lck_attr);
#endif
	lck_spin_init(&child_proc->p_slock, proc_lck_grp, proc_lck_attr);
#endif /* !CONFIG_FINE_LOCK_GROUPS */
	klist_init(&child_proc->p_klist);

	if (child_proc->p_textvp != NULLVP) {
		/* bump references to the text vnode */
		/* Need to hold iocount across the ref call */
		if (vnode_getwithref(child_proc->p_textvp) == 0) {
			error = vnode_ref(child_proc->p_textvp);
			vnode_put(child_proc->p_textvp);
			if (error != 0)
				child_proc->p_textvp = NULLVP;
		}
	}

	/*
	 * Copy the parents per process open file table to the child; if
	 * there is a per-thread current working directory, set the childs
	 * per-process current working directory to that instead of the
	 * parents.
	 *
	 * XXX may fail to copy descriptors to child
	 */
	child_proc->p_fd = fdcopy(parent_proc, parent_uthread->uu_cdir);

#if SYSV_SHM
	if (parent_proc->vm_shm) {
		/* XXX may fail to attach shm to child */
		(void)shmfork(parent_proc, child_proc);
	}
#endif
	/*
	 * inherit the limit structure to child
	 */
	proc_limitfork(parent_proc, child_proc);

	if (child_proc->p_limit->pl_rlimit[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) {
		uint64_t rlim_cur = child_proc->p_limit->pl_rlimit[RLIMIT_CPU].rlim_cur;
		child_proc->p_rlim_cpu.tv_sec = (rlim_cur > __INT_MAX__) ? __INT_MAX__ : rlim_cur;
	}

	/* Intialize new process stats, including start time */
	/* <rdar://6640543> non-zeroed portion contains garbage AFAICT */
	bzero(&child_proc->p_stats->pstat_startzero,
	    (unsigned) ((caddr_t)&child_proc->p_stats->pstat_endzero -
	    (caddr_t)&child_proc->p_stats->pstat_startzero));
	bzero(&child_proc->p_stats->user_p_prof, sizeof(struct user_uprof));
	microtime(&child_proc->p_start);
	child_proc->p_stats->p_start = child_proc->p_start;     /* for compat */

	if (parent_proc->p_sigacts != NULL)
		(void)memcpy(child_proc->p_sigacts,
				parent_proc->p_sigacts, sizeof *child_proc->p_sigacts);
	else
		(void)memset(child_proc->p_sigacts, 0, sizeof *child_proc->p_sigacts);

	sessp = proc_session(parent_proc);
	if (sessp->s_ttyvp != NULL && parent_proc->p_flag & P_CONTROLT)
		OSBitOrAtomic(P_CONTROLT, &child_proc->p_flag);
	session_rele(sessp);

	/*
	 * block all signals to reach the process.
	 * no transition race should be occuring with the child yet,
	 * but indicate that the process is in (the creation) transition.
	 */
	proc_signalstart(child_proc, 0);
	proc_transstart(child_proc, 0);

	child_proc->p_pcaction = (parent_proc->p_pcaction) & P_PCMAX;
	TAILQ_INIT(&child_proc->p_uthlist);
	TAILQ_INIT(&child_proc->p_aio_activeq);
	TAILQ_INIT(&child_proc->p_aio_doneq);

	/* Inherit the parent flags for code sign */
	child_proc->p_csflags = (parent_proc->p_csflags & ~CS_KILLED);

	/*
	 * All processes have work queue locks; cleaned up by
	 * reap_child_locked()
	 */
	workqueue_init_lock(child_proc);

	/*
	 * Copy work queue information
	 *
	 * Note: This should probably only happen in the case where we are
	 *	creating a child that is a copy of the parent; since this
	 *	routine is called in the non-duplication case of vfork()
	 *	or posix_spawn(), then this information should likely not
	 *	be duplicated.
	 *
	 * <rdar://6640553> Work queue pointers that no longer point to code
	 */
	child_proc->p_wqthread = parent_proc->p_wqthread;
	child_proc->p_threadstart = parent_proc->p_threadstart;
	child_proc->p_pthsize = parent_proc->p_pthsize;
	child_proc->p_targconc = parent_proc->p_targconc;
	if ((parent_proc->p_lflag & P_LREGISTER) != 0) {
		child_proc->p_lflag |= P_LREGISTER;
	}
	child_proc->p_dispatchqueue_offset = parent_proc->p_dispatchqueue_offset;
#if PSYNCH
	pth_proc_hashinit(child_proc);
#endif /* PSYNCH */

#if CONFIG_LCTX
	child_proc->p_lctx = NULL;
	/* Add new process to login context (if any). */
	if (parent_proc->p_lctx != NULL) {
		/*
		 * <rdar://6640564> This should probably be delayed in the
		 * vfork() or posix_spawn() cases.
		 */
		LCTX_LOCK(parent_proc->p_lctx);
		enterlctx(child_proc, parent_proc->p_lctx, 0);
	}
#endif

bad:
	return(child_proc);
}
Пример #14
0
//=============================================================================
// Build Header
//-----------------------------------------------------------------------------
// RFC 2616 / 6 Response (Header)
//
//   The first line of a Response message is the Status-Line, consisting
//   of the protocol version followed by a numeric status code and its
//   associated textual phrase, with each element separated by SP
//   characters. No CR or LF is allowed except in the final CRLF sequence.
//
//	Response       =Status-Line		; generated by SendHeader
//			*(( general-header
//			 | response-header
//			 | entity-header ) CRLF)
//			 CRLF			; generated by SendHeader
//			 [ message-body ]	; by HOOK Handling Loop or Sendfile
//
//	Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF ; generated by SendHeader
//
//	general-header = Cache-Control             ; not implemented
//			| Connection               ; implemented
//			| Date                     ; implemented
//			| Pragma                   ; not implemented
//			| Trailer                  ; not implemented
//			| Transfer-Encoding        ; not implemented
//			| Upgrade                  ; not implemented
//			| Via                      ; not implemented
//			| Warning                  ; not implemented
//
//	response-header = Accept-Ranges          ; not implemented
//			| Age                     ; not implemented
//			| ETag                    ; not implemented
//			| Location                ; implemented (redirection / Object moved)
//			| Proxy-Authenticate      ; not implemented
//			| Retry-After             ; not implemented
//			| Server                  ; implemented
//			| Vary                    ; not implemented
//			| WWW-Authenticate        ; implemented (by mod_auth and SendHeader)
//
//	entity-header  = Allow                    ; not implemented
//			| Content-Encoding         ; not implemented
//			| Content-Language         ; not implemented
//			| Content-Length           ; implemented
//			| Content-Location         ; not implemented
//			| Content-MD5              ; not implemented
//			| Content-Range            ; not implemented
//			| Content-Type             ; implemented
//			| Expires                  ; not implemented
//			| Last-Modified            ; implemented for static files
//			| extension-header
//
//				extension-header = message-header
//=============================================================================
std::string CyhookHandler::BuildHeader(bool cache) {
	std::string result = "";

	const char *responseString = "";
	const char *infoString = 0;

	// get Info Index
	for (unsigned int i = 0; i < (sizeof(httpResponseNames)
			/ sizeof(httpResponseNames[0])); i++)
		if (httpResponseNames[i].type == httpStatus) {
			responseString = httpResponseNames[i].name;
			infoString = httpResponseNames[i].info;
			break;
		}
	// print Status-line
	result = string_printf(HTTP_PROTOCOL " %d %s\r\nContent-Type: %s\r\n",httpStatus, responseString, ResponseMimeType.c_str());
	log_level_printf(2, "Respose: HTTP/1.1 %d %s\r\nContent-Type: %s\r\n",
			httpStatus, responseString, ResponseMimeType.c_str());

	switch (httpStatus) {
	case HTTP_UNAUTHORIZED:
		result += "WWW-Authenticate: Basic realm=\"";
		result += AUTH_NAME_MSG "\r\n";
		break;

	case HTTP_MOVED_TEMPORARILY:
	case HTTP_MOVED_PERMANENTLY:
		// Status HTTP_*_TEMPORARILY (redirection)
		result += string_printf("Location: %s\r\n", NewURL.c_str());
		// NO break HERE !!!

	default:
		time_t timer = time(0);
		char timeStr[80];
		// cache
		if (!cache && (HookVarList["CacheCategory"]).empty())
			result += "Cache-Control: no-cache\r\n";
		else {
			time_t x_time = time(NULL);
			struct tm *ptm = gmtime(&x_time);
			ptm->tm_mday += 1;
			x_time = mktime(ptm);
			strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&x_time));
			result += string_printf("Expires: %s\r\n", timeStr);
		}
		result += "Server: " WEBSERVERNAME "\r\n";
		// actual date
		strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
		result += string_printf("Date: %s\r\n", timeStr);
		// connection type
#ifdef Y_CONFIG_FEATURE_KEEP_ALIVE
		if(keep_alive)
		result += "Connection: keep-alive\r\n";
		else
		result += "Connection: close\r\n";
#else
		result += "Connection: close\r\n";
#endif
		// gzipped ?
		if (UrlData["fileext"] == "gz")
			result += "Content-Encoding: gzip\r\n";
		// content-len, last-modified
		if (httpStatus == HTTP_NOT_MODIFIED || httpStatus == HTTP_NOT_FOUND)
			result += "Content-Length: 0\r\n";
		else if (GetContentLength() > 0) {
			time_t mod_time = time(NULL);
			if (LastModified != (time_t) - 1)
				mod_time = LastModified;

			strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&mod_time));
			result += string_printf(
					"Last-Modified: %s\r\nContent-Length: %ld\r\n", timeStr,
					GetContentLength());
		}
		result += "\r\n"; // End of Header
		break;
	}

	// Body
	if (Method != M_HEAD)
		switch (httpStatus) {
		case HTTP_OK:
		case HTTP_NOT_MODIFIED:
		case HTTP_CONTINUE:
		case HTTP_ACCEPTED:
		case HTTP_NO_CONTENT:
		case HTTP_NOT_FOUND:
		case HTTP_INTERNAL_SERVER_ERROR:
			break;

		case HTTP_MOVED_TEMPORARILY:
		case HTTP_MOVED_PERMANENTLY:
			result += "<html><head><title>Object moved</title></head><body>";
			result
					+= string_printf(
							"302 : Object moved.<br/>If you dont get redirected click <a href=\"%s\">here</a></body></html>\n",
							NewURL.c_str());
			break;

		default:
			// Error pages
			break;
		}
	return result;
}
Пример #15
0
    } while (bytestream2_get_bytes_left(&s->gb) > 0);

    memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE);

    *got_frame = 1;
    if ((ret = av_frame_ref(data, s->frame)) < 0)
        return ret;

    return buf_size;
}

static av_cold int decode_end(AVCodecContext *avctx)
{
    AnmContext *s = avctx->priv_data;

    av_frame_free(&s->frame);
    return 0;
}

AVCodec ff_anm_decoder = {
    .name           = "anm",
    .long_name      = NULL_IF_CONFIG_SMALL("Deluxe Paint Animation"),
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_ANM,
    .priv_data_size = sizeof(AnmContext),
    .init           = decode_init,
    .close          = decode_end,
    .decode         = decode_frame,
    .capabilities   = CODEC_CAP_DR1,
};
Пример #16
0
int HaiCrypt_Clone(HaiCrypt_Handle hhcSrc, HaiCrypt_CryptoDir tx, HaiCrypt_Handle *phhc)
{
    hcrypt_Session *cryptoSrc = (hcrypt_Session *)hhcSrc;
    hcrypt_Session *cryptoClone;
    unsigned char *mem_buf;
    size_t mem_siz, inbuf_siz;

    *phhc = NULL;

    ASSERT(NULL != hhcSrc);

    /* 
     * If cipher has no special input buffer alignment requirement,
     * handle it in the crypto session.
     */
    inbuf_siz = cryptoSrc->inbuf_siz ;	

    /* Allocate crypto session control struct */
    mem_siz = sizeof(hcrypt_Session)	// structure
        + inbuf_siz;

    cryptoClone = malloc(mem_siz);
    if (NULL == cryptoClone){	
        HCRYPT_LOG(LOG_ERR, "%s\n", "malloc failed");
        return(-1);
    }
    mem_buf = (unsigned char *)cryptoClone;
    mem_buf += sizeof(*cryptoClone);
    memset(cryptoClone, 0, sizeof(*cryptoClone));
    memcpy(cryptoClone, cryptoSrc, sizeof(*cryptoClone));

    if (inbuf_siz) {
        cryptoClone->inbuf = mem_buf;
        mem_buf += inbuf_siz;
    }
    timerclear(&cryptoClone->km.tx_last);

    /* Adjust pointers  pointing into cryproSrc after copy
       msg_info adn ciphers are extern statics so this is ok*/
    cryptoClone->ctx_pair[0].alt = &cryptoClone->ctx_pair[1];
    cryptoClone->ctx_pair[1].alt = &cryptoClone->ctx_pair[0];

    /* create a new cipher (OpenSSL) context */
    cryptoClone->cipher_data = cryptoClone->cipher->open(cryptoClone->cfg.data_max_len);
    if (NULL == cryptoClone->cipher_data) {
        //shred
        free(cryptoClone);
        return(-1);
    }
    if (tx) { /* Sender */
        hcrypt_Ctx *ctx = cryptoClone->ctx = &cryptoClone->ctx_pair[0];

        cryptoClone->ctx_pair[0].flags |= HCRYPT_CTX_F_ENCRYPT;
        cryptoClone->ctx_pair[1].flags |= HCRYPT_CTX_F_ENCRYPT;

        /* Set SEK in cipher */
        if (cryptoClone->cipher->setkey(cryptoClone->cipher_data, ctx, ctx->sek, ctx->sek_len)) {
            HCRYPT_LOG(LOG_ERR, "cipher setkey(sek[%zd]) failed\n", ctx->sek_len);
            return(-1);
        }
        ctx->status = HCRYPT_CTX_S_ACTIVE;
    } else { /* Receiver */

        /* Configure contexts */
        if (hcryptCtx_Rx_Init(cryptoClone, &cryptoClone->ctx_pair[0], NULL)
                ||  hcryptCtx_Rx_Init(cryptoClone, &cryptoClone->ctx_pair[1], NULL)) {
            free(cryptoClone);
            return(-1);
        }

        /* Clear salt to force later regeneration of KEK as AES decrypting key,
           copyed one is encrypting key */
        cryptoClone->ctx_pair[0].flags &= ~HCRYPT_CTX_F_ENCRYPT;
        cryptoClone->ctx_pair[1].flags &= ~HCRYPT_CTX_F_ENCRYPT;
        memset(cryptoClone->ctx_pair[0].salt, 0, sizeof(cryptoClone->ctx_pair[0].salt));
        cryptoClone->ctx_pair[0].salt_len = 0;
    }

    *phhc = (void *)cryptoClone;
    return(0);
}
Пример #17
0
int main(int argc, char *argv[]){
  
  char DFin_location[256];
  DFin_location = argv[1] ;
  char DFout_location[256] argv[2];
  char AnaFile[256] = argv[3] ;
  char SimFile[256] = argv[4] ;
  int TriggerBucket = atoi(argv[5]);
  int RUN = atoi(argv[5]);

  std::cout << argv[1] << std::endl;  
  std::cout << DFin_location << std::endl;

  return;



  //here goes the first file
  TChain * DFinput = new TChain("Telescope");
  DFinput->Add(DFin_location);

  unsigned int Event_in;
  int roc_in;
  int col_in,row_in,vcal_in;
  float flux_in;
  double pulseHeight_in;
  std::cout << roc_in << std::endl;

  DFinput->SetBranchStatus("*",false);

  DFinput->SetBranchStatus("Event",true);
  DFinput->SetBranchStatus("roc",true);
  DFinput->SetBranchStatus("pulseHeight",true);
  DFinput->SetBranchStatus("vcal",true);
  DFinput->SetBranchStatus("col",true);
  DFinput->SetBranchStatus("row",true);
  DFinput->SetBranchStatus("flux",true);

  DFinput->SetBranchAddress("Event",&Event_in);
  DFinput->SetBranchAddress("roc",&roc_in);
  DFinput->SetBranchAddress("row",&row_in);
  DFinput->SetBranchAddress("col",&col_in);
  DFinput->SetBranchAddress("vcal",&vcal_in);
  DFinput->SetBranchAddress("flux",&flux_in);
  DFinput->SetBranchAddress("pulseHeight",&pulseHeight_in);

  std::cout << "Loaded DF input file from: " << DFin_location << std::endl;


  //here goes the second file
  TChain * DFoutput = new TChain("hitTree");
  DFoutput->Add(DFout_location);

  unsigned int event_number;
  int roc_out,col_out,row_out,vcal_out;
  double pulseHeight_out;
  long TS_out;


  DFoutput->SetBranchStatus("*",false);

  DFoutput->SetBranchStatus("event_number",true);
  DFoutput->SetBranchStatus("TS",true);
  DFoutput->SetBranchStatus("roc",true);
  DFoutput->SetBranchStatus("col",true);
  DFoutput->SetBranchStatus("row",true);
  DFoutput->SetBranchStatus("vcal",true);
  DFoutput->SetBranchStatus("pulseHeight",true);


  DFoutput->SetBranchAddress("event_number",&event_number);
  DFoutput->SetBranchAddress("TS",&TS_out);
  DFoutput->SetBranchAddress("roc",&roc_out);
  DFoutput->SetBranchAddress("col",&col_out);
  DFoutput->SetBranchAddress("row",&row_out);
  DFoutput->SetBranchAddress("vcal",&vcal_out);
  DFoutput->SetBranchAddress("pulseHeight",&pulseHeight_out);

  std::cout << "Loaded DF output file from: " << DFout_location << std::endl;

  //here come the analysis files
  //comes later


  //here come the original run data files



  //Now we make some histograms we want to compare


  TCanvas * c1 = new TCanvas("Comparison","Comparison",1200,1200);
  // gStyle->SetOptStat(0);
  c1->Divide(2,2);

  c1->cd(1);



  TH1I * Pixels_per_Event_in = new TH1I("Pixels per Event", "DataFlow input",20,0,20);
  unsigned int temp_evtn=-1;

  int ROC_DUT = 3;
  int nhits = 0;
  std::cout << "Total Entries input : " <<  DFinput->GetEntries() << std::endl;
  std::cout << "Total Entries output: " <<  DFoutput->GetEntries() << std::endl;
  long int maxEntries = DFinput->GetEntries();
  for(int i = 0; i < maxEntries; ++i)
    //for(int i = 0; i < 5000000; ++i)
    {
      DFinput->GetEntry(i);
      if(i%100000 == 0) std::cout << setprecision(2) << "Entry: " << i << "    " << (double)(i*100)/maxEntries << "%" << std::endl;
      //std::cout << "Entry: " << i << "Event " << Event_in << "ROC " << roc_in << " " << row_in << "|" << col_in << std::endl;
      temp_evtn = Event_in;
      if(Event_in%588 == TriggerBucket)
	{
	  if(roc_in == -1)
	    {
	      Pixels_per_Event_in->Fill(0);
	      continue;
	    }
	  else
	    {
	      while(Event_in == temp_evtn)
		{
		  // std::cout << "I'm in the loop. ROC " << roc_in << std::endl;
		  if(roc_in == ROC_DUT)
		    {
		      ++nhits;
		    }
		  ++i;
		  if(i == maxEntries) break;
		  DFinput->GetEntry(i);
		  //	      std::cout << "Entry: " << i << "Event " << Event_in << "ROC " << roc_in <<   std::endl;
		}
	    }
	  --i;
	  Pixels_per_Event_in->Fill(nhits);
	  //	  std::cout << "Found event with " << nhits << "Hits on ROC " << ROC_DUT << std::endl;
	  nhits = 0;
	}
    }

    
  Pixels_per_Event_in->Draw();
  c1->Update();
  //second histogram
  std::cout << "Second histogramm" << std::endl;

  TH1I * Pixels_per_Event_out = new TH1I("Pixels per Event","DataFlow output",20,0,20);
  for(int i = 0; i < DFoutput->GetEntries();++i)
    {
      DFoutput->GetEntry(i);
      //if(i%100 == 0) std::cout << "Entry: " << i << "Event " << event_number << "ROC " << roc_out <<   std::endl;
      //      std::cout << "Entry: " << i << "Event " << event_number << "ROC " << roc_out <<   std::endl;
      temp_evtn = event_number;
      if(roc_out == -1)
	{
	  nhits = 0;
	 Pixels_per_Event_out->Fill(nhits);
	  continue;
	}
      else
	{
	  while(event_number == temp_evtn)
	    {
	      // std::cout << "I'm in the loop. ROC " << roc_in << std::endl;
	      if(roc_out == ROC_DUT)
		{
		  ++nhits;
		}
	      ++i;
	      if(i == DFoutput->GetEntries()) break;
	      DFoutput->GetEntry(i);
	      // std::cout << "Entry: " << i << "Event " << event_number << "ROC " << roc_out <<   std::endl;

	    }

	  --i;
	  Pixels_per_Event_out->Fill(nhits);
	  //	  std::cout << "Found event with " << nhits << "Hits on ROC " << ROC_DUT << std::endl;
	  nhits = 0;

	}

    }

  c1->cd(2);
  Pixels_per_Event_out->Draw();
  c1->Update();

  //picking up the 3rd histogram
  TFile * simAnaFile = new TFile(SimFile,"READ");
  if ( simAnaFile->IsOpen()) printf("File opened successfully\n");				    
  
				    
  char histname[256];
  sprintf(histname,"MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d%i",ROC_DUT);

  std::cout << histname << std::endl;

  TH1I * Hits_per_Event_sim;

  Hits_per_Event_sim=(TH1I*)simAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d3");
  
  c1->cd(3);
 
  Hits_per_Event_sim->GetXaxis()->SetRangeUser(0,20);
 
  Hits_per_Event_sim->SetTitle("Analysis of simulated data");
 
  Hits_per_Event_sim->Draw();

  c1->Update();


  //pick up the last "original" histogram

  TFile * realAnaFile = new TFile(AnaFile,"READ");
  if ( realAnaFile->IsOpen()) printf("File opened successfully\n");				    
  
				    
  sprintf(histname,"MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d%i",ROC_DUT);

  TH1I * Hits_per_Event_ana;


  Hits_per_Event_ana=(TH1I*)realAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d3");
  
  c1->cd(4);
  Hits_per_Event_ana->GetXaxis()->SetRangeUser(0,20);
  Hits_per_Event_ana->SetTitle("Analysis of measured data");
  Hits_per_Event_ana->Draw();

  c1->Update();

  char txt[256];
  sprintf(txt,"RUN%i_PixelsPerEvent.pdf",RUN);
  c1->SaveAs(txt);

  ///now for future references I'll try everything in one plot

  TCanvas * c2 = new TCanvas("c2","c2",600,600);
  c2->cd();
  //  gStyle->SetOptStat(0);

  double norm = 100.;
  std::cout << Pixels_per_Event_in->Integral() << std::endl;
  //Pixels_per_Event_out->GetXaxis()->SetLimits(0, norm);
  Pixels_per_Event_out->Scale(norm/Pixels_per_Event_out->Integral());
  Pixels_per_Event_out->SetMaximum(100);
  Pixels_per_Event_out->SetLineColor(2);
  Pixels_per_Event_out->SetLineWidth(3);
  Pixels_per_Event_out->Draw("SAME");

  Hits_per_Event_sim->Scale(norm/Hits_per_Event_sim->Integral());
  Hits_per_Event_sim->SetMaximum(100);
  Hits_per_Event_sim->SetLineColor(3);
  Hits_per_Event_sim->SetLineWidth(3);
  Hits_per_Event_sim->Draw("SAME");

  Hits_per_Event_ana->Scale(norm/Hits_per_Event_ana->Integral());
  Hits_per_Event_ana->SetMaximum(100);
  Hits_per_Event_ana->SetLineColor(4);
  Hits_per_Event_ana->SetLineWidth(3);
  Hits_per_Event_ana->Draw("SAME");

  Pixels_per_Event_in->Scale(norm/Pixels_per_Event_in->Integral());
  Pixels_per_Event_in->SetMaximum(100);
  Pixels_per_Event_in->SetLineColor(1);
  Pixels_per_Event_in->SetLineWidth(3);
  Pixels_per_Event_in->Draw("SAME");

  TLegend * leg1 = new TLegend(0.75,0.9,0.35,0.75);
  leg1->AddEntry(Pixels_per_Event_in,"DataFlow input","L");
  leg1->AddEntry(Pixels_per_Event_out,"DataFlow output","L");
  leg1->AddEntry(Hits_per_Event_sim,"Analysis of simulated data","L");
  leg1->AddEntry(Hits_per_Event_ana,"Analysis of measured data","L");


  leg1->Draw();


  c2->Update();


  sprintf(txt,"RUN%i_PixelsPerEventNorm.pdf",RUN);
  c2->SaveAs(txt);

  /*
   *  Now some more plots
   */

  //hit map
  //simulated data
  TCanvas * c3 = new TCanvas("c3","c3",1200,600);
  c3->Divide(2,1);
  c3->cd(1);
  
  sprintf(histname,"MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d%i",ROC_DUT);

  std::cout << histname << std::endl;

  TH2D * Hit_Map_sim;


  Hit_Map_sim=(TH2D*)simAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/hitMap_d3");
  

  Hit_Map_sim->SetTitle("Analysis of simulated data");
  Hit_Map_sim->Draw("COLZ");
  Hit_Map_sim->SetStats(0);
  c3->Update();

  //measured data

  c3->cd(2);

  TH2D * Hit_Map_ana;
  

  Hit_Map_ana=(TH2D*)realAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/hitMap_d3");
  
 
  Hit_Map_ana->GetXaxis()->SetRangeUser(1,50);
  Hit_Map_ana->GetYaxis()->SetRangeUser(1,78);
  Hit_Map_ana->SetTitle("Analysis of measured data");
  Hit_Map_ana->Draw("COLZ");
  Hit_Map_ana->SetStats(0);

  char txt[256];
  sprintf(txt,"RUN%i_HitMap.pdf",RUN);
  c3->SaveAs(txt);


  /*
   *cluster size
   */

  //simulated data 
  TCanvas * c4 = new TCanvas("c4","c4",1200,600);
  c4->Divide(2,1);
  c4->cd(1);
  c4->SetLogy(1);

  sprintf(histname,"MyCMSPixelClusteringProcessor/detector_%i/clustersize_d%i",ROC_DUT,ROC_DUT);

  std::cout << histname << std::endl;

  TH1I * Clustersize_sim;


  Clustersize_sim=(TH1I*)simAnaFile->Get(histname);
  
 
  Clustersize_sim->GetXaxis()->SetRangeUser(0,20);
  Clustersize_sim->SetTitle("Analysis of simulated data");
  Clustersize_sim->Draw();
  c4->Update();

  //measured data
  c4->cd(2);
  c4->SetLogy(1);

  TH1I * Clustersize_ana;
  Clustersize_ana=(TH1I*)realAnaFile->Get(histname);
  
  Clustersize_ana->GetXaxis()->SetRangeUser(0,20);
  Clustersize_ana->SetTitle("Analysis of measured data");
  Clustersize_ana->Draw();
  c4->Update();

  sprintf(txt,"RUN%i_ClusterSize.pdf",RUN);
  c4->SaveAs(txt);
  
  /*
   *number of tracks
   */

  string simTrackFileName(SimFile);
  simTrackFileName = simTrackFileName.replace(simTrackFileName.find("clustering"), sizeof("clustering")-1,"tracks");
 
  char * filename = simTrackFileName.c_str();

  std::cout << filename << std::endl;

  TFile * simTrackFile = new TFile(filename,"READ");
  if ( simTrackFile->IsOpen()) printf("Track file opened successfully\n");				    

  TCanvas * c5 = new TCanvas("c5","c5",1200,600);
  c5->Divide(2,1);
  c5->SetLogy(1);
  c5->cd(1);
  sprintf(histname,"MyEUTelTestFitter/nTrack");
 
  std::cout << histname << std::endl;

  TH1D * NTracks_sim;
  NTracks_sim=(TH1D*)simTrackFile->Get(histname);
  NTracks_sim->SetTitle("Analysis of simulated data");
  NTracks_sim->Draw();
  c5->Update();

  string anaTrackFileName(AnaFile);
  anaTrackFileName = anaTrackFileName.replace(anaTrackFileName.find("clustering"), sizeof("clustering")-1,"tracks");
  char * filename2 = anaTrackFileName.c_str();

  TFile * anaTrackFile = new TFile(filename2,"READ");
  if ( anaTrackFile->IsOpen()) printf("Analysis track file opened successfully\n");				    

  c5->cd(2);
  c5->SetLogy(1);

  TH1D * NTracks_ana;
  NTracks_ana=(TH1D*)anaTrackFile->Get(histname);
  NTracks_ana->SetTitle("Analysis of measured data");
  NTracks_ana->Draw();
  c5->Update();

  sprintf(txt,"RUN%i_NumberOfTracks.pdf",RUN);
  c5->SaveAs(txt);



}//comparison()
Пример #18
0
int HaiCrypt_Create(const HaiCrypt_Cfg *cfg, HaiCrypt_Handle *phhc)
{
    hcrypt_Session *crypto;
    hcrypt_Cipher *cipher;
    unsigned char *mem_buf;
    size_t mem_siz, inbuf_siz;
    int tx;

    *phhc = NULL;

    ASSERT(NULL != cfg);

    HCRYPT_LOG_INIT();
    //Test log
    HCRYPT_LOG(LOG_INFO, "creating crypto context(flags=0x%x)\n", cfg->flags);

    if (!(HAICRYPT_CFG_F_CRYPTO & cfg->flags)) {
        HCRYPT_LOG(LOG_INFO, "no supported flags set (0x%x)\n", cfg->flags);
        return(-1);
    } else if ((16 != cfg->key_len)	/* SEK length */
            &&  (24 != cfg->key_len)
            &&  (32 != cfg->key_len)) {
        HCRYPT_LOG(LOG_ERR, "invalid key length (%zd)\n", cfg->key_len);
        return(-1);
    } else if ((HAICRYPT_SECTYP_PASSPHRASE == cfg->secret.typ)
            &&  ((0 == cfg->secret.len) || (sizeof(cfg->secret.str) < cfg->secret.len))) { /* KEK length */
        HCRYPT_LOG(LOG_ERR, "invalid secret passphrase length (%zd)\n", cfg->secret.len);
        return(-1);
    } else if ((HAICRYPT_SECTYP_PRESHARED == cfg->secret.typ)
            &&  (16 != cfg->key_len)	/* SEK length */
            &&  (24 != cfg->key_len)
            &&  (32 != cfg->key_len)) {
        HCRYPT_LOG(LOG_ERR, "invalid pre-shared secret length (%zd)\n", cfg->secret.len);
        return(-1);
    } else if ((HAICRYPT_SECTYP_PRESHARED == cfg->secret.typ)
            &&  (cfg->key_len > cfg->secret.len)) {
        HCRYPT_LOG(LOG_ERR, "preshared secret length (%zd) smaller than key length (%zd)\n", 
                cfg->secret.len, cfg->key_len);
        return(-1);
    } else if (NULL == cfg->cipher) {
        HCRYPT_LOG(LOG_ERR, "%s\n", "no cipher specified");
        return(-1);
    } else if (0 == cfg->data_max_len) {
        HCRYPT_LOG(LOG_ERR, "%s\n", "no data_max_len specified");
        return(-1);
    }

    cipher = (hcrypt_Cipher *)cfg->cipher;
    tx = HAICRYPT_CFG_F_TX & cfg->flags;
    HCRYPT_PRINTKEY(cfg->secret.str, cfg->secret.len, "cfgkey");

    /* 
     * If cipher has no special input buffer alignment requirement,
     * handle it in the crypto session.
     */
    inbuf_siz = 0;	
    if (NULL == cipher->getinbuf) {
        inbuf_siz = hcryptMsg_PaddedLen(cfg->data_max_len, 128/8);
    }

    /* Allocate crypto session control struct */
    mem_siz = sizeof(hcrypt_Session)	// structure
        + inbuf_siz;

    crypto = malloc(mem_siz);
    if (NULL == crypto){	
        HCRYPT_LOG(LOG_ERR, "%s\n", "malloc failed");
        return(-1);
    }
    mem_buf = (unsigned char *)crypto;
    mem_buf += sizeof(*crypto);
    memset(crypto, 0, sizeof(*crypto));

    if (inbuf_siz) {
        crypto->inbuf = mem_buf;
        crypto->inbuf_siz = inbuf_siz;
    }

    crypto->cipher = cfg->cipher;
    crypto->cfg.data_max_len = cfg->data_max_len;

    /* Setup transport packet info */
    switch (cfg->xport) {
    case HAICRYPT_XPT_STANDALONE:
        crypto->se = HCRYPT_SE_TSUDP;
        crypto->msg_info = hcryptMsg_STA_MsgInfo();
        break;
    case HAICRYPT_XPT_SRT:
        crypto->se = HCRYPT_SE_TSSRT;
        crypto->msg_info = hcryptMsg_SRT_MsgInfo();
        break;
    default:
        HCRYPT_LOG(LOG_ERR, "invalid xport: %d\n", cfg->xport);
        free(crypto);
        return(-1);
    }

    timerclear(&crypto->km.tx_last);
    crypto->km.tx_period.tv_sec  = cfg->km_tx_period_ms / 1000;
    crypto->km.tx_period.tv_usec = (cfg->km_tx_period_ms % 1000) * 1000;

    crypto->km.refresh_rate = cfg->km_refresh_rate_pkt;
    crypto->km.pre_announce = cfg->km_pre_announce_pkt;

    /* Indentify each context */
    crypto->ctx_pair[0].flags = HCRYPT_MSG_F_eSEK | (tx ? HCRYPT_CTX_F_ENCRYPT : 0);
    crypto->ctx_pair[1].flags = HCRYPT_MSG_F_oSEK | (tx ? HCRYPT_CTX_F_ENCRYPT : 0);
    /* Point to each other */
    crypto->ctx_pair[0].alt = &crypto->ctx_pair[1];
    crypto->ctx_pair[1].alt = &crypto->ctx_pair[0];

    crypto->cipher_data = crypto->cipher->open(cfg->data_max_len);
    if (NULL == crypto->cipher_data) {
        free(crypto);
        return(-1);
    }
    if (tx) { /* Encoder */
        /* Configure initial context */
        if (hcryptCtx_Tx_Init(crypto, &crypto->ctx_pair[0], cfg)
                ||  hcryptCtx_Tx_Init(crypto, &crypto->ctx_pair[1], cfg)) {
            free(crypto);
            return(-1);
        }			
        /* Generate keys for first (default) context */
        if (hcryptCtx_Tx_Rekey(crypto, &crypto->ctx_pair[0])) {
            free(crypto);
            return(-1);
        }
        crypto->ctx = &crypto->ctx_pair[0];
        crypto->ctx->flags |= (HCRYPT_CTX_F_ANNOUNCE | HCRYPT_CTX_F_TTSEND);
        crypto->ctx->status = HCRYPT_CTX_S_ACTIVE;
    } else { /* Decoder */
        /* Configure contexts */
        if (hcryptCtx_Rx_Init(crypto, &crypto->ctx_pair[0], cfg)
                ||  hcryptCtx_Rx_Init(crypto, &crypto->ctx_pair[1], cfg)) {
            free(crypto);
            return(-1);
        }
    }

    *phhc = (void *)crypto;
    return(0);
}
Пример #19
0
/* Main Function acting as a client for Image Encode Call*/
XDAS_Int32 main(int argc, char *argv[])
{

    /* File I/O variables */
    FILE *fConfigFile, /**ftestFile, *finFile,*/ *fparamsFile;

#ifdef LINUX
    CMEM_AllocParams memParams;
    memParams.type=CMEM_POOL;
    memParams.flags=CMEM_NONCACHED;
    memParams.alignment=256;
#endif

    char* colorf[]={"YUV422P", "YUV420P", "YUV422P", "YUV422IL", "YUV422IL", "YUV444", "YUV411", "GRAY", "RGB", "YUV420_LINE"};
#ifdef LINUX
    XDAS_Int8 *fname = "../TestVecs/Config/Testvecs.cfg";
#else
    XDAS_Int8 *fname = "..\\..\\Test\\TestVecs\\Config\\Testvecs_ccs.cfg";
#endif
    Int32 lTemp,countConfigSet;
    Int32 retVal;
    Uint32 numAU, totalAU,repeat;
    Uint32 bytesGenerated;
    Uint16 mbSizeX, mbSizeY,mbY;

    char *RefBuffPtr;
    FILE *fp_out;
    FILE *fp_in;
    int processTime = 0, processTimeTotal = 0,algActivateTime =0, algDeactivateTime =0,copctime=0;
    int val,queue_word,queue_num=0,i,k;
    char baseParams[STRING_SIZE];
    int baseParamsOnly;
    int Offset;
    int num_markers;
    IIMGENC1_Fxns            *iimgEncfxns;
    IIMGENC1_Status  imgencStatus;
    IIMGENC1_InArgs imgencInArgs;
    IIMGENC1_OutArgs imgencOutArgs;
    IJPEGENC_Status          status;
    IJPEGENC_InArgs          inArgs;
    IJPEGENC_OutArgs         outArgs;
    unsigned int lTemp1;

    /*Algorithm specific handle */
    IALG_Handle handle;

    /* Input/Output Buffer Descriptor variables */
    XDM1_BufDesc inputBufDesc, outputBufDesc;


#ifdef ENABLE_RMAN // IRES/RMAN Related declarations
    // temp_trace_init();
    IRES_Status iresStatus;
    Int size =0;
    Int scratchId =0;
    Bool result = TRUE;
    IRES_Fxns *resFxns = &JPEGENC_TI_IRES;
    IRESMAN_Edma3ChanParams configParams;
    IRESMAN_VicpParams iresmanConfigParams;
    IRESMAN_AddrSpaceParams addrspaceConfigParams;

    iresStatus = RMAN_init();
    if (IRES_OK != iresStatus) {
        printf("RMAN initialization Failed \n");
        return -1;
    }
    printf("RMAN initialization done \n");

#ifndef LINUX
        /* Call the functions to enable ARM926 FIQ and do some basic
         * setup to AINTC to accept KLD INTC (arm968) interupt in 
         * FIQ pin of Arm926  
         */
        ARM926_enable_FIQ();  /* SWI call to enable interrupts */
        ARM926_INTC_init();  /* Init AINTC */
#endif

    /*
     * Supply initialization information for the RESMAN while registering
     */
    size = sizeof(IRESMAN_VicpParams);

    iresmanConfigParams.baseConfig.allocFxn = RMAN_PARAMS.allocFxn;
    iresmanConfigParams.baseConfig.freeFxn = RMAN_PARAMS.freeFxn;
    iresmanConfigParams.baseConfig.size = size;

    /* Register the VICP protocol/resource manager with the
    *      * generic resource manager */

    iresStatus = RMAN_register(&IRESMAN_VICP2, (IRESMAN_Params *)&iresmanConfigParams);

    if (IRES_OK != iresStatus) {
        printf("VICP Protocol Registration Failed \n");
        return -1;
    }
    printf("VICP Protocol Registration Success \n");
    /*
     *      * Supply initialization information for the EDMA3 RESMAN while registering
     *           */
    size = sizeof(IRESMAN_Edma3ChanParams);

    configParams.baseConfig.allocFxn = RMAN_PARAMS.allocFxn;
    configParams.baseConfig.freeFxn = RMAN_PARAMS.freeFxn;
    configParams.baseConfig.size = size;

    iresStatus = RMAN_register(&IRESMAN_EDMA3CHAN, (IRESMAN_Params *)&configParams);

    if (IRES_OK != iresStatus) {
        printf("EDMA3 Protocol Registration Failed \n");
        return -1;
    }
    printf("EDMA3 Protocol Registration Success \n");

    /** Supply initialization information for the ADDRSPACE RESMAN while registering
    	* */
#if 1
    size = sizeof(IRESMAN_AddrSpaceParams);
    addrspaceConfigParams.baseConfig.allocFxn = RMAN_PARAMS.allocFxn;
    addrspaceConfigParams.baseConfig.freeFxn = RMAN_PARAMS.freeFxn;
    addrspaceConfigParams.baseConfig.size = size;

    iresStatus = RMAN_register(&IRESMAN_ADDRSPACE, (IRESMAN_Params *)&addrspaceConfigParams);

    if (IRES_OK != iresStatus) {
        printf("ADDRSPACE Protocol Registration Failed \n");
        return -1;
    }
#ifdef _DBG_MSG
    printf("ADDRSPACE Protocol Registration Success \n");
#endif
#endif


#endif //IRES/RMAN related code ends here  


#ifdef LINUX
    CMEM_init();

    ExternalGlobalMemPool = ExternalGlobalMemPoolBase = CMEM_alloc(EXTERNAL_DATA_MEM_SIZE,&memParams);
#ifdef ENABLE_RING_BUF_USAGE
    ringbuf = CMEM_alloc(RINGBUFSIZE, &memParams);
#endif
    OrgPictureY_0=CMEM_alloc( (LUMABUF_SIZE*2+ORGBUF_OFFSET), &memParams);
    OrgPictureCb_0=CMEM_alloc((CHROMABUF_SIZE+ORGBUF_OFFSET), &memParams);
    OrgPictureCr_0=CMEM_alloc((CHROMABUF_SIZE+ORGBUF_OFFSET), &memParams);
    media=CMEM_alloc((ENCODED_DATA_BUFFER_SIZE), &memParams);

//#ifdef LINUX
    //      DM350MM_init();
//#endif

    if (argc==2)
    {
        strncpy(baseParams,argv[1],256);
        if (!strcmp(baseParams,"-ext"))
        {
            printf("\n----- Running in extended parameter mode -----\n");
            baseParamsOnly=0;

        }
        else
        {
            printf("Argument  -ext needed to run in  extended param mode\n");
            exit(0);
        }
    }

    else
    {
        printf("\n----- Running in base parameter mode -----\n");
        baseParamsOnly=1;
    }


#else
    baseParamsOnly=0;
#endif


    //memset(ringbuf,0xaa,RINGBUFSIZE );
    memset(media, 0xaa, ENCODED_DATA_BUFFER_SIZE);
    memset(ExternalGlobalMemPool, 0xaa,EXTERNAL_DATA_MEM_SIZE );
    memset(OrgPictureY_0, 0xaa, (LUMABUF_SIZE*2+ORGBUF_OFFSET));
    memset(OrgPictureCb_0, 0xaa, (CHROMABUF_SIZE+ORGBUF_OFFSET));
    memset(OrgPictureCr_0, 0xaa, (CHROMABUF_SIZE+ORGBUF_OFFSET));

    OrgPictureY  = &OrgPictureY_0[ORGBUF_OFFSET];
    OrgPictureCb = &OrgPictureCb_0[ORGBUF_OFFSET];
    OrgPictureCr = &OrgPictureCr_0[ORGBUF_OFFSET];


    /* Open Test Config File   */
    fConfigFile = fopen(fname, "r");

    if (!fConfigFile)
    {
        printf("Couldn't open parameter file %s\n", fname);
        return XDM_EFAIL;
    }


    countConfigSet = 1;         /* Reset countConfigSet value to 1 */

    /* Read the Config File until it reaches the end of file                    */
    while (!feof(fConfigFile))
    {
        /* Read Compliance Checking parameter */
        if (fgets(line, 254, fConfigFile))
        {
            sscanf(line, "%d\n", &testCompliance);
            printf("\nTestcompliance = %d\n",testCompliance);
        } else {
            break;
        }
        /* Read Parameters file name */
        if (fgets(line, 254, fConfigFile))
        {
            sscanf(line, "%s", paramsFile);
            printf("\nParam file = %s\n",paramsFile);
        }
        else
        {
            break;
        }
        /* Read Input file name */
        if (fgets(line, 254, fConfigFile))
        {
            sscanf(line, "%s", inFile);
            printf("\nInput file = %s\n",inFile);
        }
        else
        {
            break;
        }

        /* Read Output/Reference file name */
        if (fgets(line, 254, fConfigFile))
        {
            sscanf(line, "%s", testFile);
            printf("\nOutput file = %s\n",testFile);
        }
        else
        {
            break;
        }

        printf("\n*******************************************");
        printf("\nRead Configuration Set %d", countConfigSet);
        printf("\n*******************************************");
        countConfigSet++;



        fp_out=fopen(testFile,"wb");
        fp_in = fopen(inFile,"rb");


        if ((fp_in == NULL) || (fp_out == NULL))
        {
            printf("'Input/out file cannot be opened\n");
            exit(0);
        }

        /** Set initialization parameters
         * Parameters in structure params are default image encode parameters required by XDM
         * Paraemters in extn_params are parameters specific to jpeg encoder,
         *
         */

        /* Open Parameters file */
        fparamsFile = fopen(paramsFile, "rb");
        //fparamsFile = fopen("Testparams.cfg", "rb");
        if (!fparamsFile)
        {
            printf("\nCouldn't open Parameters file...   %s\n ",
                   paramsFile);
            printf("Exiting for this configuration...\n");
            continue;
        }

        printf("\nParameter file read starts...\n");
        if (readparamfile(fparamsFile,baseParamsOnly) < 0)
        {
            printf("\nSyntax Error in %s\n ", paramsFile);
            printf("Exiting for this configuration...\n");
            continue;
        }

        /* Close Parameters File */
        fclose(fparamsFile);
        if (testCompliance)
        {
            printf("\nRunning in Compliance Mode");
        }
        else
        {
            printf("\nRunning in Output Dump Mode");
        }


        /** Call algorithm creation function
          * See file alg_create.
          * memory allocation functions are called inside alg_malloc file.
          * Modify _ALG_allocMemory in alg_malloc.c to suit the application need (static allocation vs dynamic through malloc())
          */

        if (baseParamsOnly==0)
        {
#ifdef ENABLE_RING_BUF_USAGE
            extn_params.halfBufCB =(XDAS_Void (*)(Uint32, XDAS_Void*))JPEGENC_TI_DM350_HalfBufCB;
            extn_params.halfBufCBarg= (void*)&ring2media;

#else
            extn_params.halfBufCB = (XDAS_Void (*))NULL;
#endif


            extn_params.imgencParams = params;
            extn_params.imgencParams.size = sizeof(IJPEGENC_Params);
        }
        else
        {
            params.size = sizeof(IIMGENC1_Params);
            dynamicParams.size =sizeof(IIMGENC1_DynamicParams);
        }
        if (baseParamsOnly==0)
        {
            if ((handle =  (IALG_Handle)ALG_create (
                               (IALG_Fxns *) &JPEGENC_TI_IJPEGENC,
                               (IALG_Handle) NULL,
                               (IALG_Params *)&extn_params)) == NULL)
            {
                printf("\nFailed to Create Instance... Exiting for this configuration..");
                exit(0);
            }

            printf("\nAlgorithm Instance Creation Done...\n");
        }
        else
        {
            if ((handle =  (IALG_Handle)ALG_create (
                               (IALG_Fxns *) &JPEGENC_TI_IJPEGENC,
                               (IALG_Handle) NULL,
                               (IALG_Params *)&params)) == NULL)
            {
                printf("\nFailed to Create Instance... Exiting for this configuration..");
                exit(0);
            }

            printf("\nAlgorithm Instance Creation Done...\n");
        }



#ifdef ENABLE_RMAN // IRES/RMAN Related code

        /* Create an instance of an algorithm that implements IALG and IRES_Fxns */
        iresStatus = RMAN_assignResources((IALG_Handle)handle, resFxns,scratchId);
        if (IRES_OK != iresStatus) {
            printf("Assign Resource Failed \n");
            result = FALSE;
        }

#endif //IRES/RMAN code ends here.

        /** Set up dynamic parameters (can be changed before each call to jpeg processing)
          * Parameters in structure dynamicParams are default image encode parameters required by XDM
          */
        if (baseParamsOnly==0)
        {
            extn_dynamicParams.imgencDynamicParams = dynamicParams;
            extn_dynamicParams.imgencDynamicParams.size  = sizeof(IJPEGENC_DynamicParams);
            extn_dynamicParams.disableEOI = 0;
            iimgEncfxns = (IIMGENC1_Fxns *)handle->fxns ;
            status.imgencStatus.size= sizeof(IJPEGENC_Status);
        }
        else
        {

            dynamicParams.size           = sizeof(IIMGENC1_DynamicParams);
            iimgEncfxns = (IIMGENC1_Fxns *)handle->fxns ;
            imgencStatus.size= sizeof(IIMGENC1_Status);

        }
        /** Request input and output buffer characteristics by calling control() function
         *  with command XDM_GETBUFINFO
         */


        // Call control function to setup dynamic params
        if (baseParamsOnly==0)
        {
            retVal=iimgEncfxns->control((IIMGENC1_Handle)handle,/*IJPEGENC_SETDEFAULT*/XDM_SETPARAMS,
                                        (IIMGENC1_DynamicParams *)&extn_dynamicParams, (IIMGENC1_Status *)&status);

            if (retVal== XDM_EFAIL) {
                printf("\n Error control SetParams  command1\n");
                exit(0);
            }

            retVal= iimgEncfxns->control((IIMGENC1_Handle)handle,
                                         XDM_GETBUFINFO,
                                         (IIMGENC1_DynamicParams *) &extn_dynamicParams,
                                         (IIMGENC1_Status *)&status);
	    if (retVal== XDM_EFAIL) {
		printf("\n Error control Getbuffinfo  command1\n");
		exit(0);
	     }


            inputBufDesc.numBufs = status.imgencStatus.bufInfo.minNumInBufs;
            Offset = 0;

            for (i=0;i<inputBufDesc.numBufs;i++)
            {
                inputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)inputData +
                                            Offset);
                Offset +=  status.imgencStatus.bufInfo.minInBufSize[i];
                inputBufDesc.descs[i].bufSize = status.imgencStatus.bufInfo.minInBufSize[i];
            }

            outputBufDesc.numBufs = status.imgencStatus.bufInfo.minNumOutBufs;
            Offset = 0;

            for (i=0;i<outputBufDesc.numBufs;i++)
            {
                outputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)outputData +
                                             Offset);
                Offset +=  status.imgencStatus.bufInfo.minOutBufSize[i];
                outputBufDesc.descs[i].bufSize = status.imgencStatus.bufInfo.minOutBufSize[i];

            }


            if (retVal== XDM_EFAIL) {
                printf("\n Error control GetInfo command\n");
                exit(0);
            }

        }
        else
        {
            retVal=iimgEncfxns->control((IIMGENC1_Handle)handle, XDM_SETPARAMS,
                                        (IIMGENC1_DynamicParams *)&dynamicParams, (IIMGENC1_Status *)&imgencStatus);

            if (retVal== XDM_EFAIL) {
                printf("\n Error control SetParams  command1\n");
                exit(0);
            }

            retVal= iimgEncfxns->control((IIMGENC1_Handle)handle,
                                         XDM_GETBUFINFO,
                                         (IIMGENC1_DynamicParams *)&dynamicParams,
                                         (IIMGENC1_Status *)&imgencStatus);
             if (retVal== XDM_EFAIL) 
	     {
		 printf("\n Error control GetBuffInfo  command1\n");
	         exit(0);
	      }

            inputBufDesc.numBufs = imgencStatus.bufInfo.minNumInBufs;
            Offset = 0;

            for (i=0;i<inputBufDesc.numBufs;i++)
            {
                inputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)inputData +
                                            Offset);
                Offset +=  imgencStatus.bufInfo.minInBufSize[i];
                inputBufDesc.descs[i].bufSize = imgencStatus.bufInfo.minInBufSize[i];
            }

            outputBufDesc.numBufs = imgencStatus.bufInfo.minNumOutBufs;
            Offset = 0;

            for (i=0;i<outputBufDesc.numBufs;i++)
            {
                outputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)outputData +
                                             Offset);
                Offset +=  imgencStatus.bufInfo.minOutBufSize[i];
                outputBufDesc.descs[i].bufSize = imgencStatus.bufInfo.minOutBufSize[i];
            }

            if (retVal== XDM_EFAIL) {
                printf("\n Error control GetInfo command\n");
                exit(0);
            }




        }
        if (baseParamsOnly==0)
        {
            /** Read input file.
               */
            printf("Number of Input bufs =%d\n",status.imgencStatus.bufInfo.minNumInBufs );
            if (status.imgencStatus.bufInfo.minNumInBufs == 3)
            {
                memset(OrgPictureY,0,(status.imgencStatus.bufInfo.minInBufSize[0]));
                memset(OrgPictureCb,0,(status.imgencStatus.bufInfo.minInBufSize[1]));
                memset(OrgPictureCr,0,(status.imgencStatus.bufInfo.minInBufSize[2]));
                printf("Input file read starts\n" );

                lTemp = fread(OrgPictureY,1,(status.imgencStatus.bufInfo.minInBufSize[0]),fp_in);
                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR);
                }
                printf("number of bytes read from input file = %d \n",lTemp);


                lTemp = fread(OrgPictureCb,1,((status.imgencStatus.bufInfo.minInBufSize[1])),fp_in);
                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR);
                }
                printf("number of bytes read from input file = %d \n",lTemp);
                lTemp = fread(OrgPictureCr,1,((status.imgencStatus.bufInfo.minInBufSize[2])),fp_in);
                printf("number of bytes read from input file = %d \n",lTemp);


            }
            else if (status.imgencStatus.bufInfo.minNumInBufs == 1)
            {
                printf("status.imgencStatus.bufInfo.minInBufSize[0]=%d\n",status.imgencStatus.bufInfo.minInBufSize[0]);
                memset(OrgPictureY,0,(status.imgencStatus.bufInfo.minInBufSize[0]));
                lTemp = fread(OrgPictureY,1,(status.imgencStatus.bufInfo.minInBufSize[0]),fp_in);
                printf("number of bytes read from input file = %d \n",lTemp);
            }
            else if (status.imgencStatus.bufInfo.minNumInBufs == 2) /* 420 semi planar*/
            {
                printf("status.imgencStatus.bufInfo.minInBufSize[0]=%d\n",status.imgencStatus.bufInfo.minInBufSize[0]);
                memset(OrgPictureY,0,(status.imgencStatus.bufInfo.minInBufSize[0]));
                printf("status.imgencStatus.bufInfo.minInBufSize[1]=%d\n",status.imgencStatus.bufInfo.minInBufSize[1]);
                memset(OrgPictureCb,'-',(status.imgencStatus.bufInfo.minInBufSize[1]));
                memset(OrgPictureCr,'-',(status.imgencStatus.bufInfo.minInBufSize[1]));

                lTemp = fread(OrgPictureY,1,(status.imgencStatus.bufInfo.minInBufSize[0]),fp_in);
                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR);
                }
                printf("number of bytes read from input file = %d \n",lTemp);

                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    lTemp = fread(OrgPictureCr,1,(status.imgencStatus.bufInfo.minInBufSize[1])/2,fp_in);
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR);

                    lTemp += fread((OrgPictureCr+(status.imgencStatus.bufInfo.minInBufSize[1])/2),1,(status.imgencStatus.bufInfo.minInBufSize[1])/2,fp_in);

                }
                else
                {
                    lTemp = fread(OrgPictureCr,1,(status.imgencStatus.bufInfo.minInBufSize[1]),fp_in);
                }

                printf("number of bytes read from input file = %d \n",lTemp);

                /* The input file is 420 planar, the following function converts the 420P to 420 semi planar
                   i.e CbCr will be interleaved. planar chrmoa data is read into OrgPictureCr buffer and
                   converted to interleaved. output is stored in OrgPictureCb buffer*/
                /*convert the 420 planar to 420 semi planar*/
                lTemp = Convert420Pto420Semi(OrgPictureCr,OrgPictureCb,status.imgencStatus.bufInfo.minInBufSize[1]);

            }
            else
            {
                printf("Unsupported number of input buffers \n");
            }
            fclose(fp_in);
        }
        else
        {
            /** Read input file.
               */
            printf("Number of Input bufs =%d\n",imgencStatus.bufInfo.minNumInBufs );
            if (imgencStatus.bufInfo.minNumInBufs == 3)
            {
                memset(OrgPictureY,0,(imgencStatus.bufInfo.minInBufSize[0]));
                memset(OrgPictureCb,0,(imgencStatus.bufInfo.minInBufSize[1]));
                memset(OrgPictureCr,0,(imgencStatus.bufInfo.minInBufSize[2]));
                printf("Input file read starts\n" );

                lTemp = fread(OrgPictureY,1,(imgencStatus.bufInfo.minInBufSize[0]),fp_in);
                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR);
                }
                printf("number of bytes read from input file = %d \n",lTemp);


                lTemp = fread(OrgPictureCb,1,((imgencStatus.bufInfo.minInBufSize[1])),fp_in);
                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR);
                }
                printf("number of bytes read from input file = %d \n",lTemp);
                lTemp = fread(OrgPictureCr,1,((imgencStatus.bufInfo.minInBufSize[2])),fp_in);
                printf("number of bytes read from input file = %d \n",lTemp);


            }
            else if (imgencStatus.bufInfo.minNumInBufs == 1)
            {
                printf("imgencStatus.bufInfo.minInBufSize[0]=%d\n",imgencStatus.bufInfo.minInBufSize[0]);
                memset(OrgPictureY,0,(imgencStatus.bufInfo.minInBufSize[0]));
                lTemp = fread(OrgPictureY,1,(imgencStatus.bufInfo.minInBufSize[0]),fp_in);
                printf("number of bytes read from input file = %d \n",lTemp);
            }
            else if (imgencStatus.bufInfo.minNumInBufs == 2) /* 420 semi planar*/
            {
                printf("imgencStatus.bufInfo.minInBufSize[0]=%d\n",imgencStatus.bufInfo.minInBufSize[0]);
                memset(OrgPictureY,0,(imgencStatus.bufInfo.minInBufSize[0]));
                printf("imgencStatus.bufInfo.minInBufSize[1]=%d\n",imgencStatus.bufInfo.minInBufSize[1]);
                memset(OrgPictureCb,'-',(imgencStatus.bufInfo.minInBufSize[1]));
                memset(OrgPictureCr,'-',(imgencStatus.bufInfo.minInBufSize[1]));

                lTemp = fread(OrgPictureY,1,(imgencStatus.bufInfo.minInBufSize[0]),fp_in);
                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR);
                }
                printf("number of bytes read from input file = %d \n",lTemp);

                if (dynamicParams.inputWidth < dynamicParams.captureWidth) {
                    lTemp = fread(OrgPictureCr,1,(imgencStatus.bufInfo.minInBufSize[1])/2,fp_in);
                    fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR);

                    lTemp += fread((OrgPictureCr+(imgencStatus.bufInfo.minInBufSize[1])/2),1,(imgencStatus.bufInfo.minInBufSize[1])/2,fp_in);

                }
                else
                {
                    lTemp = fread(OrgPictureCr,1,(imgencStatus.bufInfo.minInBufSize[1]),fp_in);
                }

                printf("number of bytes read from input file = %d \n",lTemp);

                /* The input file is 420 planar, the following function converts the 420P to 420 semi planar
                   i.e CbCr will be interleaved. planar chrmoa data is read into OrgPictureCr buffer and
                   converted to interleaved. output is stored in OrgPictureCb buffer*/
                /*convert the 420 planar to 420 semi planar*/
                lTemp = Convert420Pto420Semi(OrgPictureCr,OrgPictureCb,imgencStatus.bufInfo.minInBufSize[1]);

                //	printf("OrgPictureCb=%x\n",OrgPictureCb);


            }
            else
            {
                printf("Unsupported number of input buffers \n");
            }
            fclose(fp_in);

        }

        /*Fill up the buffers as required by algorithm                            */
        if (baseParamsOnly==0) {
            inputBufDesc.numBufs  = status.imgencStatus.bufInfo.minNumInBufs ;
        }
        else
        {
            inputBufDesc.numBufs  = imgencStatus.bufInfo.minNumInBufs ;
        }
        inputBufDesc.descs[0].buf= (XDAS_Int8 *)OrgPictureY;

        if (dynamicParams.inputChromaFormat== IJPEGENC_YUV_420LINE)
        {
            inputBufDesc.descs[1].buf= (XDAS_Int8 *)OrgPictureY + dynamicParams.inputWidth;
            inputBufDesc.descs[2].buf= inputBufDesc.descs[1].buf + dynamicParams.inputWidth*3/2;
        }
        else if (dynamicParams.inputChromaFormat!= XDM_YUV_422ILE)
        {
            if (dynamicParams.inputChromaFormat== XDM_YUV_420SP)
            {
                inputBufDesc.descs[1].buf= (XDAS_Int8 *)OrgPictureCb;
            }
            else
            {
                inputBufDesc.descs[1].buf= (XDAS_Int8 *)OrgPictureCb;
                inputBufDesc.descs[2].buf= (XDAS_Int8 *)OrgPictureCr;
            }

        }
        if (baseParamsOnly==0) {
            inputBufDesc.descs[0].bufSize = status.imgencStatus.bufInfo.minInBufSize[0]; // actually ignored by codec

            outputBufDesc.numBufs     = status.imgencStatus.bufInfo.minNumOutBufs ;
        }
        else
        {
            inputBufDesc.descs[0].bufSize = imgencStatus.bufInfo.minInBufSize[0]; // actually ignored by codec

            outputBufDesc.numBufs     = imgencStatus.bufInfo.minNumOutBufs ;
        }

        if (baseParamsOnly==0)
        {
#ifdef ENABLE_RING_BUF_USAGE

            outputBufDesc.descs[0].buf     = (XDAS_Int8 *)ringbuf;
            outputBufDesc.descs[0].bufSize =  RINGBUFSIZE; // actually ignored by codec
            ring2media.mediaPtr= media;
            ring2media.ringCurPtr= ringbuf;
            ring2media.ringStartPtr=ringbuf;
            ring2media.ringEndPtr= (Uint8*)((Uint32)ringbuf +RINGBUFSIZE) ;
            inArgs.ringBufStart= (XDAS_UInt8*)ringbuf;
            inArgs.ringBufSize= RINGBUFSIZE;
            printf("RINGBUFSIZE %x\n", RINGBUFSIZE);
#else
            outputBufDesc.descs[0].buf     = (XDAS_Int8 *)media;
            outputBufDesc.descs[0].bufSize =  ENCODED_DATA_BUFFER_SIZE; // actually ignored by codec
            ring2media.mediaPtr= media;
            ring2media.ringCurPtr= media;
            ring2media.ringStartPtr=media;
            ring2media.ringEndPtr= (Uint8*)((Uint32)media +ENCODED_DATA_BUFFER_SIZE) ;
            inArgs.ringBufStart= (XDAS_UInt8*)media;
            inArgs.ringBufSize= ENCODED_DATA_BUFFER_SIZE;
#endif


            inArgs.imgencInArgs.size =  sizeof(IJPEGENC_InArgs);
            outArgs.imgencOutArgs.size= sizeof(IJPEGENC_OutArgs);
        }
        else
        {
            outputBufDesc.descs[0].buf     = (XDAS_Int8 *)media;
            outputBufDesc.descs[0].bufSize =  ENCODED_DATA_BUFFER_SIZE; // actually ignored by codec
            imgencInArgs.size = sizeof(IIMGENC1_InArgs);
            imgencOutArgs.size= sizeof(IIMGENC1_OutArgs);

        }

#ifdef LINUX
        algActStart.tv_sec = 0;
        algActStart.tv_usec = 0;
        gettimeofday(&algActStart, 0);
#endif

        handle->fxns->algActivate(handle);

#ifdef LINUX
        processStart.tv_sec = 0;
        processStart.tv_usec = 0;
        gettimeofday(&processStart, 0);
#endif



        if (baseParamsOnly==0)
        {
            inArgs.insertCommentMarker = 0;
            inArgs.appDataType =0;
            inArgs.commentSegLen = 0;

            retVal = iimgEncfxns->process((IIMGENC1_Handle)handle,
                                          (XDM1_BufDesc *)&inputBufDesc,
                                          (XDM1_BufDesc *)&outputBufDesc,
                                          (IIMGENC1_InArgs *)&inArgs,
                                          (IIMGENC1_OutArgs *)&outArgs);

            bytesGenerated= outArgs.imgencOutArgs.bytesGenerated;
        }
        else
        {
            retVal = iimgEncfxns->process((IIMGENC1_Handle)handle,
                                          (XDM1_BufDesc *)&inputBufDesc,
                                          (XDM1_BufDesc *)&outputBufDesc,
                                          (IIMGENC1_InArgs *)&imgencInArgs,
                                          (IIMGENC1_OutArgs *)&imgencOutArgs);
            bytesGenerated= imgencOutArgs.bytesGenerated;
        }

#ifdef SLICE_MODE_TEST
        /* SLICE_MODE_TEST*/
        // Call get status to get number of total AU
        if (baseParamsOnly==0)
        {
            
		
	    retVal=iimgEncfxns->control((IIMGENC1_Handle)handle, IJPEGENC_GETSTATUS,
                                        (IIMGENC1_DynamicParams *)&extn_dynamicParams, (IIMGENC1_Status *)&status);
	    
	    if (retVal== XDM_EFAIL) {
                printf("\n Error control in slice mode get status command\n");
                exit(0);
            }
            totalAU= status.imgencStatus.totalAU;

	    printf("totalAU = %d\n",totalAU);
            extn_dynamicParams.imgencDynamicParams.numAU= 50/*totalAU/5*/;
	    
            // Call control function to setup dynamic params
            retVal=iimgEncfxns->control((IIMGENC1_Handle)handle, XDM_SETPARAMS,
                                        (IIMGENC1_DynamicParams *)&extn_dynamicParams, (IIMGENC1_Status *)&status);
            numAU = status.numAU;
	    printf("numAU = %d\n",numAU);

	    if (retVal== XDM_EFAIL) {
                printf("\n Error control in slice mode SetParams command\n");
                exit(0);
            }          // Get real numAU computed by codec

            // In case of 270 rotation, must point to right most slice of the image
            
	    if (extn_dynamicParams.rotation== 90)
            {
                if (dynamicParams.inputChromaFormat==XDM_YUV_420SP)
                {
                    Uint16 sliceWidth= (numAU*16/dynamicParams.inputHeight)*(8<<(params.forceChromaFormat==XDM_YUV_420P));
                    inputBufDesc.descs[0].buf+= (dynamicParams.inputWidth - sliceWidth);
                    inputBufDesc.descs[1].buf+= (dynamicParams.inputWidth - sliceWidth);

                    //	inputBufDesc.descs[2].buf+= (dynamicParams.inputWidth - sliceWidth);//dynamicParams.inputWidth/2 - sliceWidth/2;
                }
                else
                {
                    Uint16 sliceWidth= (numAU*16/dynamicParams.inputHeight)*(8<<(params.forceChromaFormat==XDM_YUV_420P));
                    inputBufDesc.descs[0].buf+= (dynamicParams.inputChromaFormat== XDM_YUV_422ILE ? 2 : 1)*(dynamicParams.inputWidth - sliceWidth);
                    inputBufDesc.descs[1].buf+= dynamicParams.inputWidth/2 - sliceWidth/2;
                    inputBufDesc.descs[2].buf+= dynamicParams.inputWidth/2 - sliceWidth/2;
                }


            }
            else if (extn_dynamicParams.rotation== 180)
            {
                Uint16 sliceHeight = (numAU*16/dynamicParams.inputWidth)*(8<<(params.forceChromaFormat==XDM_YUV_420P));
                if (dynamicParams.inputChromaFormat != XDM_YUV_420SP)
                {
                    inputBufDesc.descs[0].buf+= dynamicParams.captureWidth*(dynamicParams.inputChromaFormat== XDM_YUV_422ILE ? 2 : 1)*(dynamicParams.inputHeight - sliceHeight);
                    inputBufDesc.descs[1].buf+= dynamicParams.captureWidth*(dynamicParams.inputHeight - sliceHeight)>>(1 + (dynamicParams.inputChromaFormat== XDM_YUV_420P));
                    inputBufDesc.descs[2].buf+= dynamicParams.captureWidth*(dynamicParams.inputHeight - sliceHeight)>>(1 + (dynamicParams.inputChromaFormat== XDM_YUV_420P));
                }
                else
                {
Пример #20
0
static int luaqt_defineMetaObject(lua_State *L)
{
	size_t strcount = 0;
	size_t totallen = 0;

	strcount = lua_objlen(L, 1);
	for (size_t i = 0; i < strcount; i++){
		lua_rawgeti(L, 1, i+1);
		totallen += lua_objlen(L, -1) +1;
		lua_pop(L, 1);
	}
	LuaQt::generic_callback* metaCall = new LuaQt::generic_callback(L);

	size_t datalen = lua_objlen(L, 2);
	char* data = (char*)lua_newuserdata(L, sizeof(QMetaObject) + sizeof(uint)*datalen + sizeof(QByteArrayData)*strcount + totallen );

	QMetaObject* obj = reinterpret_cast<QMetaObject*>(data);
	uint* metadata = reinterpret_cast<uint*>(data + sizeof(QMetaObject));
	QByteArrayData* stringdata = reinterpret_cast<QByteArrayData*>(data + sizeof(QMetaObject) + sizeof(uint)*datalen);
	char* strings = reinterpret_cast<char*>(data + sizeof(QMetaObject) + sizeof(uint)*datalen + sizeof(QByteArrayData)*strcount);

	{
		QMetaObject defineobj = {
			{
				reinterpret_cast<QMetaObject*>(lua_touserdata(L, 3)),
				stringdata, 
				metadata, 
				NULL,
				0,
				metaCall
			}
		};
		*obj = defineobj;
	}

	for (size_t i = 0; i < datalen; i++){
		lua_rawgeti(L, 2, i+1);
		metadata[i] = lua_tointeger(L, -1);
		lua_pop(L, 1);
	}

	{
		char* ptr = strings;
		for (size_t i = 0; i < strcount; i++){
			lua_rawgeti(L, 1, i+1);
			size_t len;
			const char* str = luaL_checklstring(L, -1, &len);
			memcpy(ptr, str, len);
			QByteArrayData tmp = {
					Q_REFCOUNT_INITIALIZE_STATIC, len, 0, 0, reinterpret_cast<char*>(ptr) - reinterpret_cast<char*>(stringdata+i)
			};
			stringdata[i] = tmp;
			ptr += len;
			*(ptr++) = 0;
			lua_pop(L, 1);
		}
	}
	

	return 1;
}
Пример #21
0
static void netdev_get_drvinfo(struct net_device *dev,
			       struct ethtool_drvinfo *info)
{
	strlcpy(info->driver, ibmveth_driver_name, sizeof(info->driver));
	strlcpy(info->version, ibmveth_driver_version, sizeof(info->version));
}
Пример #22
0
XAttrList* getAllExtendedAttributes(HFSCatalogNodeID CNID, Volume* volume) {
	BTree* tree;
	HFSPlusAttrKey key;
	HFSPlusAttrRecord* record;
	uint32_t nodeNumber;
	int recordNumber;
	BTNodeDescriptor* descriptor;
	HFSPlusAttrKey* currentKey;
	off_t recordOffset;
	XAttrList* list = NULL;
	XAttrList* lastItem = NULL;
	XAttrList* item = NULL;

	if(!volume->attrTree)
		return NULL;

	memset(&key, 0 , sizeof(HFSPlusAttrKey));
	key.fileID = CNID;
	key.startBlock = 0;
	key.name.length = 0;
	key.keyLength = sizeof(HFSPlusAttrKey) - sizeof(HFSUniStr255) + sizeof(key.name.length) + (sizeof(uint16_t) * key.name.length);

	tree = volume->attrTree;
	record = (HFSPlusAttrRecord*) search(tree, (BTKey*)(&key), NULL, &nodeNumber, &recordNumber);
	if(record == NULL)
		return NULL;

	free(record);
	
	while(nodeNumber != 0) {    
		descriptor = readBTNodeDescriptor(nodeNumber, tree);

		while(recordNumber < descriptor->numRecords) {
			recordOffset = getRecordOffset(recordNumber, nodeNumber, tree);
			currentKey = (HFSPlusAttrKey*) READ_KEY(tree, recordOffset, tree->io);

			if(currentKey->fileID == CNID) {
				item = (XAttrList*) malloc(sizeof(XAttrList));
				item->name = (char*) malloc(currentKey->name.length + 1);
				int i;
				for(i = 0; i < currentKey->name.length; i++) {
					item->name[i] = currentKey->name.unicode[i];
				}
				item->name[currentKey->name.length] = '\0';
				item->next = NULL;

				if(lastItem != NULL) {
					lastItem->next = item;
				} else {
					list = item;
				}

				lastItem = item;

				free(currentKey);
			} else {
				free(currentKey);
				free(descriptor);
				return list;
			}

			recordNumber++;
		}

		nodeNumber = descriptor->fLink;
		recordNumber = 0;

		free(descriptor);
	}
	return list;
}
Пример #23
0
/* initiate a report if we previously enabled accounting for this t */
static inline void acc_onreply( struct cell* t, struct sip_msg *req,
											struct sip_msg *reply, int code)
{
	str new_uri_bk;
	int br = -1;
	hdr_field_t *hdr;
	sip_msg_t tmsg;
	sip_msg_t *preq;

	/* acc_onreply is bound to TMCB_REPLY which may be called
	   from _reply, like when FR hits; we should not miss this
	   event for missed calls either */
	if (is_invite(t) && code>=300 && is_mc_on(req) )
		on_missed(t, req, reply, code);

	if (!should_acc_reply(req, reply, code))
		return;

	if(_acc_clone_msg==1) {
		memcpy(&tmsg, req, sizeof(sip_msg_t));
		preq = &tmsg;
	} else {
		preq = req;
	}

	/* get winning branch index, if set */
	if (t->relayed_reply_branch>=0) {
		br = t->relayed_reply_branch;
	} else {
		if(code>=300) {
			br = tmb.t_get_picked_branch();
		}
	}

	/* for reply processing, set as new_uri the one from selected branch */
	if (br>=0) {
		new_uri_bk = preq->new_uri;
		preq->new_uri = t->uac[br].uri;
		preq->parsed_uri_ok = 0;
	} else {
		new_uri_bk.len = -1;
		new_uri_bk.s = 0;
	}
	/* set env variables */
	env_set_to( get_rpl_to(t,reply) );
	env_set_code_status( code, reply);

	if ( is_log_acc_on(preq) ) {
		env_set_text( ACC_ANSWERED, ACC_ANSWERED_LEN);
		acc_log_request(preq);
	}
#ifdef SQL_ACC
	if (is_db_acc_on(preq)) {
		if(acc_db_set_table_name(preq, db_table_acc_data, &db_table_acc)<0) {
			LM_ERR("cannot set acc db table name\n");
		} else {
			acc_db_request(preq);
		}
	}
#endif
#ifdef RAD_ACC
	if (is_rad_acc_on(preq))
		acc_rad_request(preq);
#endif
/* DIAMETER */
#ifdef DIAM_ACC
	if (is_diam_acc_on(preq))
		acc_diam_request(preq);
#endif

	/* run extra acc engines */
	acc_run_engines(preq, 0, NULL);

	if (new_uri_bk.len>=0) {
		req->new_uri = new_uri_bk;
		req->parsed_uri_ok = 0;
	}

	/* free header's parsed structures that were added by resolving acc attributes */
	for( hdr=req->headers ; hdr ; hdr=hdr->next ) {
		if ( hdr->parsed && hdr_allocs_parse(hdr) &&
					(hdr->parsed<(void*)t->uas.request ||
					hdr->parsed>=(void*)t->uas.end_request)) {
			/* header parsed filed doesn't point inside uas.request memory
			 * chunck -> it was added by resolving acc attributes -> free it as pkg */
			DBG("removing hdr->parsed %d\n", hdr->type);
			clean_hdr_field(hdr);
			hdr->parsed = 0;
		}
	}
}
Пример #24
0
static int construct_genes(GT_UNUSED void *key, void *value, void *data,
                           GtError *err)
{
  GtHashmap *transcript_id_hash = (GtHashmap*) value;
  ConstructionInfo *cinfo = (ConstructionInfo*) data;
  GtQueue *genome_nodes = cinfo->genome_nodes;
  const char *gname;
  GtArray *mRNAs = gt_array_new(sizeof (GtGenomeNode*));
  GtGenomeNode *gene_node, *gn;
  GtStrand gene_strand;
  GtRange gene_range;
  GtStr *gene_seqid;
  GtUword i;
  int had_err = 0;

  gt_error_check(err);
  gt_assert(key && value && data);
  cinfo->mRNAs = mRNAs;
  had_err = gt_hashmap_foreach(transcript_id_hash, construct_mRNAs, cinfo, err);
  if (!had_err) {
    gt_assert(gt_array_size(mRNAs)); /* at least one mRNA constructed */

    /* determine the range and the strand of the gene */
    gn = *(GtGenomeNode**) gt_array_get(mRNAs, 0);
    gene_range = gt_genome_node_get_range(gn);
    gene_strand = gt_feature_node_get_strand((GtFeatureNode*) gn);
    gene_seqid = gt_genome_node_get_seqid(gn);
    for (i = 1; i < gt_array_size(mRNAs); i++) {
      GtRange range;
      GtStrand strand;
      gn = *(GtGenomeNode**) gt_array_get(mRNAs, i);
      range = gt_genome_node_get_range(gn);
      gene_range = gt_range_join(&gene_range, &range);
      strand = gt_feature_node_get_strand((GtFeatureNode*) gn);
      if (strand != gene_strand) {
        GT_UNUSED const char *transcript_name =
                gt_feature_node_get_attribute((GtFeatureNode*) gn, GT_GFF_NAME);
        gt_error_set(err, "transcript on strand %c encountered, but the "
                          "parent gene %s has strand %c",
                     GT_STRAND_CHARS[strand],
                     (const char*) key,
                     GT_STRAND_CHARS[gene_strand]);
        had_err = -1;
      } else {
        gene_strand = gt_strand_join(gene_strand, strand);
      }
      gt_assert(had_err || gt_str_cmp(gene_seqid,
                                      gt_genome_node_get_seqid(gn)) == 0);
    }
  }

  if (!had_err) {
    gene_node = gt_feature_node_new(gene_seqid, gt_ft_gene, gene_range.start,
                                    gene_range.end, gene_strand);

    if ((gname = gt_hashmap_get(cinfo->gene_id_to_name_mapping,
                              (const char*) key)) && strlen(gname) > 0) {
      gt_feature_node_add_attribute((GtFeatureNode*) gene_node, GT_GFF_NAME,
                                      gname);
    }

    /* register children */
    for (i = 0; i < gt_array_size(mRNAs); i++) {
      gn = *(GtGenomeNode**) gt_array_get(mRNAs, i);
      gt_feature_node_add_child((GtFeatureNode*) gene_node,
                                (GtFeatureNode*) gn);
    }

    /* store the gene */
    gt_queue_add(genome_nodes, gene_node);
  } else {
    for (i = 0; i < gt_array_size(mRNAs); i++) {
      gt_genome_node_delete(*(GtGenomeNode**) gt_array_get(mRNAs, i));
    }
  }

  /* free */
  gt_array_delete(mRNAs);

  return had_err;
}
Пример #25
0
int space(VM* vm, size_t size) {
    return (vm->heap.next + size + sizeof(size_t) < vm->heap.end);
}
Пример #26
0
int gt_gtf_parser_parse(GtGTFParser *parser, GtQueue *genome_nodes,
                        GtStr *filenamestr, GtFile *fpin, bool be_tolerant,
                        GtError *err)
{
  GtStr *seqid_str, *source_str, *line_buffer;
  char *line;
  size_t line_length;
  GtUword i, line_number = 0;
  GtGenomeNode *gn;
  GtRange range;
  GtPhase phase_value;
  GtStrand gt_strand_value;
  GtSplitter *splitter, *attribute_splitter;
  float score_value;
  char *seqname,
       *source,
       *feature,
       *start,
       *end,
       *score,
       *strand,
       *frame,
       *attributes,
       *token,
       *gene_id,
       *gene_name = NULL,
       *transcript_id,
       *transcript_name = NULL,
       **tokens;
  GtHashmap *transcript_id_hash; /* map from transcript id to array of genome
                                    nodes */
  GtArray *gt_genome_node_array;
  ConstructionInfo cinfo;
  GTF_feature_type gtf_feature_type;
  GT_UNUSED bool gff_type_is_valid = false;
  const char *type = NULL;
  const char *filename;
  bool score_is_defined;
  int had_err = 0;

  gt_assert(parser && genome_nodes);
  gt_error_check(err);

  filename = gt_str_get(filenamestr);

  /* alloc */
  line_buffer = gt_str_new();
  splitter = gt_splitter_new(),
  attribute_splitter = gt_splitter_new();

#define HANDLE_ERROR                                                \
        if (had_err) {                                              \
          if (be_tolerant) {                                        \
            fprintf(stderr, "skipping line: %s\n", gt_error_get(err)); \
            gt_error_unset(err);                                       \
            gt_str_reset(line_buffer);                                 \
            had_err = 0;                                            \
            continue;                                               \
          }                                                         \
          else {                                                    \
            had_err = -1;                                           \
            break;                                                  \
          }                                                         \
        }

  while (gt_str_read_next_line_generic(line_buffer, fpin) != EOF) {
    line = gt_str_get(line_buffer);
    line_length = gt_str_length(line_buffer);
    line_number++;
    gene_name = gene_id = transcript_id = transcript_name = NULL;
    had_err = 0;

    if (line_length == 0) {
      gt_warning("skipping blank line " GT_WU " in file \"%s\"", line_number,
                 filename);
    }
    else if (line[0] == '#') {
      /* storing comment */
      if (line_length >= 2 && line[1] == '#')
        gn = gt_comment_node_new(line+2); /* store '##' line as '#' line */
      else
        gn = gt_comment_node_new(line+1);
      gt_genome_node_set_origin(gn, filenamestr, line_number);
      gt_queue_add(genome_nodes, gn);
    }
    else {
      bool stop_codon = false;

      /* process tab delimited GTF line */
      gt_splitter_reset(splitter);
      gt_splitter_split(splitter, line, line_length, '\t');
      if (gt_splitter_size(splitter) != 9UL) {
        gt_error_set(err, "line " GT_WU " in file \"%s\" contains " GT_WU
                     " tab (\\t) " "separated fields instead of 9", line_number,
                     filename,
                  gt_splitter_size(splitter));
        had_err = -1;
        break;
      }
      tokens = gt_splitter_get_tokens(splitter);
      seqname    = tokens[0];
      source     = tokens[1];
      feature    = tokens[2];
      start      = tokens[3];
      end        = tokens[4];
      score      = tokens[5];
      strand     = tokens[6];
      frame      = tokens[7];
      attributes = tokens[8];

      /* parse feature */
      if (GTF_feature_type_get(&gtf_feature_type, feature) == -1) {
        /* we skip unknown features */
        fprintf(stderr, "skipping line " GT_WU " in file \"%s\": unknown "
                "feature: \"%s\"\n", line_number, filename, feature);
        gt_str_reset(line_buffer);
        continue;
      }

      /* translate into GFF3 feature type */
      switch (gtf_feature_type) {
        case GTF_stop_codon:
          stop_codon = true;
        case GTF_CDS:
          gff_type_is_valid = gt_type_checker_is_valid(parser->type_checker,
                                                       gt_ft_CDS);
          type = gt_ft_CDS;
          break;
        case GTF_exon:
          gff_type_is_valid = gt_type_checker_is_valid(parser->type_checker,
                                                       gt_ft_exon);
          type = gt_ft_exon;
          break;
        case GTF_start_codon:
          /* we can skip the start codons, they are part of the CDS anyway */
          gt_str_reset(line_buffer);
          continue;
      }
      gt_assert(gff_type_is_valid);

      /* parse the range */
      had_err = gt_parse_range(&range, start, end, line_number, filename, err);
      HANDLE_ERROR;

      /* process seqname (we have to do it here because we need the range) */
      gt_region_node_builder_add_region(parser->region_node_builder, seqname,
                                        range);

      /* parse the score */
      had_err = gt_parse_score(&score_is_defined, &score_value, score,
                               line_number, filename, err);
      HANDLE_ERROR;

      /* parse the strand */
      had_err = gt_parse_strand(&gt_strand_value, strand, line_number, filename,
                               err);
      HANDLE_ERROR;

      /* parse the frame */
      had_err = gt_parse_phase(&phase_value, frame, line_number, filename, err);
      HANDLE_ERROR;

      /* parse the attributes */
      gt_splitter_reset(attribute_splitter);
      gene_id = NULL;
      transcript_id = NULL;
      gt_splitter_split(attribute_splitter, attributes, strlen(attributes),
                        ';');
      for (i = 0; i < gt_splitter_size(attribute_splitter); i++) {
        token = gt_splitter_get_token(attribute_splitter, i);
        /* skip leading blanks */
        while (*token == ' ')
          token++;
        /* look for the two mandatory attributes */
        if (strncmp(token, GENE_ID_ATTRIBUTE, strlen(GENE_ID_ATTRIBUTE)) == 0) {
          if (strlen(token) + 2 < strlen(GENE_ID_ATTRIBUTE)) {
            gt_error_set(err, "missing value to attribute \"%s\" on line "
                         GT_WU "in file \"%s\"", GENE_ID_ATTRIBUTE, line_number,
                         filename);
            had_err = -1;
          }
          HANDLE_ERROR;
          gene_id = token + strlen(GENE_ID_ATTRIBUTE) + 1;
        }
        else if (strncmp(token, TRANSCRIPT_ID_ATTRIBUTE,
                         strlen(TRANSCRIPT_ID_ATTRIBUTE)) == 0) {
          if (strlen(token) + 2 < strlen(TRANSCRIPT_ID_ATTRIBUTE)) {
            gt_error_set(err, "missing value to attribute \"%s\" on line "
                         GT_WU "in file \"%s\"", TRANSCRIPT_ID_ATTRIBUTE,
                         line_number, filename);
            had_err = -1;
          }
          HANDLE_ERROR;
          transcript_id = token + strlen(TRANSCRIPT_ID_ATTRIBUTE) + 1;
        }
        else if (strncmp(token, GENE_NAME_ATTRIBUTE,
                         strlen(GENE_NAME_ATTRIBUTE)) == 0) {
          if (strlen(token) + 2 < strlen(GENE_NAME_ATTRIBUTE)) {
            gt_error_set(err, "missing value to attribute \"%s\" on line "
                         GT_WU "in file \"%s\"", GENE_NAME_ATTRIBUTE,
                         line_number, filename);
            had_err = -1;
          }
          HANDLE_ERROR;
          gene_name = token + strlen(GENE_NAME_ATTRIBUTE) + 1;
          /* for output we want to strip quotes */
          if (*gene_name == '"')
            gene_name++;
          if (gene_name[strlen(gene_name)-1] == '"')
            gene_name[strlen(gene_name)-1] = '\0';
        }
        else if (strncmp(token, TRANSCRIPT_NAME_ATTRIBUTE,
                         strlen(TRANSCRIPT_NAME_ATTRIBUTE)) == 0) {
          if (strlen(token) + 2 < strlen(TRANSCRIPT_NAME_ATTRIBUTE)) {
            gt_error_set(err, "missing value to attribute \"%s\" on line "
                         GT_WU "in file \"%s\"", TRANSCRIPT_NAME_ATTRIBUTE,
                         line_number, filename);
            had_err = -1;
          }
          HANDLE_ERROR;
          transcript_name = token + strlen(TRANSCRIPT_NAME_ATTRIBUTE) + 1;
          /* for output we want to strip quotes */
          if (*transcript_name == '"')
            transcript_name++;
          if (transcript_name[strlen(transcript_name)-1] == '"')
            transcript_name[strlen(transcript_name)-1] = '\0';
        }
      }

      /* check for the mandatory attributes */
      if (!gene_id) {
        gt_error_set(err, "missing attribute \"%s\" on line " GT_WU
                     " in file \"%s\"", GENE_ID_ATTRIBUTE, line_number,
                     filename);
        had_err = -1;
      }
      HANDLE_ERROR;
      if (!transcript_id) {
        gt_error_set(err, "missing attribute \"%s\" on line " GT_WU
                     " in file \"%s\"", TRANSCRIPT_ID_ATTRIBUTE, line_number,
                     filename);
        had_err = -1;
      }
      HANDLE_ERROR;

      /* process the mandatory attributes */
      if (!(transcript_id_hash = gt_hashmap_get(parser->gene_id_hash,
                                             gene_id))) {
        transcript_id_hash = gt_hashmap_new(GT_HASH_STRING, gt_free_func,
                                            (GtFree) gt_array_delete);
        gt_hashmap_add(parser->gene_id_hash, gt_cstr_dup(gene_id),
                    transcript_id_hash);
      }
      gt_assert(transcript_id_hash);

      if (!(gt_genome_node_array = gt_hashmap_get(transcript_id_hash,
                                            transcript_id))) {
        gt_genome_node_array = gt_array_new(sizeof (GtGenomeNode*));
        gt_hashmap_add(transcript_id_hash, gt_cstr_dup(transcript_id),
                    gt_genome_node_array);
      }
      gt_assert(gt_genome_node_array);

      /* save optional gene_name and transcript_name attributes */
      if (transcript_name && strlen(transcript_name) > 0
            && !gt_hashmap_get(parser->transcript_id_to_name_mapping,
                             transcript_id)) {
        gt_hashmap_add(parser->transcript_id_to_name_mapping,
                    gt_cstr_dup(transcript_id),
                    gt_cstr_dup(transcript_name));
      }
      if (gene_name && strlen(gene_name) > 0
            && !gt_hashmap_get(parser->gene_id_to_name_mapping,
                                    gene_id)) {
        gt_hashmap_add(parser->gene_id_to_name_mapping,
                    gt_cstr_dup(gene_id),
                    gt_cstr_dup(gene_name));
      }

      /* get seqid */
      seqid_str = gt_hashmap_get(parser->seqid_to_str_mapping, seqname);
      if (!seqid_str) {
        seqid_str = gt_str_new_cstr(seqname);
        gt_hashmap_add(parser->seqid_to_str_mapping, gt_str_get(seqid_str),
                       seqid_str);
      }
      gt_assert(seqid_str);

      /* construct the new feature */
      gn = gt_feature_node_new(seqid_str, type, range.start, range.end,
                                 gt_strand_value);
      gt_genome_node_set_origin(gn, filenamestr, line_number);
      if (stop_codon) {
        gt_feature_node_add_attribute((GtFeatureNode*) gn,
                                      GTF_PARSER_STOP_CODON_FLAG, "true");
      }

      /* set source */
      source_str = gt_hashmap_get(parser->source_to_str_mapping, source);
      if (!source_str) {
        source_str = gt_str_new_cstr(source);
        gt_hashmap_add(parser->source_to_str_mapping, gt_str_get(source_str),
                    source_str);
      }
      gt_assert(source_str);
      gt_feature_node_set_source((GtFeatureNode*) gn, source_str);

      if (score_is_defined)
        gt_feature_node_set_score((GtFeatureNode*) gn, score_value);
      if (phase_value != GT_PHASE_UNDEFINED)
        gt_feature_node_set_phase((GtFeatureNode*) gn, phase_value);
      gt_array_add(gt_genome_node_array, gn);
    }

    gt_str_reset(line_buffer);
  }

  /* process all region nodes */
  if (!had_err)
    gt_region_node_builder_build(parser->region_node_builder, genome_nodes);

  /* process all feature nodes */
  cinfo.genome_nodes = genome_nodes;
  cinfo.tidy = be_tolerant;
  cinfo.gene_id_to_name_mapping = parser->gene_id_to_name_mapping;
  cinfo.transcript_id_to_name_mapping = parser->transcript_id_to_name_mapping;
  if (!had_err) {
    had_err = gt_hashmap_foreach(parser->gene_id_hash, construct_genes,
                                 &cinfo, err);
  }
  gt_hashmap_foreach(parser->gene_id_hash, delete_genes, NULL, err);

  /* free */
  gt_splitter_delete(splitter);
  gt_splitter_delete(attribute_splitter);
  gt_str_delete(line_buffer);

  return had_err;
}
Пример #27
0
static int read_dir(DIR *dir, struct dirent *entry)
{
  cibar_dir_t *p = (cibar_dir_t*)dir->priv;

  if (p->cur >= p->cibar->n_files)
    return -1;

  /* Copy the name */
  strncpy(entry->d_name, p->cibar->files[p->cur].name, 256);

  p->cur++;
  return 0;
}

/* The dops structure */
static cibyl_dops_t cibar_dops =
{
  .keep_uri = 0,
  .priv_data_size = sizeof(cibar_dir_t),
  .opendir  = open_dir,
  .closedir = close_dir,
  .readdir  = read_dir,
};

static void __attribute__((constructor))register_fs(void)
{
  /* Register as default */
  cibyl_dops_register("cibar://", &cibar_dops, 0);
}
Пример #28
0
/* this used to be implemented in every file system as an fcntl, but the code
 * is identical for all file systems without a real "preallocate" system call.
 * This naive approach will get the job done, but not in a terribly efficient
 * manner.
 */
void ADIOI_GEN_Prealloc(ADIO_File fd, ADIO_Offset diskspace, int *error_code) 
{
	ADIO_Offset curr_fsize, alloc_size, size, len, done, ntimes;
	ADIO_Status status;
	int i;
	char *buf;
	ADIO_Fcntl_t *fcntl_struct;
	static char myname[] = "ADIOI_GEN_PREALLOC";

	/* will be called by one process only */
	/* On file systems with no preallocation function, we have to 
           explicitly write 
           to allocate space. Since there could be holes in the file, 
           we need to read up to the current file size, write it back, 
           and then write beyond that depending on how much 
           preallocation is needed.
           read/write in sizes of no more than ADIOI_PREALLOC_BUFSZ */

	/*curr_fsize = fd->fp_ind; */
	fcntl_struct = (ADIO_Fcntl_t *) ADIOI_Malloc(sizeof(ADIO_Fcntl_t));
	ADIO_Fcntl(fd, ADIO_FCNTL_GET_FSIZE, fcntl_struct, error_code);

	curr_fsize = fcntl_struct->fsize; /* don't rely on fd->fp_ind: might be
					    working on a pre-existing file */
	alloc_size = diskspace;

	size = MPL_MIN(curr_fsize, alloc_size);
	
	ntimes = (size + ADIOI_PREALLOC_BUFSZ - 1)/ADIOI_PREALLOC_BUFSZ;
	buf = (char *) ADIOI_Malloc(ADIOI_PREALLOC_BUFSZ);
	done = 0;

	for (i=0; i<ntimes; i++) {
	    len = MPL_MIN(size-done, ADIOI_PREALLOC_BUFSZ);
	    ADIO_ReadContig(fd, buf, 
                      (int)len, /* len is ADIO_Offset but is <= ADIOI_PREALLOC_BUFSZ (16M),
                              so it fits in an int parameter */
                      MPI_BYTE, ADIO_EXPLICIT_OFFSET, done,
			    &status, error_code);
	    if (*error_code != MPI_SUCCESS) {
		*error_code = MPIO_Err_create_code(MPI_SUCCESS,
						   MPIR_ERR_RECOVERABLE,
						   myname, __LINE__,
						   MPI_ERR_IO, 
						   "**iopreallocrdwr",
						   0);
                return;  
	    }
	    ADIO_WriteContig(fd, buf, 
                       (int)len, /* len is ADIO_Offset but is <= ADIOI_PREALLOC_BUFSZ (16M),
                               so it fits in an int parameter */
                       MPI_BYTE, ADIO_EXPLICIT_OFFSET, 
                             done, &status, error_code);
	    if (*error_code != MPI_SUCCESS) return;
	    done += len;
	}

	if (alloc_size > curr_fsize) {
	    memset(buf, 0, ADIOI_PREALLOC_BUFSZ); 
	    size = alloc_size - curr_fsize;
	    ntimes = (size + ADIOI_PREALLOC_BUFSZ - 1)/ADIOI_PREALLOC_BUFSZ;
	    for (i=0; i<ntimes; i++) {
		len = MPL_MIN(alloc_size-done, ADIOI_PREALLOC_BUFSZ);
		ADIO_WriteContig(fd, buf, 
                     (int)len, /* len is ADIO_Offset but is <= ADIOI_PREALLOC_BUFSZ (16M),
                             so it fits in an int parameter */
                     MPI_BYTE, ADIO_EXPLICIT_OFFSET, 
				 done, &status, error_code);
		if (*error_code != MPI_SUCCESS) return;
		done += len;  
	    }
	}
	ADIOI_Free(fcntl_struct);
	ADIOI_Free(buf);
	*error_code = MPI_SUCCESS;
}
Пример #29
0
Файл: ar.c Проект: 8l/vlink
bool ar_extract(struct ar_info *ai)
/* fill ar_info structure with informations about the next */
/* archive member */
{
    struct ar_hdr *ah;
    uint8_t *p;
    bool cont;
    unsigned long size;

    do {
        cont = FALSE;
        if (ai->next==NULL || ai->arlen<sizeof(struct ar_hdr))
            return FALSE;  /* archive ends here */

        ah = ai->next;
        p = ((uint8_t *)ah) + sizeof(struct ar_hdr);
        ai->arlen -= sizeof(struct ar_hdr);
        ai->name[0] = 0;
        sscanf(ah->ar_size,"%lu",&ai->size);  /* file size */

        if (!strncmp(ah->ar_name,"/ ",2) ||             /* GNU symbol table */
                !strncmp(ah->ar_name,"__.SYMDEF ",10))      /* BSD symbol table */
            cont = TRUE;

        if (!strncmp(ah->ar_name,"ARFILENAMES/",12) ||  /* GNU long names 1 */
                !strncmp(ah->ar_name,"// ",3)) {            /* GNU long names 2 */
            ai->long_names = (char *)p;
            cont = TRUE;
        }

        if (ai->long_names &&                           /* long name (GNU) */
                (ah->ar_name[0]=='/' || ah->ar_name[0]==' ') &&
                (ah->ar_name[1]>='0' && ah->ar_name[1]<='9')) {
            int i,offset;
            char c,*s,*d=ai->name;

            sscanf(&ah->ar_name[1],"%d",&offset);  /* name offset */
            s = ai->long_names + offset;
            for (i=0; i<MAXARNAME; i++) {
                c = *s++;
                if (c==0 || c=='/' || c=='\n')
                    break;
                *d++ = c;
            }
            *d = 0;
        }
        else if (!strncmp(ah->ar_name,"#1/",3)) {  /* ext. name fmt. #1 (BSD) */
            int d,len;

            sscanf(&ah->ar_name[3],"%d",&d);  /* ext.fmt. name length */
            if (d > ai->arlen)
                error(37,ai->arname,ai->name);  /* Malformatted archive member */
            len = (d>MAXARNAME) ? MAXARNAME : d;
            memcpy(ai->name,p,len);
            ai->name[len] = 0;
            p += d;  /* set real beginning of file and size */
            ai->size -= d;
            ai->arlen -= d;
        }
        else {  /* normal file name < 16 chars */
            char *n = &ah->ar_name[16];
            int len;

            for (len=16; len>0; len--)
                if (*(--n) != ' ')
                    break;
            if (len && *n=='/')  /* GNU */
                --len;
            memcpy(ai->name,ah->ar_name,len);
            ai->name[len] = 0;
        }

        if (strncmp(ah->ar_fmag,ARFMAG,2))
            error(42,ai->arname,ai->name);  /* consistency check failed */
        ai->header = ah;
        ai->data = p;
        size = ((unsigned long)(p + ai->size) & 1) ? (ai->size+1) : ai->size;
        ai->next = (struct ar_hdr *)(p + size);
        if ((long)(ai->arlen -= size) < 0)
            error(37,ai->arname,ai->name);  /* Malformatted archive member */
    }
    while (cont);
    return TRUE;
}
Пример #30
0
int avi_writer_update_avi_and_stream_headers(avi_writer *w) {
    avi_writer_stream *s;
    int stream;

    if (w == NULL) return 0;
    if (w->state == AVI_WRITER_STATE_INIT || w->state == AVI_WRITER_STATE_DONE) return 0;

    if (w->enable_avioldindex || w->enable_opendml_index) {
        /* FIXME: This needs to use the rawint.h macros to read and set the value */
        w->main_header.dwFlags |=
            riff_avih_AVIMAINHEADER_flags_HASINDEX |
            riff_avih_AVIMAINHEADER_flags_MUSTUSEINDEX |
            riff_avih_AVIMAINHEADER_flags_ISINTERLEAVED;
    }

    /* NTS: As of 2013/02/06 we now allow the caller to pre-set
     *      the dwLength value, and we update it with our own if
     *      the actual frame count is larger */
    /* FIXME: When writing OpenDML files, we're actually supposed to set the stream header's
     *        dwLength to what would be the maximum length for older programs that do not
     *        read OpenDML extensions, and then we write an extended chunk into the stream
     *        header LIST that holds the true length. When will we implement this? */
    for (stream=0;stream < w->avi_stream_max;stream++) {
        s = w->avi_stream + stream;
        if (s->header.fccType == avi_fccType_video || s->header.fccType == avi_fccType_iavs) {
            if (s->header.dwLength < s->sample_index_max)
                s->header.dwLength = s->sample_index_max;
        }
        else if (s->header.fccType == avi_fccType_audio) {
            unsigned int nss,nlength=0;

            if (s->format != NULL && s->format_len >= sizeof(windows_WAVEFORMAT)) {
                windows_WAVEFORMAT *w = (windows_WAVEFORMAT*)(s->format);
                nss = __le_u16(&w->nBlockAlign);
                if (nss != 0) nlength = s->sample_write_offset / nss;
            }
            else {
                nlength = s->sample_write_offset;
            }

            if (s->header.dwLength < nlength)
                s->header.dwLength = nlength;
        }

        if (s->strh.absolute_data_offset != 0LL && s->strh.data_length >= sizeof(riff_strh_AVISTREAMHEADER)) {
            riff_chunk r = s->strh;
            assert(riff_stack_seek(w->riff,&r,0) == 0);
            assert(riff_stack_write(w->riff,&r,&s->header,sizeof(s->header)) == (int)sizeof(s->header));
        }
    }

    /* FIXME: This needs to use the rawint.h macros to set the value */
    w->main_header.dwTotalFrames = 0;
    for (stream=0;stream < w->avi_stream_max;stream++) {
        s = w->avi_stream + stream;
        if (s->header.fccType == avi_fccType_video || s->header.fccType == avi_fccType_iavs) {
            /* FIXME: This needs to use the rawint.h macros to set the value */
            w->main_header.dwTotalFrames = s->header.dwLength;
            break;
        }
    }

    if (w->avih.absolute_data_offset != 0LL && w->avih.data_length >= sizeof(riff_avih_AVIMAINHEADER)) {
        riff_chunk r = w->avih;
        assert(riff_stack_seek(w->riff,&r,0) == 0);
        assert(riff_stack_write(w->riff,&r,&w->main_header,sizeof(w->main_header)) == (int)sizeof(w->main_header));
    }

    return 1;
}