Example #1
0
VOID CATOLECRList::PassCmd(BSTR ID, LPBYTE lpUncodedCmd, DWORD dwCmdLen, 
						   LPBYTE lpDecodedRsp, DWORD &dwRspLen, 
						   LONG *pErrorCode)
{
	BOOL bSuccess = FALSE;
	BYTE nResponse, nEncodedCmd[CMD_LEN], nEncodedRsp[CMD_LEN];
	DWORD dwRetry = 0;
	CECRConnection *pConnection = GetConnection(ID);
	
	if (pConnection == NULL)
	{
		*pErrorCode = E_NOT_FOUND;
		return;
	}

	// подготовка данных команды к отправке
	ZeroMemory(nEncodedRsp, CMD_LEN);
	EncodeCmd(lpUncodedCmd, nEncodedCmd, dwCmdLen);

	// отправка запроса ENQ
	SetTimeouts(pConnection, T_T1, T_TW);
	do
	{
		COMM_OPERATION(ClearError(pConnection, pErrorCode), 100);
		COMM_OPERATION(PurgeComm(pConnection->m_hCommPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR), 0);
		COMM_OPERATION(WriteByte(pConnection, ENQ), 1);
		if (ReadByte(pConnection, &nResponse))
		{
			if (nResponse == ACK)
				// приемник готов к установке связи
				break;

			if (nResponse == ENQ)
			{
				// конфликтная ситуация
				Sleep(T_T7);
				SaveDumpString("ENQ Conflict\n");
			}
			else
			{
				// неверный ответ на запрос установки связи
				Sleep(T_T1);
				SaveDumpString("Wrong ENQ answer\n");
			}
		}

		// увеличиваем счетчик попыток
		dwRetry++;
	}
	while (dwRetry < N_ENQ_RETRY);
	CHECK_EQUALS(dwRetry, N_ENQ_RETRY, 3);

	// отправка команды
	dwRetry = 1;
	SetTimeouts(pConnection, T_T3, T_TW);
	do
	{
		COMM_OPERATION(WriteBuffer(pConnection, nEncodedCmd, dwCmdLen), 4);
		COMM_OPERATION(ReadByte(pConnection, &nResponse), 5);
		if (nResponse == ACK)
			break;
		
		// увеличиваем счетчик попыток
		SaveDumpString("NAK received on command\n");
		dwRetry++;
	}
	while (dwRetry < N_CMD_RETRY);
	CHECK_EQUALS(dwRetry, N_CMD_RETRY, 6);

	// закрытие сеанса связи
	COMM_OPERATION(WriteByte(pConnection, EOT), 7);

	// определяем таймаут ожидания ответа
	DWORD dwResponseWaitTimeout = 0;
	switch (nEncodedCmd[3])
	{
		case 0x4A:
		case 0x62:
		case 0xA7:
		case 0xA6:
		case 0x8D:
		case 0x8E:
			dwResponseWaitTimeout = 20000;
			break;
		case 0xA8:
		case 0xA9:
		case 0xAA:
		case 0xAB:
		case 0xAC:
		case 0xAD:
		case 0x5A:
			dwResponseWaitTimeout = 120000;
			break;
		case 0x91:
			dwResponseWaitTimeout = 45000;
			break;
		default:
			dwResponseWaitTimeout = T_T5;
	}

	// ждем ответ
	SetTimeouts(pConnection, dwResponseWaitTimeout, T_TW);
	COMM_OPERATION(ReadByte(pConnection, &nResponse), 8);
	CHECK_NOT_EQUALS(nResponse, ENQ, 80);
	COMM_OPERATION(WriteByte(pConnection, ACK), 9);

	// принимаем ответ
	dwRetry = 1;
	do
	{
		ZeroMemory(nEncodedRsp, CMD_LEN);
		COMM_OPERATION(GetResponse(pConnection, nEncodedRsp, dwRspLen), 10);
		
		// проверяем CRC
		if (IsValidCRC(nEncodedRsp, dwRspLen))
			break;

		// отправляем отказ 
		COMM_OPERATION(WriteByte(pConnection, NAK), 11);

		// увеличиваем счетчик попыток
		SaveDumpString("Response CRC error\n");
		dwRetry++;
	}
	while (dwRetry < N_CMD_RETRY);
	CHECK_EQUALS(dwRetry, N_CMD_RETRY, 12);

	// отправка подтверждения получения ответа
	COMM_OPERATION(WriteByte(pConnection, ACK), 13);
	// завершение сеанса связи
	SetTimeouts(pConnection, T_T4, T_TW);
	COMM_OPERATION(ReadByte(pConnection, &nResponse), 14);

	// декодируем ответ
	DecodeRsp(nEncodedRsp, lpDecodedRsp, dwRspLen);

	// проверяем результат выполнения команды
	((lpDecodedRsp[0] == 'U') && (lpDecodedRsp[1] != 0)) ? 
		*pErrorCode = lpDecodedRsp[1] : *pErrorCode = E_SUCCESS;

	// если команда выполнена с ошибкой
	// и код команды отличен от 0x45 (запрос кода состояния)
	if ((*pErrorCode != E_SUCCESS) && (nEncodedCmd[3] != 0x45))
	{
		// сохраняем дамп команды и дамп ответа
		SaveCommandDump(nEncodedCmd, nEncodedRsp, CMD_LEN, 0xFF);
	}
}
Example #2
0
                    else
                        break;
                }
                if (realsize & 1)
                    hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &length); /* skip pad byte */
                if (FAILED(hr))
                    goto fail;
            }
            }
        }
        else
        {
            BYTE colors;
            DWORD color1;
            DWORD color2;
            hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &colors);
            if (FAILED(hr))
                goto fail;
            color1 = palette[colors>>4];
            color2 = palette[colors&0xf];
            while (length-- && x < width)
            {
                bgrdata[y*width + x++] = color1;
                if (length-- && x < width)
                    bgrdata[y*width + x++] = color2;
                else
                    break;
            }
        }
    }
static const char *SetServerVar (char *name, ECVarType type, BYTE **stream, bool singlebit)
{
	FBaseCVar *var = FindCVar (name, NULL);
	UCVarValue value;

	if (singlebit)
	{
		if (var != NULL)
		{
			int bitdata;
			int mask;

			value = var->GetFavoriteRep (&type);
			if (type != CVAR_Int)
			{
				return NULL;
			}
			bitdata = ReadByte (stream);
			mask = 1 << (bitdata & 31);
			if (bitdata & 32)
			{
				value.Int |= mask;
			}
			else
			{
				value.Int &= ~mask;
			}
		}
	}
	else
	{
		switch (type)
		{
		case CVAR_Bool:		value.Bool = ReadByte (stream) ? 1 : 0;	break;
		case CVAR_Int:		value.Int = ReadLong (stream);			break;
		case CVAR_Float:	value.Float = ReadFloat (stream);		break;
		case CVAR_String:	value.String = ReadString (stream);		break;
		default: break;	// Silence GCC
		}
	}

	if (var)
	{
		var->ForceSet (value, type);
	}

	if (type == CVAR_String)
	{
		delete[] value.String;
	}

	if (var == &teamplay)
	{
		// Put players on teams if teamplay turned on
		for (int i = 0; i < MAXPLAYERS; ++i)
		{
			if (playeringame[i])
			{
				UpdateTeam (i, players[i].userinfo.team, true);
			}
		}
	}

	if (var)
	{
		value = var->GetGenericRep (CVAR_String);
		return value.String;
	}

	return NULL;
}
Example #4
0
/*** THIS FUNCTION INTENDED FOR INTERNAL USE ONLY ***/
int
match_next_vnode(XFILE * X, dump_parser * p, u_int64 * where,
		 afs_uint32 vnode)
{
    afs_uint32 r, x, y, z;
    unsigned char tag;

    if (r = xfseek(X, where))
	return r;
    if (r = ReadByte(X, &tag))
	return r;
    switch (tag) {
    case 3:			/* A vnode? */
	if (r = ReadInt32(X, &x))
	    return r;
	if (r = ReadInt32(X, &y))
	    return r;
	if (r = ReadByte(X, &tag))
	    return r;
	if (!((vnode & 1) && !(x & 1) && x < vnode)
	    && !((vnode & 1) == (x & 1) && x > vnode))
	    return DSERR_FMT;
	if (x > vnode && x - vnode > 10000)
	    return DSERR_FMT;
	if (y < 0 || y > p->vol_uniquifier)
	    return DSERR_FMT;

	/* Now, what follows the vnode/uniquifier? */
	switch (tag) {
	case 3:		/* Another vnode? - Only if this is a non-directory */
	    if (x & 1)
		return DSERR_FMT;
	    if (r = ReadInt32(X, &z))
		return r;
	    if (!((x & 1) && !(z & 1) && z < x)
		&& !((x & 1) == (z & 1) && z > x))
		return DSERR_FMT;
	    return 0;

	case 4:		/* Dump end - Only if this is a non-directory */
	    if (x & 1)
		return DSERR_FMT;
	    if (r = ReadInt32(X, &z))
		return r;
	    if (z != DUMPENDMAGIC)
		return DSERR_FMT;
	    return 0;

	case 't':		/* Vnode type byte */
	    if (r = ReadByte(X, &tag))
		return r;
	    if ((tag == vFile || tag == vSymlink) && !(x & 1))
		return 0;
	    if (tag == vDirectory && (x & 1))
		return 0;
	    return DSERR_FMT;

	default:
	    return DSERR_FMT;
	}

    case 4:			/* A dump end? */
	if (r = ReadInt32(X, &x))
	    return r;
	if (x != DUMPENDMAGIC)
	    return DSERR_FMT;
	return 0;

    default:
	return DSERR_FMT;
    }
}
Example #5
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d I P T C I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Method ReadIPTCImage reads an image file in the IPTC format and returns it.
%  It allocates the memory necessary for the new Image structure and returns a
%  pointer to the new image.  This method differs from the other decoder
%  methods in that only the iptc profile information is useful in the
%  returned image.
%
%  The format of the ReadIPTCImage method is:
%
%      Image *ReadIPTCImage(const ImageInfo *image_info)
%
%  A description of each parameter follows:
%
%    o image:  Method ReadIPTCImage returns a pointer to the image after
%      reading. A null image is returned if there is a memory shortage or if
%      the image cannot be read.
%
%    o image_info: Specifies a pointer to an ImageInfo structure.
%
%
*/
Export Image *ReadIPTCImage(const ImageInfo *image_info)
{
  Image
    *image;

  int
    c;

  register unsigned char
    *q;

  unsigned char
    *data;

  unsigned int
    tag_length,
    length,
    status;

  /*
    Allocate image structure.
  */
  image=AllocateImage(image_info);
  if (image == (Image *) NULL)
    return((Image *) NULL);
  /*
    Open image file.
  */
  status=OpenBlob(image_info,image,ReadBinaryType);
  if (status == False)
    ReaderExit(FileOpenWarning,"Unable to open file",image);
  /*
    Read IPTC image.
  */
  length=MaxTextExtent;
  tag_length=12;
  data=(unsigned char *)
    AllocateMemory((length+2)*sizeof(unsigned char));
  if (data == (unsigned char *) NULL)
    WriterExit(ResourceLimitWarning,"Memory allocation failed",image);
  (void) memcpy((char *) data,"8BIM\04\04\0\0\0\0\0\0",tag_length);
  q=data;
  q+=tag_length;
  while (1)
  {
    c=ReadByte(image);
    if (c == EOF)
      break;
    if ((q-data+1) >= (int) length)
      {
        image->iptc_profile.length=q-data;
        length<<=1;
        data=(unsigned char *) ReallocateMemory((char *)
          data,(length+2)*sizeof(unsigned char));
        if (data == (unsigned char *) NULL)
          break;
        q=data+image->iptc_profile.length;
      }
    *q++=(unsigned char) c;
  }
  image->iptc_profile.length=0;
  if (data != (unsigned char *) NULL)
    {
      image->iptc_profile.length=q-data;
      length=image->iptc_profile.length-tag_length;
      data[10]=length >> 8;
      data[11]=length & 0xff;
      image->iptc_profile.info=data;
    }
	short BufferReader::ReadShort() const
	{
		short aShort = ReadByte();
		aShort |= ((short) ReadByte() << 8);
		return aShort;	
	}
Example #7
0
void CInArchive::Skip(size_t size)
{
  while (size-- != 0)
    ReadByte();
}
Example #8
0
static ParseStatus ParseVP8X(WebPDemuxer* const dmux) {
  MemBuffer* const mem = &dmux->mem_;
  int anim_chunks = 0;
  uint32_t vp8x_size;
  ParseStatus status = PARSE_OK;

  if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;

  dmux->is_ext_format_ = 1;
  Skip(mem, TAG_SIZE);  // VP8X
  vp8x_size = ReadLE32(mem);
  if (vp8x_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
  if (vp8x_size < VP8X_CHUNK_SIZE) return PARSE_ERROR;
  vp8x_size += vp8x_size & 1;
  if (SizeIsInvalid(mem, vp8x_size)) return PARSE_ERROR;
  if (MemDataSize(mem) < vp8x_size) return PARSE_NEED_MORE_DATA;

  dmux->feature_flags_ = ReadByte(mem);
  Skip(mem, 3);  // Reserved.
  dmux->canvas_width_  = 1 + ReadLE24s(mem);
  dmux->canvas_height_ = 1 + ReadLE24s(mem);
  if (dmux->canvas_width_ * (uint64_t)dmux->canvas_height_ >= MAX_IMAGE_AREA) {
    return PARSE_ERROR;  // image final dimension is too large
  }
  Skip(mem, vp8x_size - VP8X_CHUNK_SIZE);  // skip any trailing data.
  dmux->state_ = WEBP_DEMUX_PARSED_HEADER;

  if (SizeIsInvalid(mem, CHUNK_HEADER_SIZE)) return PARSE_ERROR;
  if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;

  do {
    int store_chunk = 1;
    const size_t chunk_start_offset = mem->start_;
    const uint32_t fourcc = ReadLE32(mem);
    const uint32_t chunk_size = ReadLE32(mem);
    const uint32_t chunk_size_padded = chunk_size + (chunk_size & 1);

    if (chunk_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
    if (SizeIsInvalid(mem, chunk_size_padded)) return PARSE_ERROR;

    switch (fourcc) {
      case MKFOURCC('V', 'P', '8', 'X'): {
        return PARSE_ERROR;
      }
      case MKFOURCC('A', 'L', 'P', 'H'):
      case MKFOURCC('V', 'P', '8', ' '):
      case MKFOURCC('V', 'P', '8', 'L'): {
        // check that this isn't an animation (all frames should be in an ANMF).
        if (anim_chunks > 0) return PARSE_ERROR;

        Rewind(mem, CHUNK_HEADER_SIZE);
        status = ParseSingleImage(dmux);
        break;
      }
      case MKFOURCC('A', 'N', 'I', 'M'): {
        if (chunk_size_padded < ANIM_CHUNK_SIZE) return PARSE_ERROR;

        if (MemDataSize(mem) < chunk_size_padded) {
          status = PARSE_NEED_MORE_DATA;
        } else if (anim_chunks == 0) {
          ++anim_chunks;
          dmux->bgcolor_ = ReadLE32(mem);
          dmux->loop_count_ = ReadLE16s(mem);
          Skip(mem, chunk_size_padded - ANIM_CHUNK_SIZE);
        } else {
          store_chunk = 0;
          goto Skip;
        }
        break;
      }
      case MKFOURCC('A', 'N', 'M', 'F'): {
        if (anim_chunks == 0) return PARSE_ERROR;  // 'ANIM' precedes frames.
        status = ParseAnimationFrame(dmux, chunk_size_padded);
        break;
      }
#ifdef WEBP_EXPERIMENTAL_FEATURES
      case MKFOURCC('F', 'R', 'G', 'M'): {
        status = ParseFragment(dmux, chunk_size_padded);
        break;
      }
#endif
      case MKFOURCC('I', 'C', 'C', 'P'): {
        store_chunk = !!(dmux->feature_flags_ & ICCP_FLAG);
        goto Skip;
      }
      case MKFOURCC('X', 'M', 'P', ' '): {
        store_chunk = !!(dmux->feature_flags_ & XMP_FLAG);
        goto Skip;
      }
      case MKFOURCC('E', 'X', 'I', 'F'): {
        store_chunk = !!(dmux->feature_flags_ & EXIF_FLAG);
        goto Skip;
      }
 Skip:
      default: {
        if (chunk_size_padded <= MemDataSize(mem)) {
          if (store_chunk) {
            // Store only the chunk header and unpadded size as only the payload
            // will be returned to the user.
            if (!StoreChunk(dmux, chunk_start_offset,
                            CHUNK_HEADER_SIZE + chunk_size)) {
              return PARSE_ERROR;
            }
          }
          Skip(mem, chunk_size_padded);
        } else {
          status = PARSE_NEED_MORE_DATA;
        }
      }
    }

    if (mem->start_ == mem->riff_end_) {
      break;
    } else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {
      status = PARSE_NEED_MORE_DATA;
    }
  } while (status == PARSE_OK);

  return status;
}
Example #9
0
HRESULT CHdmvClipInfo::ReadChapters(CString strPlaylistFile, CAtlList<CHdmvClipInfo::PlaylistItem>& PlaylistItems, CAtlList<PlaylistChapter>& Chapters)
{
    CPath Path(strPlaylistFile);

    // Get BDMV folder
    Path.RemoveFileSpec();
    Path.RemoveFileSpec();

    m_hFile = CreateFile(strPlaylistFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                         OPEN_EXISTING, FILE_ATTRIBUTE_READONLY | FILE_FLAG_SEQUENTIAL_SCAN, NULL);

    if (m_hFile != INVALID_HANDLE_VALUE) {
        REFERENCE_TIME* rtOffset = DEBUG_NEW REFERENCE_TIME[PlaylistItems.GetCount()];
        REFERENCE_TIME rtSum = 0;
        int nIndex = 0;
        BYTE Buff[100];
        bool bDuplicate = false;

        POSITION pos = PlaylistItems.GetHeadPosition();
        while (pos) {
            CHdmvClipInfo::PlaylistItem& PI = PlaylistItems.GetNext(pos);

            rtOffset[nIndex] = rtSum - PI.m_rtIn;
            rtSum = rtSum + PI.Duration();
            nIndex++;
        }

        ReadBuffer(Buff, 4);
        if (memcmp(Buff, "MPLS", 4)) {
            SAFE_DELETE_ARRAY(rtOffset);
            return CloseFile(VFW_E_INVALID_FILE_FORMAT);
        }

        ReadBuffer(Buff, 4);
        if ((memcmp(Buff, "0200", 4) != 0) && (memcmp(Buff, "0100", 4) != 0)) {
            SAFE_DELETE_ARRAY(rtOffset);
            return CloseFile(VFW_E_INVALID_FILE_FORMAT);
        }

        LARGE_INTEGER  Pos;
        unsigned short nMarkCount;

        ReadDword();                // PlayList_start_address
        Pos.QuadPart = ReadDword(); // PlayListMark_start_address

        // PlayListMark()
        SetFilePointerEx(m_hFile, Pos, NULL, FILE_BEGIN);
        ReadDword();                // length
        nMarkCount = ReadShort();   // number_of_PlayList_marks
        for (size_t i = 0; i < nMarkCount; i++) {
            PlaylistChapter Chapter;

            ReadByte();                                           // reserved_for_future_use
            Chapter.m_nMarkType   = (PlaylistMarkType)ReadByte(); // mark_type
            Chapter.m_nPlayItemId = ReadShort();                  // ref_to_PlayItem_id
            Chapter.m_rtTimestamp = 20000i64 * ReadDword() / 90 + rtOffset[Chapter.m_nPlayItemId];    // mark_time_stamp
            Chapter.m_nEntryPID   = ReadShort();                  // entry_ES_PID
            Chapter.m_rtDuration  = 20000i64 * ReadDword() / 90;  // duration

            Chapters.AddTail(Chapter);

            //TRACE(_T("Chapter %d : %s\n"), i, ReftimeToString(Chapter.m_rtTimestamp));
        }

        CloseFile(S_OK);
        SAFE_DELETE_ARRAY(rtOffset);
        return bDuplicate ? S_FALSE : S_OK;
    }

    return AmHresultFromWin32(GetLastError());
}
Example #10
0
/* Parse a VNode, including any tagged attributes and data, and call the
 * appropriate callback, if one is defined.
 */
afs_uint32
parse_vnode(XFILE * X, unsigned char *tag, tagged_field * field,
	    afs_uint32 value, tag_parse_info * pi, void *g_refcon,
	    void *l_refcon)
{
    dump_parser *p = (dump_parser *) g_refcon;
    afs_uint32(*cb) (afs_vnode *, XFILE *, void *);
    u_int64 where, offset2k;
    afs_vnode v;
    afs_uint32 r;


    if ((r = xftell(X, &where)))
	return r;
    memset(&v, 0, sizeof(v));
    sub64_32(v.offset, where, 1);
    if ((r = ReadInt32(X, &v.vnode)))
	return r;
    if ((r = ReadInt32(X, &v.vuniq)))
	return r;

    mk64(offset2k, 0, 2048);
    if (!LastGoodVNode
	|| ((p->flags & DSFLAG_SEEK) && v.vnode == 1
	    && lt64(v.offset, offset2k)))
	LastGoodVNode = -1;

    if (p->print_flags & DSPRINT_ITEM) {
	printf("%s %d/%d [%s = 0x%s]\n", field->label, v.vnode, v.vuniq,
	       decimate_int64(&where, 0), hexify_int64(&where, 0));
    }

    r = ParseTaggedData(X, vnode_fields, tag, pi, g_refcon, (void *)&v);

    /* Try to resync, if requested */
    if (!r && (p->repair_flags & DSFIX_VFSYNC)) {
	afs_uint32 drop;
	u_int64 xwhere;

	if ((r = xftell(X, &where)))
	    return r;
	sub64_32(xwhere, where, 1);

	/* Are we at the start of a valid vnode (or dump end)? */
	r = match_next_vnode(X, p, &xwhere, v.vnode);
	if (r && r != DSERR_FMT)
	    return r;
	if (r) {		/* Nope. */
	    /* Was _this_ a valid vnode?  If so, we can keep it and search for
	     * the next one.  Otherwise, we throw it out, and start the search
	     * at the starting point of this vnode.
	     */
	    drop = r = match_next_vnode(X, p, &v.offset, LastGoodVNode);
	    if (r && r != DSERR_FMT)
		return r;
	    if (!r) {
		add64_32(where, v.offset, 1);
		if ((r = xfseek(X, &v.offset)))
		    return r;
	    } else {
		if ((r = xfseek(X, &xwhere)))
		    return r;
	    }
	    if ((r = resync_vnode(X, p, &v, 0, 1024)))
		return r;
	    if ((r = ReadByte(X, tag)))
		return r;
	    if (drop) {
		if (p->cb_error)
		    (p->cb_error) (DSERR_FMT, 0, p->err_refcon,
				   "Dropping vnode %d", v.vnode);
		return 0;
	    }
	} else {
	    if ((r = xfseek(X, &where)))
		return r;
	}
    }
    LastGoodVNode = v.vnode;

    if (!r) {
	if (v.field_mask & F_VNODE_TYPE)
	    switch (v.type) {
	    case vFile:
		cb = p->cb_vnode_file;
		break;
	    case vDirectory:
		cb = p->cb_vnode_dir;
		break;
	    case vSymlink:
		cb = p->cb_vnode_link;
		break;
	    default:
		cb = p->cb_vnode_wierd;
		break;
	} else
	    cb = p->cb_vnode_empty;
	if (cb) {
	    u_int64 where;

	    if ((r = xftell(X, &where)))
		return r;
	    r = (cb) (&v, X, p->refcon);
	    if (p->flags & DSFLAG_SEEK) {
		if (!r)
		    r = xfseek(X, &where);
		else
		    xfseek(X, &where);
	    }
	}
    }
    return r;
}
Example #11
0
/* Parse or skip over the vnode data */
static afs_uint32
parse_vdata(XFILE * X, unsigned char *tag, tagged_field * field,
	    afs_uint32 value, tag_parse_info * pi, void *g_refcon,
	    void *l_refcon)
{
    dump_parser *p = (dump_parser *) g_refcon;
    afs_vnode *v = (afs_vnode *) l_refcon;
    static char *symlink_buf = 0;
    static int symlink_size = 0;
    afs_uint32 r;

    if ((r = ReadInt32(X, &v->size)))
	return r;
    v->field_mask |= F_VNODE_SIZE;

    if (v->size) {
	v->field_mask |= F_VNODE_DATA;
	if ((r = xftell(X, &v->d_offset)))
	    return r;
	if (p->print_flags & DSPRINT_VNODE)
	    printf("%s%d (0x%08x) bytes at %s (0x%s)\n", field->label,
		   v->size, v->size, decimate_int64(&v->d_offset, 0),
		   hexify_int64(&v->d_offset, 0));

	switch (v->type) {
	case vSymlink:
	    if (v->size > symlink_size) {
		if (symlink_buf)
		    symlink_buf = (char *)realloc(symlink_buf, v->size + 1);
		else
		    symlink_buf = (char *)malloc(v->size + 1);
		symlink_size = symlink_buf ? v->size : 0;
	    }
	    if (symlink_buf) {
		if ((r = xfread(X, symlink_buf, v->size)))
		    return r;
		symlink_buf[v->size] = 0;
		if (p->print_flags & DSPRINT_VNODE)
		    printf(" Target:       %s\n", symlink_buf);
	    } else {
		/* Call the callback here, because it's non-fatal */
		if (p->cb_error)
		    (p->cb_error) (ENOMEM, 0, p->err_refcon,
				   "Out of memory reading symlink");
		if ((r = xfskip(X, v->size)))
		    return r;
	    }
	    break;

	case vDirectory:
	    if (p->cb_dirent || (p->print_flags & DSPRINT_DIR)) {
		if ((r = parse_directory(X, p, v, v->size, 0)))
		    return r;
		break;
	    }

	default:
	    if ((r = xfskip(X, v->size)))
		return r;
	}
    } else if (p->print_flags & DSPRINT_VNODE) {
	printf("%sEmpty\n", field->label);
    }
    if (p->repair_flags & DSFIX_VDSYNC) {
	r = resync_vnode(X, p, v, 10, 15);
	if (r)
	    return r;
    }
    return ReadByte(X, tag);
}
Example #12
0
File: sct.c Project: vgck/opendr2
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d S C T I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Method ReadSCTImage reads a Scitex image file and returns it.  It allocates
%  the memory necessary for the new Image structure and returns a pointer to
%  the new image.
%
%  The format of the ReadSCTImage method is:
%
%      Image *ReadSCTImage(const ImageInfo *image_info)
%
%  A description of each parameter follows:
%
%    o image:  Method ReadSCTImage returns a pointer to the image after
%      reading.  A null image is returned if there is a memory shortage or
%      if the image cannot be read.
%
%    o image_info: Specifies a pointer to an ImageInfo structure.
%
%
*/
Export Image *ReadSCTImage(const ImageInfo *image_info)
{
  char
    buffer[768],
    magick[2];

  Image
    *image;

  int
    y;

  register int
    x;

  register PixelPacket
    *q;

  unsigned int
    status;

  /*
    Allocate image structure.
  */
  image=AllocateImage(image_info);
  if (image == (Image *) NULL)
    return((Image *) NULL);
  /*
    Open image file.
  */
  status=OpenBlob(image_info,image,ReadBinaryType);
  if (status == False)
    ReaderExit(FileOpenWarning,"Unable to open file",image);
  /*
    Read control block.
  */
  (void) ReadBlob(image,80,(char *) buffer);
  (void) ReadBlob(image,2,(char *) magick);
  if ((strncmp((char *) magick,"CT",2) != 0) &&
      (strncmp((char *) magick,"LW",2) != 0) &&
      (strncmp((char *) magick,"BM",2) != 0) &&
      (strncmp((char *) magick,"PG",2) != 0) &&
      (strncmp((char *) magick,"TX",2) != 0))
    ReaderExit(CorruptImageWarning,"Not a SCT image file",image);
  if ((strncmp((char *) magick,"LW",2) == 0) ||
      (strncmp((char *) magick,"BM",2) == 0) ||
      (strncmp((char *) magick,"PG",2) == 0) ||
      (strncmp((char *) magick,"TX",2) == 0))
    ReaderExit(CorruptImageWarning,"only Continuous Tone Picture supported",
      image);
  (void) ReadBlob(image,174,(char *) buffer);
  (void) ReadBlob(image,768,(char *) buffer);
  /*
    Read paramter block.
  */
  (void) ReadBlob(image,32,(char *) buffer);
  (void) ReadBlob(image,14,(char *) buffer);
  image->rows=atoi(buffer);
  (void) ReadBlob(image,14,(char *) buffer);
  image->columns=atoi(buffer);
  (void) ReadBlob(image,196,(char *) buffer);
  (void) ReadBlob(image,768,(char *) buffer);
  if (image_info->ping)
    {
      CloseBlob(image);
      return(image);
    }
  /*
    Convert SCT raster image to pixel packets.
  */
  image->colorspace=CMYKColorspace;
  for (y=0; y < (int) image->rows; y++)
  {
    q=SetPixelCache(image,0,y,image->columns,1);
    if (q == (PixelPacket *) NULL)
      break;
    for (x=0; x < (int) image->columns; x++)
    {
      q->red=MaxRGB-UpScale(ReadByte(image));
      q++;
    }
    if ((image->columns % 2) != 0)
      (void) ReadByte(image);  /* pad */
    q=GetPixelCache(image,0,y,image->columns,1);
    if (q == (PixelPacket *) NULL)
      break;
    for (x=0; x < (int) image->columns; x++)
    {
      q->green=MaxRGB-UpScale(ReadByte(image));
      q++;
    }
    if ((image->columns % 2) != 0)
      (void) ReadByte(image);  /* pad */
    q=GetPixelCache(image,0,y,image->columns,1);
    if (q == (PixelPacket *) NULL)
      break;
    for (x=0; x < (int) image->columns; x++)
    {
      q->blue=MaxRGB-UpScale(ReadByte(image));
      q++;
    }
    if ((image->columns % 2) != 0)
      (void) ReadByte(image);  /* pad */
    q=GetPixelCache(image,0,y,image->columns,1);
    if (q == (PixelPacket *) NULL)
      break;
    for (x=0; x < (int) image->columns; x++)
    {
      q->opacity=MaxRGB-UpScale(ReadByte(image));
      q++;
    }
    if (!SyncPixelCache(image))
      break;
    if ((image->columns % 2) != 0)
      (void) ReadByte(image);  /* pad */
    if (QuantumTick(y,image->rows))
      ProgressMonitor(LoadImageText,y,image->rows);
  }
  return(image);
}
Example #13
0
	int Stream::Read(unsigned char *buffer, int offset, int count)
	{
		int i = offset;
		for (; i < count && GetPosition() < Length(); i++) buffer[i] = ReadByte();
		return i - offset;
	}
Example #14
0
HRESULT CDecoder::DecodeFile(ICompressProgressInfo *progress)
{
  Progress = progress;
  #ifndef _7ZIP_ST
  RINOK(Create());
  for (UInt32 t = 0; t < NumThreads; t++)
  {
    CState &s = m_States[t];
    if (!s.Alloc())
      return E_OUTOFMEMORY;
    if (MtMode)
    {
      RINOK(s.StreamWasFinishedEvent.Reset());
      RINOK(s.WaitingWasStartedEvent.Reset());
      RINOK(s.CanWriteEvent.Reset());
    }
  }
  #else
  if (!m_States[0].Alloc())
    return E_OUTOFMEMORY;
  #endif

  IsBz = false;

  /*
  if (Base.BitDecoder.ExtraBitsWereRead())
    return E_FAIL;
  */

  Byte s[4];
  unsigned i;
  for (i = 0; i < 4; i++)
    s[i] = ReadByte();
  if (Base.BitDecoder.ExtraBitsWereRead())
    return S_FALSE;

  if (s[0] != kArSig0 ||
      s[1] != kArSig1 ||
      s[2] != kArSig2 ||
      s[3] <= kArSig3 ||
      s[3] > kArSig3 + kBlockSizeMultMax)
    return S_FALSE;

  UInt32 dicSize = (UInt32)(s[3] - kArSig3) * kBlockSizeStep;

  CombinedCrc.Init();
  #ifndef _7ZIP_ST
  if (MtMode)
  {
    NextBlockIndex = 0;
    StreamWasFinished1 = StreamWasFinished2 = false;
    CloseThreads = false;
    CanStartWaitingEvent.Reset();
    m_States[0].CanWriteEvent.Set();
    BlockSizeMax = dicSize;
    Result1 = Result2 = S_OK;
    CanProcessEvent.Set();
    UInt32 t;
    for (t = 0; t < NumThreads; t++)
      m_States[t].StreamWasFinishedEvent.Lock();
    CanProcessEvent.Reset();
    CanStartWaitingEvent.Set();
    for (t = 0; t < NumThreads; t++)
      m_States[t].WaitingWasStartedEvent.Lock();
    CanStartWaitingEvent.Reset();
    RINOK(Result2);
    RINOK(Result1);
  }
  else
  #endif
  {
    CState &state = m_States[0];
    for (;;)
    {
      RINOK(SetRatioProgress(Base.BitDecoder.GetProcessedSize()));
      UInt32 crc;
      RINOK(ReadSignature(crc));
      if (BzWasFinished)
        return S_OK;

      CBlockProps props;
      props.randMode = true;
      RINOK(Base.ReadBlock(state.Counters, dicSize, &props));
      DecodeBlock1(state.Counters, props.blockSize);
      if (DecodeBlock(props, state.Counters + 256, m_OutStream) != crc)
      {
        CrcError = true;
        return S_FALSE;
      }
    }
  }
  return SetRatioProgress(Base.BitDecoder.GetProcessedSize());
}
Example #15
0
bool ON_BinaryArchive::ReadInflate(
        size_t sizeof___outbuffer,  // sizeof uncompressed data
        void* out___buffer          // buffer for uncompressed data
        )
{
  const size_t max_avail = 0x7FFFFFF0; // See max_avail comment in ON_BinaryArchive::WriteInflate

  size_t sizeof__inbuffer = 0;
  void* in___buffer = 0;
  bool rc = false;

  // read compressed buffer from 3dm archive
  bool bValidCompressedBuffer = false;
  {
    unsigned int tcode = 0;
    unsigned int value = 0; // value must be unsigned
    rc = BeginRead3dmChunk(&tcode,(int*)(&value) );
    if (!rc)
    {
      if ( 0 != out___buffer && sizeof___outbuffer > 0 )
        memset(out___buffer,0,sizeof___outbuffer);
      return false;
    }
    if (   tcode == TCODE_ANONYMOUS_CHUNK
        && value > 4
        && sizeof___outbuffer > 0
        && 0 != out___buffer )
    {
      // read compressed buffer from the archive
      sizeof__inbuffer = value-4; // the last 4 bytes in this chunk are a 32 bit crc
      in___buffer = onmalloc(sizeof__inbuffer);
      if ( !in___buffer )
      {
        rc = false;
      }
      else
      {
        rc = ReadByte( sizeof__inbuffer, in___buffer );
      }
    }
    else
    {
      // Either I have the wrong chunk, or the input
      // parameters are bogus.
      rc = false;
    }
    int c0 = m_bad_CRC_count;
    if ( !EndRead3dmChunk() )
    {
      rc = false;
    }
    bValidCompressedBuffer = ( m_bad_CRC_count > c0 )
                           ? false
                           : rc;
  }

  if ( !bValidCompressedBuffer && 0 != out___buffer && sizeof___outbuffer > 0 )
  {
    // Decompression will fail, but we might get something valid
    // at the start if the data flaw was near the end of the buffer.
    memset(out___buffer,0,sizeof___outbuffer);
  }

  if ( !rc )
  {
    if ( in___buffer )
    {
      onfree(in___buffer);
      in___buffer = 0;
    }
    return false;
  }

  int zrc = -1;

  // set up zlib in buffer
  unsigned char* my_next_in = (unsigned char*)in___buffer;
  size_t my_avail_in = sizeof__inbuffer;

  size_t d = my_avail_in;
  if ( d > max_avail )
    d = max_avail;
  m_zlib.strm.next_in  = my_next_in;
  m_zlib.strm.avail_in = (unsigned int)d;
  my_next_in  += d;
  my_avail_in -= d;

  // set up zlib out buffer
  unsigned char* my_next_out = (unsigned char*)out___buffer;
  size_t my_avail_out = sizeof___outbuffer;

  d = my_avail_out;
  if ( d > max_avail )
    d = max_avail;
  m_zlib.strm.next_out  = my_next_out;
  m_zlib.strm.avail_out = (unsigned int)d;
  my_next_out  += d;
  my_avail_out -= d;

  // counter guards against infinte loop if there are
  // bugs in zlib return codes
  int counter = 512;
  int flush = Z_NO_FLUSH;

  while ( rc && counter > 0 )
  {
    // Call zlib's inflate function.  It can either process
    // more input from m_zlib.strm.next_in[], create more
    // uncompressed output in m_zlib.strm.next_out[], or do both.
    if ( 0 == my_avail_in && 0 == m_zlib.strm.avail_in )
    {
      // no compressed input is left - switch to finish mode
      flush = Z_FINISH;
    }
    zrc = inflate( &m_zlib.strm, flush );
    if ( zrc < 0 )
    {
      // Something went haywire - bail out.
      ON_ERROR("ON_BinaryArchive::ReadInflate - inflate failure");
      rc = false;
      break;
    }

    if ( Z_FINISH == flush && Z_STREAM_END == zrc )
    {
      // no input left, all pending decompression is finished,
      // and all decompressed output has been returned.
      break;
    }

    d = 0;
    if ( my_avail_in > 0 && m_zlib.strm.avail_in < max_avail )
    {
      if ( 0 == m_zlib.strm.avail_in || 0 == m_zlib.strm.next_in )
      {
        // The call to inflate() used up all the input
        // in m_zlib.strm.next_in[].  I can feed it another chunk
        // from inbuffer[]
        d = my_avail_in;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_in  = my_next_in;
        m_zlib.strm.avail_in = (unsigned int)d;
      }
      else
      {
        // The call to inflate() left some input in m_zlib.strm.next_in[],
        // but I can increase m_zlib.strm.avail_in.
        d =  max_avail - m_zlib.strm.avail_in;
        if ( d > my_avail_in )
          d = my_avail_in;
        m_zlib.strm.avail_in += (unsigned int)d;
      }
      my_next_in  += d;
      my_avail_in -= d;
    }

    if ( my_avail_out > 0 && m_zlib.strm.avail_out < max_avail )
    {
      // increase m_zlib.strm.next_out[] buffer
      if ( 0 == m_zlib.strm.avail_out || 0 == m_zlib.strm.next_out )
      {
        d = my_avail_out;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_out  = my_next_out;
        m_zlib.strm.avail_out = (unsigned int)d;
      }
      else
      {
        d = max_avail - m_zlib.strm.avail_out;
        if ( d > my_avail_out )
          d = my_avail_out;
        m_zlib.strm.avail_out += ((unsigned int)d);
      }
      my_next_out  += d;
      my_avail_out -= d;
    }
    else if ( 0 == d )
    {
      // no buffer changes
      counter--;
    }
  }

  if (in___buffer )
  {
    onfree(in___buffer);
    in___buffer = 0;
  }

  if ( 0 == counter )
  {
    rc = false;
  }

  return rc;
}
Example #16
0
DWORD CHdmvClipInfo::ReadDword()
{
    return ReadByte() << 24 | ReadByte() << 16 | ReadByte() << 8 | ReadByte();
}
	bool BufferReader::ReadBoolean() const
	{
		return ReadByte() != 0;
	}
Example #18
0
short CHdmvClipInfo::ReadShort()
{
    return ReadByte() << 8 | ReadByte();
}
Example #19
0
void CInArchive::ReadBytes(Byte *data, UInt32 size)
{
  for (UInt32 i = 0; i < size; i++)
    data[i] = ReadByte();
}
Example #20
0
HRESULT CHdmvClipInfo::ReadProgramInfo()
{
    BYTE number_of_program_sequences;
    BYTE number_of_streams_in_ps;
    LARGE_INTEGER Pos;

    m_Streams.RemoveAll();
    Pos.QuadPart = ProgramInfo_start_address;
    SetFilePointerEx(m_hFile, Pos, NULL, FILE_BEGIN);

    ReadDword();    //length
    ReadByte();     //reserved_for_word_align
    number_of_program_sequences = (BYTE)ReadByte();
    int iStream = 0;
    for (size_t i = 0; i < number_of_program_sequences; i++) {
        ReadDword();    //SPN_program_sequence_start
        ReadShort();    //program_map_PID
        number_of_streams_in_ps = (BYTE)ReadByte(); //number_of_streams_in_ps
        ReadByte();     //reserved_for_future_use

        for (size_t stream_index = 0; stream_index < number_of_streams_in_ps; stream_index++) {
            m_Streams.SetCount(iStream + 1);
            m_Streams[iStream].m_PID = ReadShort();  // stream_PID

            // == StreamCodingInfo
            Pos.QuadPart = 0;
            SetFilePointerEx(m_hFile, Pos, &Pos, FILE_CURRENT);
            Pos.QuadPart += ReadByte() + 1; // length
            m_Streams[iStream].m_Type = (PES_STREAM_TYPE)ReadByte();

            switch (m_Streams[iStream].m_Type) {
                case VIDEO_STREAM_MPEG1:
                case VIDEO_STREAM_MPEG2:
                case VIDEO_STREAM_H264:
                case VIDEO_STREAM_VC1: {
                    UINT8 Temp = ReadByte();
                    BDVM_VideoFormat VideoFormat = (BDVM_VideoFormat)(Temp >> 4);
                    BDVM_FrameRate FrameRate = (BDVM_FrameRate)(Temp & 0xf);
                    Temp = ReadByte();
                    BDVM_AspectRatio AspectRatio = (BDVM_AspectRatio)(Temp >> 4);

                    m_Streams[iStream].m_VideoFormat = VideoFormat;
                    m_Streams[iStream].m_FrameRate = FrameRate;
                    m_Streams[iStream].m_AspectRatio = AspectRatio;
                }
                break;
                case AUDIO_STREAM_MPEG1:
                case AUDIO_STREAM_MPEG2:
                case AUDIO_STREAM_LPCM:
                case AUDIO_STREAM_AC3:
                case AUDIO_STREAM_DTS:
                case AUDIO_STREAM_AC3_TRUE_HD:
                case AUDIO_STREAM_AC3_PLUS:
                case AUDIO_STREAM_DTS_HD:
                case AUDIO_STREAM_DTS_HD_MASTER_AUDIO:
                case SECONDARY_AUDIO_AC3_PLUS:
                case SECONDARY_AUDIO_DTS_HD: {
                    UINT8 Temp = ReadByte();
                    BDVM_ChannelLayout ChannelLayout = (BDVM_ChannelLayout)(Temp >> 4);
                    BDVM_SampleRate SampleRate = (BDVM_SampleRate)(Temp & 0xF);

                    ReadBuffer((BYTE*)m_Streams[iStream].m_LanguageCode, 3);
                    m_Streams[iStream].m_LCID = ISO6392ToLcid(m_Streams[iStream].m_LanguageCode);
                    m_Streams[iStream].m_ChannelLayout = ChannelLayout;
                    m_Streams[iStream].m_SampleRate = SampleRate;
                }
                break;
                case PRESENTATION_GRAPHICS_STREAM:
                case INTERACTIVE_GRAPHICS_STREAM: {
                    ReadBuffer((BYTE*)m_Streams[iStream].m_LanguageCode, 3);
                    m_Streams[iStream].m_LCID = ISO6392ToLcid(m_Streams[iStream].m_LanguageCode);
                }
                break;
                case SUBTITLE_STREAM: {
                    ReadByte(); // Should this really be here?
                    ReadBuffer((BYTE*)m_Streams[iStream].m_LanguageCode, 3);
                    m_Streams[iStream].m_LCID = ISO6392ToLcid(m_Streams[iStream].m_LanguageCode);
                }
                break;
                default:
                    break;
            }

            iStream++;
            SetFilePointerEx(m_hFile, Pos, NULL, FILE_BEGIN);
        }
    }
    return S_OK;
}
Example #21
0
void CxdsBuffer::SkipWhite(void)
{
	while(isspace(Lookahead(0)))
		(void)ReadByte();
}
Example #22
0
	BOOL ReadStruct (

/*  SYNOPSIS */
	struct Hook * hook,
	APTR	    * dataptr,
	void	    * stream,
	const IPTR  * sd)

/*  FUNCTION
	Reads one big endian structure from a streamhook.

    INPUTS
	hook - Streamhook
	dataptr - Put the data here
	stream - Read from this stream
	sd - Description of the structure to be read. The first element
		is the size of the structure.

    RESULT
	The function returns TRUE on success. On success, the value
	read is written into dataptr. On failure, FALSE is returned and the
	contents of dataptr are not changed.

    NOTES
	This function reads big endian values from a streamhook even on
	little endian machines.

    EXAMPLE
	See below.

    BUGS

    SEE ALSO
	ReadByte(), ReadWord(), ReadLong(), ReadFloat(), ReadDouble(),
	ReadString(), ReadStruct(), WriteByte(), WriteWord(), WriteLong(),
	WriteFloat(), WriteDouble(), WriteString(), WriteStruct()

    HISTORY

******************************************************************************/
{
    struct MinList     _list;
    struct ReadLevel * curr;

#   define list     ((struct List *)&_list)

    NEWLIST(list);

    if (!(curr = AllocMem (sizeof (struct ReadLevel), MEMF_ANY)) )
	return FALSE;

    AddTail (list, (struct Node *)curr);

    curr->sd  = sd;
    curr->pos = 0;
    curr->s   = NULL;

#   define DESC     curr->sd[curr->pos]
#   define IDESC    curr->sd[curr->pos ++]

    for (;;)
    {
	if (!curr->pos)
	{
	    if (!(curr->s = AllocMem (IDESC, MEMF_CLEAR)) )
		goto error;
	}

	if (DESC == SDT_END)
	    break;

	switch (IDESC)
	{
	case SDT_UBYTE:      /* Read one  8bit byte */
	    if (!ReadByte (hook, (UBYTE *)(curr->s + IDESC), stream))
		goto error;

	    break;

	case SDT_UWORD:      /* Read one 16bit word */
	    if (!ReadWord (hook, (UWORD *)(curr->s + IDESC), stream))
		goto error;

	    break;

	case SDT_ULONG:      /* Read one 32bit long */
	    if (!ReadLong (hook, (ULONG *)(curr->s + IDESC), stream))
		goto error;

	    break;

	case SDT_FLOAT:      /* Read one 32bit IEEE */
	    if (!ReadFloat (hook, (FLOAT *)(curr->s + IDESC), stream))
		goto error;

	    break;

	case SDT_DOUBLE:     /* Read one 64bit IEEE */
	    if (!ReadDouble (hook, (DOUBLE *)(curr->s + IDESC), stream))
		goto error;

	    break;

	case SDT_STRING: {   /* Read a string */
	    UBYTE    valid_ptr;
	    STRPTR * sptr;

	    sptr = (STRPTR *)(curr->s + IDESC);

	    if (!ReadByte (hook, &valid_ptr, stream))
		goto error;

	    if (valid_ptr)
	    {
		if (!ReadString (hook, sptr, stream))
		    goto error;
	    }
	    else
	    {
		*sptr = NULL;
	    }

	    break; }

	case SDT_STRUCT: {    /* Read a structure */
	    struct ReadLevel * next;
	    IPTR * desc;
	    APTR   aptr;

	    aptr = (APTR)(curr->s + IDESC);
	    desc = (IPTR *)IDESC;

	    curr->pos -= 3; /* Go back to type */

	    if (!(next = AllocMem (sizeof (struct ReadLevel), MEMF_ANY)) )
		goto error;

	    AddTail (list, (struct Node *)next);
	    next->sd  = desc;
	    next->pos = 1;
	    next->s   = aptr;

	    curr = next;

	    break; }

	case SDT_PTR: {    /* Follow a pointer */
	    struct ReadLevel * next;

	    UBYTE  valid_ptr;
	    IPTR * desc;
	    APTR * aptr;

	    aptr = ((APTR *)(curr->s + IDESC));
	    desc = (IPTR *)IDESC;

	    if (!ReadByte (hook, &valid_ptr, stream))
		goto error;

	    if (valid_ptr)
	    {
		curr->pos -= 3;

		if (!(next = AllocMem (sizeof (struct ReadLevel), MEMF_ANY)) )
		    goto error;

		AddTail (list, (struct Node *)next);
		next->sd  = desc;
		next->pos = 0;

		curr = next;
	    }
	    else
	    {
		*aptr = NULL;
	    }

	    break; }

	case SDT_IGNORE: {   /* Ignore x bytes */
        struct BEIOM_Ignore ig = {BEIO_IGNORE, IDESC};
	    if (CallHookA (hook, stream, &ig) == EOF)
		goto error;

	    break; }

	case SDT_FILL_BYTE: { /* Fill x bytes */
	    IPTR  offset;
	    UBYTE value;
	    IPTR  count;

	    offset = IDESC;
	    value  = IDESC;
	    count  = IDESC;

	    memset (curr->s + offset, value, count);

	    break; }

	case SDT_FILL_LONG: { /* Fill x longs */
	    ULONG * ulptr;
	    ULONG   value;
	    IPTR    count;

	    ulptr = (ULONG *)(curr->s + IDESC);
	    value = IDESC;
	    count = IDESC;

	    while (count --)
		*ulptr ++ = value;

	    break; }

	case SDT_IFILL_BYTE: { /* Fill x bytes */
	    IPTR  offset;
	    UBYTE value;
	    IPTR  count;

	    offset = IDESC;
	    value  = IDESC;
	    count  = IDESC;

        struct BEIOM_Ignore ig = {BEIO_IGNORE, count};

	    if (CallHookA (hook, stream, &ig) == EOF)
		goto error;

	    memset (curr->s + offset, value, count);

	    break; }

	case SDT_IFILL_LONG: { /* Fill x longs */
	    ULONG * ulptr;
	    ULONG   value;
	    IPTR    count;

	    ulptr = (ULONG *)(curr->s + IDESC);
	    value = IDESC;
	    count = IDESC;

        struct BEIOM_Ignore ig = {BEIO_IGNORE, count << 2};

	    if (CallHookA (hook, stream, &ig) == EOF)
		goto error;

	    while (count --)
		*ulptr ++ = value;

	    break; }

	case SDT_SPECIAL: {   /* Call user hook */
	    struct Hook * uhook;
	    struct SDData data;

	    data.sdd_Dest   = ((APTR)(curr->s + IDESC));
	    data.sdd_Mode   = SDV_SPECIALMODE_READ;
	    data.sdd_Stream = stream;

	    uhook = (struct Hook *)IDESC;

	    if (!CallHookA (uhook, hook, &data))
	    	goto error;

	    break; }

	default:
	    goto error;

	} /* switch */

	/* End of the description list ? */
	if (DESC == SDT_END)
	{
	    struct ReadLevel * last;

	    /* Remove the current level */
	    last = curr;
	    Remove ((struct Node *)last);

	    /* Get the last level */
	    if ((curr = (struct ReadLevel *)GetTail (list)))
	    {
		switch (IDESC)
		{
		case SDT_STRUCT:
		    curr->pos += 2; /* Skip 2 parameters */
		    break;

		case SDT_PTR: {
		    APTR * aptr;

		    aptr  = ((APTR *)(curr->s + IDESC));
		    curr->pos ++; /* Skip description parameter */

		    /*
			Now put the result of the current level in the
			struct of the previous level.
		    */
		    *aptr = last->s;

		    break; }

		}

		FreeMem (last, sizeof (struct ReadLevel));
	    }
	    else
	    {
		curr = last;
	    }
	}
    } /* while */

    *dataptr = curr->s;

    FreeMem (curr, sizeof (struct ReadLevel));

    return TRUE;

error:
    curr = (struct ReadLevel *)GetHead (list);

    if (curr && curr->s)
	FreeStruct (curr->s, curr->sd);

    while ((curr = (struct ReadLevel *)RemTail (list)))
	FreeMem (curr, sizeof (struct ReadLevel));

    return FALSE;
} /* ReadStruct */
Example #23
0
uchar CPU::ReadImm8Arg()
{
	return ReadByte(PC + 1);
}
Example #24
0
     byte=ReadByte(image);
     for (i=0; i < count; i++)
     {
       if (compression == 1)
         *q++=(unsigned char) byte;
       else
         *q++=(i & 0x01) ? (byte & 0x0f) : ((byte >> 4) & 0x0f);
       x++;
     }
   }
 else
   {
     /*
       Escape mode.
     */
     count=ReadByte(image);
     if (count == 0x01)
       return(True);
     switch (count)
     {
       case 0x00:
       {
         /*
           End of line.
         */
         x=0;
         y++;
         q=pixels+y*number_columns;
         break;
       }
       case 0x02:
Example #25
0
    Dantestrasse 20
    04159 Leipzig
    Deutschland / Germany
    E-mail: [email protected] */

/*
 * This file was created automatically out of the DM2 specs.
 * This ensures the necessary equvivalence and simplifies my task of writing
 * corresponding specs and programs.
 */

/* udm2-te2.c */

/* read binary into variables */

entitytype = ReadByte(m);
switch (entitytype) {
  /* version problems */
  /* case DM2_TE_PLASMATRAIL: */
  case DM2_TE_GREENBLOOD_new:
    if (SERVERVERSION >= 32) /* game version >= 3.15 */
      goto impact_entity_1;
    else
      goto line_entity_1;
  break;
  /* case DM2_TE_GREENBLOOD_old: */
  case DM2_TE_BLUEHYPERBLASTER:
    if (SERVERVERSION >= 32) /* game version >= 3.15 */
      goto line_entity_1;
    else
      goto impact_entity_1;
Example #26
0
void PLPCXDecoder::GetImage (PLBmpBase & Bmp)
{
  int i, x, y;
  PLBYTE ColorMap[PCX_MAXCOLORS][3];
  PLBYTE * pcximage = NULL;
  PLBYTE * lpHead1 = NULL;
  PLBYTE * lpHead2 = NULL;
  PLBYTE * pcxplanes;
  PLBYTE * pcxpixels;
  PLBYTE c;
  int nbytes, count;

  Trace (2, "PCX getimage.\n");

  try
  {
    nbytes = m_PcxHeader.BytesPerLine * m_PcxHeader.ColorPlanes * GetHeight();
    lpHead1 = pcximage = (PLBYTE *)malloc(nbytes);
    try
    {
      while (nbytes > 0)
      {
        c = ReadByte(m_pDataSrc);
        if ((c & 0XC0) != 0XC0) // Repeated group
        {
          *pcximage++ = c;
          --nbytes;
          continue;
        }
        count = c & 0X3F; // extract count
        c = ReadByte(m_pDataSrc);
        if (count > nbytes)
        {
          raiseError(PL_ERRINTERNAL, "repeat count spans end of image.");
        }
        nbytes -= count;
        while (--count >=0)
          *pcximage++ = c;
      }
    }
    catch (PLTextException e)
    {
      // Just in case BytesPerLine is bogus.
      // This will fall apart for images that have a palette after the
      // image data, however.
      if (e.GetCode() != PL_ERREND_OF_FILE)
        throw;
    }
    pcximage = lpHead1;

    for (i = 0; i < 16; i++)
    {
      ColorMap[i][0] = m_PcxHeader.ColorMap[i][0];
      ColorMap[i][1] = m_PcxHeader.ColorMap[i][1];
      ColorMap[i][2] = m_PcxHeader.ColorMap[i][2];
    }
    if (m_PcxHeader.BitsPerPixel == 8 && m_PcxHeader.ColorPlanes == 1)
    {
/* It seems like valid PCXs exist with a bad color map signature...
      PLBYTE colsig = ReadByte(m_pDataSrc);
      if (colsig != PCX_256_COLORS)
      {
        raiseError(PL_ERRINTERNAL, "bad color map signature.");
      }
*/
      for (i = 0; i < PCX_MAXCOLORS; i++)
      {
        ColorMap[i][0] = ReadByte(m_pDataSrc);
        ColorMap[i][1] = ReadByte(m_pDataSrc);
        ColorMap[i][2] = ReadByte(m_pDataSrc);
      }
    }
    if (m_PcxHeader.BitsPerPixel == 1 && m_PcxHeader.ColorPlanes == 1)
    {
      ColorMap[0][0] = ColorMap[0][1] = ColorMap[0][2] = 0;
      ColorMap[1][0] = ColorMap[1][1] = ColorMap[1][2] = 255;
    }

    lpHead2 = pcxpixels = (PLBYTE *)malloc(GetWidth() + m_PcxHeader.BytesPerLine * 8);
    // Convert the image
    PLPixel32 ** pLineArray = Bmp.GetLineArray32();
    for (y = 0; y < GetHeight(); y++)
    {
      pcxpixels = lpHead2;
      pcxplanes = pcximage + (y * m_PcxHeader.BytesPerLine * m_PcxHeader.ColorPlanes);
      if (m_PcxHeader.ColorPlanes == 3 && m_PcxHeader.BitsPerPixel == 8)
      {
        // Deal with 24 bit color image
        for (x = 0; x < GetWidth(); x++)
        {
          PLPixel32 * pPixel = pLineArray[y];
          pPixel[x].Set (pcxplanes[x],
                         pcxplanes[m_PcxHeader.BytesPerLine + x],
                         pcxplanes[2*m_PcxHeader.BytesPerLine + x],
                         0xFF);
        }
        continue;
      }
      else if (m_PcxHeader.ColorPlanes == 1)
      {
        PCX_UnpackPixels(pcxpixels, pcxplanes, m_PcxHeader.BytesPerLine, m_PcxHeader.ColorPlanes, m_PcxHeader.BitsPerPixel);
      }
      else
      {
        PCX_PlanesToPixels(pcxpixels, pcxplanes, m_PcxHeader.BytesPerLine, m_PcxHeader.ColorPlanes, m_PcxHeader.BitsPerPixel);
      }
      for (x = 0; x < GetWidth(); x++)
      {
        i = pcxpixels[x];
        PLPixel32 * pPixel = pLineArray[y];
        pPixel[x].Set (ColorMap[i][0], ColorMap[i][1],
                       ColorMap[i][2], 0xFF);
      }
    }
  }

  catch (PLTextException)
  {
    if (lpHead1)
    {
      free(lpHead1);
      lpHead1 = NULL;
    }
    if (lpHead2)
    {
      free(lpHead2);
      lpHead2 = NULL;
    }
    throw;
  }

  if (lpHead1)
  {
    free(lpHead1);
    lpHead1 = NULL;
  }
  if (lpHead2)
  {
    free(lpHead2);
    lpHead2 = NULL;
  }
}
Example #27
0
static HRESULT BmpFrameDecode_ReadRLE4(BmpDecoder* This)
{
    UINT bytesperrow;
    UINT width, height;
    BYTE rledata[4096];
    UINT datasize, palettesize;
    DWORD palette[16];
    UINT x, y;
    DWORD *bgrdata;
    HRESULT hr;
    LARGE_INTEGER offbits;
    ULONG cursor=0, bytesread=0;

    width = This->bih.bV5Width;
    height = abs(This->bih.bV5Height);
    bytesperrow = width * 4;
    datasize = bytesperrow * height;
    if (This->bih.bV5ClrUsed && This->bih.bV5ClrUsed < 16)
        palettesize = 4 * This->bih.bV5ClrUsed;
    else
        palettesize = 4 * 16;

    This->imagedata = HeapAlloc(GetProcessHeap(), 0, datasize);
    if (!This->imagedata)
    {
        hr = E_OUTOFMEMORY;
        goto fail;
    }

    /* read palette */
    offbits.QuadPart = This->palette_offset;
    hr = IStream_Seek(This->stream, offbits, STREAM_SEEK_SET, NULL);
    if (FAILED(hr)) goto fail;

    hr = IStream_Read(This->stream, palette, palettesize, &bytesread);
    if (FAILED(hr) || bytesread != palettesize) goto fail;

    /* read RLE data */
    offbits.QuadPart = This->image_offset;
    hr = IStream_Seek(This->stream, offbits, STREAM_SEEK_SET, NULL);
    if (FAILED(hr)) goto fail;

    /* decode RLE */
    bgrdata = (DWORD*)This->imagedata;
    x = 0;
    y = 0;
    cursor = 0;
    bytesread = 0;
    while (y < height)
    {
        BYTE length;
        hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &length);

        if (FAILED(hr))
            goto fail;
        else if (length == 0)
        {
            /* escape code */
            BYTE escape;
            hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &escape);
            if (FAILED(hr))
                goto fail;
            switch(escape)
            {
            case 0: /* end of line */
                x = 0;
                y++;
                break;
            case 1: /* end of bitmap */
                goto end;
            case 2: /* delta */
            {
                BYTE dx, dy;
                hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &dx);
                if (SUCCEEDED(hr))
                    hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &dy);
                if (FAILED(hr))
                    goto fail;
                x += dx;
                y += dy;
                break;
            }
            default: /* absolute mode */
            {
                BYTE realsize=0;
                length = escape;
                while (length-- && x < width)
                {
                    BYTE colors;
                    hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &colors);
                    realsize++;
                    if (FAILED(hr))
                        goto fail;
                    bgrdata[y*width + x++] = palette[colors>>4];
                    if (length-- && x < width)
                        bgrdata[y*width + x++] = palette[colors&0xf];
                    else
                        break;
                }
                if (realsize & 1)
                    hr = ReadByte(This->stream, rledata, 4096, &cursor, &bytesread, &length); /* skip pad byte */
                if (FAILED(hr))
                    goto fail;
            }
            }
        }
        else
        {
void idZeroRunLengthCompressor::ReadBytes( byte * dest, int count ) {
	for ( int i = 0; i < count; i++ ) {
		*dest++ = ReadByte();
	}
}
Example #29
0
main (int argc, char *argv[])
{
  int            i, j, k, n;
  FILE           *ifp, *ofp, *mfp=0, *qfp=0;
  float          *phase;     /* array */ 
  float          *soln;      /* array */ 
  float          *qual_map;  /* array */ 
  float          *rarray;    /* array */
  float          *zarray;    /* array */
  float          *parray;    /* array */
  float          *dxwts;     /* array */
  float          *dywts;     /* array */
  unsigned char  *bitflags;
  double         *xcos, *ycos;
  char           buffer[200], tempstr[200];
  char           infile[200], outfile[200];
  char           bmaskfile[200], qualfile[200];
  char           format[200], modekey[200];
  int            in_format, debug_flag;
  int            xsize, ysize;   /* dimensions of arrays */ 
  int            xsize_actual, ysize_actual, xsize_dct, ysize_dct;
  int            avoid_code, thresh_flag, fatten, tsize;
  int            num_iter=DEFAULT_NUM_ITER;
  int            pcg_iter=DEFAULT_PCG_ITER;
  double         rmin, rmax, rscale, e0=DEFAULT_E0;
  double         one_over_twopi = 1.0/TWOPI;
  UnwrapMode     mode;
  char           use[] =     /* define usage statement */
    "Usage: prog-name -input file -format fkey -output file\n"
    "  -xsize x -ysize y [ -mode mkey -bmask file -corr file\n"
    "  -tsize size -debug yes/no -iter num -pcg_iter nump\n"
    "  -e0 e0val -thresh yes/no -fat n ]\n"
    "where 'fkey' is a keyword designating the input file type\n"
    "(key = complex8, complex4, float or byte), 'x' and 'y' are\n"
    "the dimensions of the file, bmask is an optional byte-file\n"
    "for masking out undefined phase, corr is an optional byte-\n"
    "file of cross-correlation values, tsize is the size of the\n"
    "square template for averaging the corr file or quality\n"
    "values (default = 1), and 'mkey' is a keyword designating\n"
    "the type of quality map.  The value of mkey may be\n"
    "'min_grad' for Minimum Gradient, 'min_var' for Minimum\n"
    "Variance, 'max_corr' for Maximum Correlation, 'max_pseu' for\n"
    "Maximum Pseudocorrelation, or 'none' for no quality map.\n" 
    "All files are simple raster files, and the output file\n"
    "is a raster file of elevation values of the unwrapped\n"
    "surface.  If the 'debug' parm is 'yes', then intermediate\n"
    "byte-files are saved.  The maximum number of iterations is\n"
    "'num', and the number of PCG iterations is 'nump'.  The\n"
    "normalization parameter is 'e0'.  To apply an automatic\n"
    "threshold to the quality map, the 'thresh' parm should be\n"
    "yes.  To thicken the quality mask, the 'fat' parm should be\n"
    "the number of pixels by which to fatten it.\n";
  
  printf("Phase Unwrapping by Minimum Lp Norm Algorithm\n");
  
  /* GET COMMAND LINE PARAMETERS AND CHECK */
  CommandLineParm(argc,argv, "-input", StringParm, infile, 1, use);
  CommandLineParm(argc,argv, "-format", StringParm, format, 1, use);
  CommandLineParm(argc,argv, "-output", StringParm, outfile, 1,use);
  CommandLineParm(argc,argv, "-xsize", IntegerParm, &xsize, 1, use);
  CommandLineParm(argc,argv, "-ysize", IntegerParm, &ysize, 1, use);
  if (!CommandLineParm(argc, argv, "-mode", StringParm,
        modekey, 0, use)) strcpy(modekey, "none");
  if (!CommandLineParm(argc, argv, "-corr", StringParm,
        qualfile, 0, use)) strcpy(qualfile, "none");
  if (!CommandLineParm(argc, argv, "-tsize", IntegerParm,
        &tsize, 0, use)) tsize = 1;
  if (!CommandLineParm(argc, argv, "-bmask", StringParm, bmaskfile,
        0, use)) strcpy(bmaskfile, "none");
  if (!CommandLineParm(argc, argv, "-debug", StringParm, tempstr,
        0, use)) debug_flag = 0;
  else debug_flag = Keyword(tempstr, "yes");
  if (!CommandLineParm(argc, argv, "-thresh", StringParm,
        tempstr, 0, use)) thresh_flag = 0;
  else thresh_flag = Keyword(tempstr, "yes");
  if (!CommandLineParm(argc, argv, "-fat", IntegerParm,
        &fatten, 0, use)) fatten = 0;
  CommandLineParm(argc, argv, "-iter", IntegerParm, &num_iter,
                  0, use);
  if (num_iter < 0) num_iter = 1;
  CommandLineParm(argc, argv, "-pcg_iter", IntegerParm, &pcg_iter,
                  0, use);
  if (pcg_iter < 0) pcg_iter = 1;
  CommandLineParm(argc, argv, "-e0", DoubleParm, &e0, 0, use);

  if (Keyword(format, "complex8"))  in_format = 0;
  else if (Keyword(format, "complex4"))  in_format = 1;
  else if (Keyword(format, "byte"))  in_format = 2;
  else if (Keyword(format, "float"))  in_format = 3;
  else {
    fprintf(stderr, "Unrecognized format: %s\n", format);
    exit(BAD_PARAMETER);
  }

  printf("Input file =  %s\n", infile);
  printf("Input file type = %s\n", format);
  printf("Output file =  %s\n", outfile);
  printf("File dimensions = %dx%d (cols x rows).\n", xsize, ysize);
  if (Keyword(bmaskfile, "none")) printf("No border mask file.\n");
  else printf("Border mask file = %s\n", bmaskfile);
  printf("Quality mode = %s\n", modekey);
  if (modekey==none) {
    printf("No quality map.\n");
    strcpy(qualfile, "none");
  }
  else {
    if (Keyword(qualfile, "none")) printf("No correlation file.\n");
    else printf("Correlation image file = %s\n", qualfile);
    printf("Averaging template size = %d\n", tsize);
    if (tsize < 0 || tsize > 30) {
      fprintf(stderr, "Illegal size: must be between 0 and 30\n");
      exit(BAD_PARAMETER);
    }
  }
  mode = SetQualityMode(modekey, qualfile, 1);
  if (mode < 0) exit(BAD_PARAMETER);  /* error msg already printed */

  /* Increase dimensions to power of two (plus one) */
  xsize_actual = xsize;
  ysize_actual = ysize;
  for (xsize_dct = 1; xsize_dct+1 < xsize_actual; xsize_dct*=2)
    ;
  xsize_dct+=1;
  for (ysize_dct = 1; ysize_dct+1 < ysize_actual; ysize_dct*=2)
    ;
  ysize_dct+=1;
  if (xsize_dct != xsize_actual || ysize_dct != ysize_actual) {
    printf("Dimensions increase from %dx%d to %dx%d for FFT's\n",
           xsize_actual, ysize_actual, xsize_dct, ysize_dct);
  }

  /*  OPEN FILES, ALLOCATE MEMORY   */
  /* note: xsize_dct >= xsize;  ysize_dct >= ysize */
  xsize = xsize_dct;
  ysize = ysize_dct;
  AllocateFloat(&phase, xsize*ysize, "phase data");
  AllocateFloat(&soln, xsize*ysize, "scratch data");
  AllocateFloat(&qual_map, xsize*ysize, "quality map");
  AllocateByte(&bitflags, xsize*ysize, "bitflags array");
  OpenFile(&ifp, infile, "r");
  OpenFile(&ofp, outfile, "w");
  if (!Keyword(bmaskfile, "none")) OpenFile(&mfp, bmaskfile, "r");
  if (mode==corr_coeffs) OpenFile(&qfp, qualfile, "r");

  /*  READ AND PROCESS DATA  */
  xsize = xsize_actual;
  ysize = ysize_actual;
  printf("Reading input data...\n");
  GetPhase(in_format, ifp, infile, phase, xsize, ysize);

  if (qfp) {
    printf("Reading quality data...\n");
    /* borrow the bitflags array temporarily */
    ReadByte(qfp, bitflags, xsize*ysize, qualfile);
    /* process data and store in quality map array */
    AverageByteToFloat(bitflags, qual_map, tsize, xsize, ysize);
  }

  /* border mask data */
  printf("Processing border mask data...\n");
  if (mfp) {
    ReadByte(mfp, bitflags, xsize*ysize, bmaskfile);
  }
  else {
    for (k=0; k<xsize*ysize; k++)
      bitflags[k] = 255;
  }
  for (k=0; k<xsize*ysize; k++) {
    bitflags[k] = (!bitflags[k]) ? BORDER : 0;
  }
  if (mfp) FattenMask(bitflags, BORDER, 1, xsize, ysize);

  GetQualityMap(mode, qual_map, phase, bitflags, BORDER,
                tsize, xsize, ysize);
  if (thresh_flag) {
    HistoAndThresh(qual_map, xsize, ysize, 0.0, 0, 0.0,
                   bitflags, BORDER);
    if (fatten > 0)
      FattenQual(qual_map, fatten, xsize, ysize);
  }
  /* Set border (masked) pixels to 0-wts  */
  for (k=0; k<xsize*ysize; k++) {
    if (bitflags[k] & BORDER) qual_map[k] = 0.0;
  }

  if (debug_flag) {
    char filename[300];
    sprintf(filename, "%s.qual", outfile);
    SaveFloatToImage(qual_map, "quality", filename, xsize, ysize,
                     0, 0, 0);
  }

  /* embed arrays in possibly larger FFT/DCT arrays */
  for (j=ysize_dct-1; j>=0; j--) {
    for (i=xsize_dct-1; i>=0; i--) {
      if (i<xsize_actual && j<ysize_actual)
        phase[j*xsize_dct + i] = phase[j*xsize_actual + i];
      else phase[j*xsize_dct + i] = 0.0;
    }
  }
  for (j=ysize_dct-1; j>=0; j--) {
    for (i=xsize_dct-1; i>=0; i--) {
      if (i<xsize_actual && j<ysize_actual)
        bitflags[j*xsize_dct + i] = bitflags[j*xsize_actual + i];
      else bitflags[j*xsize_dct + i] = BORDER;
    }
  }
  if (qual_map) {
    for (j=ysize_dct-1; j>=0; j--) {
      for (i=xsize_dct-1; i>=0; i--) {
        if (i<xsize_actual && j<ysize_actual)
          qual_map[j*xsize_dct + i] = qual_map[j*xsize_actual + i];
        else
          qual_map[j*xsize_dct + i] = 0.0;
      }
    }
  }

  /* Set dimensions to DCT dimensions */
  xsize = xsize_dct;
  ysize = ysize_dct;
  /* Allocate more memory */
  AllocateFloat(&rarray, xsize*ysize, "r array data");
  AllocateFloat(&zarray, xsize*ysize, "z array data");
  AllocateFloat(&parray, xsize*ysize, "p array data");
  AllocateFloat(&dxwts, xsize*ysize, "dx weights");
  AllocateFloat(&dywts, xsize*ysize, "dy weights");

  /*  UNWRAP  */
  for (k=0; k<xsize*ysize; k++) soln[k] = 0.0;
  printf("Unwrapping...\n");
  LpNormUnwrap(soln, phase, dxwts, dywts, bitflags, qual_map,
    rarray, zarray, parray, num_iter, pcg_iter, e0, xsize, ysize);
  printf("\nFinished\n");
  PrintMinAndMax(xsize, ysize, soln, "solution");

  /* restore dimensions to input sizes and save solution*/
  xsize = xsize_actual;
  ysize = ysize_actual;
  for (j=0; j<ysize; j++) {
    for (i=0; i<xsize; i++) {
      soln[j*xsize + i] = TWOPI*soln[j*xsize_dct + i];
    }
  }
  /* save solution */
  printf("Saving unwrapped surface to file '%s'\n", outfile);
  WriteFloat(ofp, soln, xsize*ysize, outfile);
  free(rarray);
  free(zarray);
  free(parray);
  free(soln);
  free(qual_map);
  free(bitflags);
  free(dxwts);
  free(dywts);
}
Example #30
0
BOOL CATOLECRList::GetResponse(CECRConnection* pConnection, LPBYTE lpResponse, DWORD &dwSize)
{
	BOOL bEof = FALSE, bMasked = FALSE;
	dwSize = 0;

	// ожидаем STX
	SetTimeouts(pConnection, T_T2, T_TW);
	do
	{
		BOOL bResult = ReadByte(pConnection, lpResponse);
		if (!bResult)
			return FALSE;
	}
	while (lpResponse[dwSize] != STX);
	dwSize++;

	// читаем остальные данные ответа
	SetTimeouts(pConnection, T_T6, T_TW);
	do
	{
		BOOL bResult = ReadByte(pConnection, lpResponse + dwSize);
		if (!bResult)
			return FALSE;

		if (!bEof)
		{
			switch(lpResponse[dwSize]) 
			{
				case DLE:
					bMasked = !bMasked;
					break;
				case ETX:
					bEof = !bMasked;
					bMasked = FALSE;
					break;
				default:
					bMasked = FALSE;
			}
		}

		dwSize++;
	}
	while (!bEof);

	// читаем контрольную сумму
	BOOL bResult = ReadByte(pConnection, lpResponse + dwSize);
	if (!bResult)
		return FALSE;

	dwSize++;
	return TRUE;

	
	

/*
	BYTE nBuffer[CMD_LEN];
	DWORD dwBytesRead, dwStartTick = GetTickCount();
	BOOL bMasked = FALSE, bEof = FALSE, bSuccess = FALSE;

	dwSize = 0;
	ZeroMemory(lpData, CMD_LEN);
	SetTimeouts(pConnection, T_T2, T_TW);

	do 
	{
		dwBytesRead = 0;
		ZeroMemory(nBuffer, CMD_LEN);
		BOOL bResult = ReadFile(hFile, nBuffer, CMD_LEN, &dwBytesRead, NULL);

		for (DWORD i = 0; i < dwBytesRead; i++)
		{
			if ((dwSize == 0) && (nBuffer[i] != STX))
				continue;

			lpData[dwSize] = nBuffer[i];
			dwSize++;

			if (bEof)
				return TRUE;

			switch(nBuffer[i]) 
			{
				case DLE:
					bMasked = !bMasked;
					break;
				case ETX:
					bEof = !bMasked;
					bMasked = FALSE;
					break;
				default:
					bMasked = FALSE;
			}
		}
	} 
	while((GetTickCount() - dwStartTick) < dwTimeout);
	return FALSE;*/
}