예제 #1
0
float get_mean(FILE *famp, int ns, int nl, int doAvg)
{
   float avg = AVG;
   float total = 0;
   float *ampIn;
   int i;
   long long offset;
   int pixelsRead;

   if (doAvg) {
     i = nl / 2;  /* find middle row of image */
     offset = i * ns * sizeof(float);
     pixelsRead = ns * SCANLINES;
     ampIn = (float *)MALLOC(sizeof(float)*pixelsRead);

     /* Read input data for this line */
     FSEEK64(famp,offset,0);
     fread(ampIn,sizeof(float),pixelsRead,famp);

     /* Establish pointers into input data arrays */
     for (i = 0; i < pixelsRead; i++)
     { 
        total += ampIn[i];
     }
     avg = total / (float)pixelsRead;
/*     printf(" Calculated values:\n total = %f\tavg = %f\n",total,avg);*/

     /* free up memory & reset files */
     free(ampIn);
     FSEEK64(famp,0,0);
   }
   return(avg);
}
예제 #2
0
// gets the size of the file without changing the current file position
// 
// args:	handle of file to get size of
// returns:	size of file if successful
//			< 0 if error
s64 ArkFile::GetFilesize(FILE* fd) const
{
	s64 curr_offset = FTELL64(fd);
	if( FSEEK64(fd, 0, SEEK_END) ) return -1;
	s64 size = FTELL64(fd);
	if( FSEEK64(fd, curr_offset, SEEK_SET) ) return -1;
	return size;
}
예제 #3
0
lasErr FUNCTION c_lswrit(FILE	**fd, const char *key, int	*clen, int	*dlen, 
	const char *cbuf, const unsigned char *dbuf, const char *dtype)
{
FILE *fp;
char header[HDRL];
char len[LENL];

fp = *fd;
if (strlen(key) >= KEYL)
    {
    c_errmsg("Error: Key length too long.  Key should be truncated.",
             "lswrit-key", NON_FATAL);
    }

/*Seek to end-of-file.*/
FSEEK64(*fd, 0, 2);

if (*clen > 0)
   sprintf(len,"%-d/%-d",*clen,*dlen);
else
   sprintf(len,"%-d",*dlen);

sprintf (header,"%-*s%-*s%-*s",LENL,len,TYPL,dtype,KEYL-1,key);
FWRITE(header,sizeof(char),HDRL,fp);

if (*clen > 0)
    FWRITE(cbuf,sizeof(char), *clen,fp);

if (*dlen > 0)
    FWRITE(dbuf,sizeof(char), *dlen,fp);

return(E_SUCC);
}
예제 #4
0
/*Read in the block corresponding to to the given (in-bounds)
location (in image pixels), making room in memory if needed.*/
float *readBlock(fetchRec *g,int imgX,int imgY)
{
    float *retBlock=(float *)MALLOC(BLOCK_SIZE);
    int bx=PIX2BLOCK(imgX);
    int by=PIX2BLOCK(imgY);
    /*printf("Loading block at %d,%d: %d\n",imgX,imgY,by*g->blockWid+bx);*/
    FSEEK64(g->blockIn,(long long)BLOCK_SIZE*(by*g->blockWid+bx),0);
    ASF_FREAD(retBlock,1,BLOCK_SIZE,g->blockIn);

    /*Now we make sure our pixel buffer isn't getting TOO big.*/
    g->blocksInCache++;
    while (g->blocksInCache*BLOCK_SIZE>30L*1024*1024) /*Keep no more than 30 MB of data in buffer.*/
    {
        /*start tossing blocks of data, starting from doomedBlock...*/
        float **doomed=&(g->cache[g->doomedBlock]);
        if ((*doomed!=NULL)&&(*doomed!=g->zeroBlock))
        {   /*...until we get under the limit.*/
            /*printf("...paging out block %i...\n",g->doomedBlock);*/
            FREE(*doomed);
            *doomed=NULL;
            g->blocksInCache--;
        }
        g->doomedBlock++;
        if (g->doomedBlock>=(g->cacheWid*g->cacheHt))
            g->doomedBlock=0;
    }
    return retBlock;
}
예제 #5
0
int read_uavsar_client(int row_start, int n_rows_to_get,
                       void *dest_void, void *read_client_info,
                       meta_parameters *meta, int data_type)
{
    ReadUavsarClientInfo *info = (ReadUavsarClientInfo*) read_client_info;
    int ns = meta->general->sample_count;

    if (meta->general->data_type == ASF_BYTE) {
        unsigned char *dest = (unsigned char*)dest_void;
        if (data_type==GREYSCALE_BYTE) {
            FSEEK64(info->fp, ns*row_start, SEEK_SET);
            ASF_FREAD(dest, sizeof(unsigned char), n_rows_to_get*ns, info->fp);
        }
        else {
            assert(FALSE);
        }
    } else {
        float *dest = (float*)dest_void;
        if (data_type==GREYSCALE_FLOAT) {
            get_uavsar_lines(info, meta, row_start, n_rows_to_get, dest);
        } else {
            assert(FALSE);
        }
    }

    return TRUE;
}
예제 #6
0
파일: fileUtil.c 프로젝트: glshort/MapReady
long long fileSize(const char *name)
{
  FILE *fp = FOPEN(name,"rb");
  FSEEK64(fp,0,SEEK_END);
  long long file_size = FTELL64(fp);
  fclose(fp);
  return file_size;
}
예제 #7
0
파일: bacon_io.cpp 프로젝트: JeppeSRC/Bacon
	void bcLoadRawFile64(const char* filename, unsigned char** data, unsigned __int64* size) {
		FILE* file;
		fopen_s(&file, filename, "rb");

		if (file) {

			FSEEK64(file, 0, SEEK_END);
			*size = FTELL64(file);
			FSEEK64(file, 0, SEEK_SET);

			*data = new unsigned char[(unsigned int)*size];
			FREAD(*data, (unsigned int)*size, file);

			fclose(file);
		} else {
			LOG("Failed To Open File: %s\n", filename);
		}
	}
예제 #8
0
s64 ArkHdrPair::GetFilesize(const char* filename) const
{
	FILE* fd = fopen(filename, "rb");
	if(fd == NULL)
		return -1;
	if( FSEEK64(fd, 0, SEEK_END) ) { fclose(fd); return -1; }
	s64 size = FTELL64(fd);
	fclose(fd);
	return size;
}
예제 #9
0
파일: bacon_io.cpp 프로젝트: JeppeSRC/Bacon
	unsigned char* bcGetRawFile64(const char* filename) {
		FILE* file;
		fopen_s(&file, filename, "rb");
		unsigned __int64 size = 0;
		unsigned char* data;
		if (file) {

			FSEEK64(file, 0, SEEK_END);
			size = FTELL64(file);
			FSEEK64(file, 0, SEEK_SET);

			data = new unsigned char[(unsigned int)size];
			FREAD(data, (unsigned int)size, file);

			fclose(file);
		} else {
			LOG("Failed To Open File: %s\n", filename);
		}

		return data;
	}
예제 #10
0
/* Estimate mean and standard deviation of an image by taking regular
   sampling points and doing the math with those. A mask value can be
   defined that is excluded from this calculation. If no mask value is
   supposed to be used, pass the mask value as NAN. */
void estimate_stats(FILE *fpIn, meta_parameters *meta, int lines, int samples,
            double mask, double *min, double *max, double *mean,
            double *stdDev)
{
  float *imgLine = (float *) MALLOC(sizeof(float) * samples);
  double *stats, sum=0.0, variance=0.0;
  int ii, kk, line_increment, sample_increment;
  long pix=0, valid=0;

#define grid 100

  /* Define the necessary parameters */
  stats = (double *) MALLOC(sizeof(double) * grid * grid);
  line_increment = lines / grid;
  sample_increment = samples / grid;

  /* Collect values from sample grid */
  for (ii=0; ii<lines; ii+=line_increment) {
      get_float_line(fpIn, meta, ii, imgLine);
      for (kk=0; kk<samples; kk+=sample_increment) {
          if (!ISNAN(mask)) {
              if (FLOAT_EQUIVALENT(imgLine[kk], mask)) stats[pix] = NAN;
              else {
                  stats[pix] = imgLine[kk];
                  valid++;
              }
          }
          else {
              stats[pix] = imgLine[kk];
              valid++;
          }
          pix++;
      }
  }
  FSEEK64(fpIn, 0, 0);

  /* Estimate min, max, mean and standard deviation */
  *min = 99999;
  *max = -99999;
  for (ii=0; ii<grid*grid; ii++)
      if (!ISNAN(stats[ii])) {
          if (stats[ii] < *min) *min = stats[ii];
          if (stats[ii] > *max) *max = stats[ii];
          sum += stats[ii];
      }
      *mean = sum / valid;
      for (ii=0; ii<grid*grid; ii++)
          if (!ISNAN(stats[ii])) variance += (stats[ii]-*mean) * (stats[ii]-*mean);
      *stdDev = sqrt(variance / (valid-1));

  return;
}
예제 #11
0
/*************************************
 * RSAT_ceos_decoder_init:
 * CEOS Decoder initialization routine.  */
bin_state *RSAT_ceos_decoder_init(char *inN,char *outN,readPulseFunc *reader)
{
    bin_state *s=new_bin_state();
    signalType *sig=NULL;
    RSAT_aux aux;

    asfPrintStatus("   Initializing RSAT decoder...\n");
    *reader=RSAT_readNextCeosPulse;

    RSAT_init(s);

    s->binary=openCeos(inN, outN, s);
    sig=getNextCeosLine(s->binary, s, inN, outN);
    RSAT_decodeAux(sig,&aux);
    RSAT_auxUpdate(&aux,s);
    RSAT_writeCeosReplica(s,outN,1.0,inN,outN);
    FSEEK64(s->binary,0,0);

    return s;
}
예제 #12
0
/*Read_line: reads given line of the given input file,
padding with zeros out to destLen if needed.*/
void read_line(fetchRec *g,int y,float *destBuf,int destLen)
{
    int x;
    if (y>=g->inDDR->nl)
    {   /*We were asked for a line past the end of the image:*/
        for (x=0; x<destLen; x++)
            destBuf[x]=backgroundFill;
        return;/*Return a line of all background*/
    }
    /*Otherwise, the line is in bounds.*/
    /*Check for complex data.*/
    if (g->inDDR->dtype==DTYPE_COMPLEX)
    {   /*Complex data has to be handled specially*/
        int maxInX=g->inDDR->ns;
        unsigned int bytesPerLine=2*sizeof(float)*maxInX;
        float *inputBuffer=(float *)MALLOC(bytesPerLine);
        FSEEK64(g->inFile,(long long) y*bytesPerLine,0);
        ASF_FREAD(inputBuffer,1,bytesPerLine,g->inFile);

        if (g->getRealCpx) /*Fetch Real fields from complex data.*/
            for (x=0; x<maxInX; x++) {
                float f=inputBuffer[x*2];
                ieee_big32(f);
                destBuf[x]=f;
            }
        else /*Fetch Imaginary Fields from complex data.*/
            for (x=0; x<maxInX; x++) {
                float f=inputBuffer[x*2+1];
                ieee_big32(f);
                destBuf[x]=f;
            }
        FREE(inputBuffer);
    }
    else /*Non-complex data is much easier to handle*/
        getFloatLine_mb(g->inFile,g->inDDR,y,g->inBand,destBuf);

    /*Pad to the end of the buffer with the background color*/
    for (x=g->inDDR->ns; x<destLen; x++)
        destBuf[x]=backgroundFill;

}
예제 #13
0
void readCeosLine(int *dest,int y,CEOS_FILE *c)
{
  int ns=c->ddr.ns;
  int lineLen=ns*dtype2dsize(c->ddr.dtype,NULL);
  unsigned char *buf=(unsigned char *)MALLOC(lineLen);
  int i;
  FSEEK64(c->f_in,(long long)c->headerBytes+y*c->lineBytes,0);
  ASF_FREAD(buf,1,lineLen,c->f_in);
  if (c->ddr.dtype==DTYPE_BYTE)
    for (i=0;i<ns;i++)
      dest[i]=buf[i];
  else
    if (c->ddr.dtype==DTYPE_SHORT)
    for (i=0;i<ns;i++)
      dest[i]=(buf[2*i]<<8)+buf[2*i+1];
  else
  {
    fprintf(stderr,"Attempted to read unsupported CEOS data type %d\n"
      "from image file %s!\n",c->ddr.dtype,c->name);
    exit(1);
  }
  FREE(buf);
}
예제 #14
0
/****************************************
getSignalLine:
    Fetches and unpacks a single line of signal data
into the given array.
*/
void getSignalLine(const getRec *r,long long lineNo,complexFloat *destArr,int readStart,int readLen)
{
    int x;
    int left,leftClip,rightClip;
    int windowShift=0;
    float agcScale=1.0;
    complexFloat czero=Czero();

/*If the line is out of bounds, return zeros.*/
    if ((lineNo>=r->nLines)||(lineNo<0))
    {
        for (x=0;x<readLen;x++)
            destArr[x]=czero;
        return;
    }
/*Fetch window shift and AGC comp. if possible*/
    if (r->lines!=NULL)
    {
        windowShift=r->lines[lineNo].shiftBy;
        agcScale=r->lines[lineNo].scaleBy;
    }

/*Compute which part of the line we'll read in.*/
    leftClip=left=readStart-windowShift;
    if (leftClip<0) {leftClip=0; /*left=0;*/}
    rightClip=left+readLen;
    if (rightClip>r->nSamples) rightClip=r->nSamples;

/*Read line of raw signal data.*/
    FSEEK64(r->fp_in,r->header+lineNo*r->lineSize+leftClip*r->sampleSize,0);
    if (rightClip-leftClip!=
        fread(r->inputArr,r->sampleSize,rightClip-leftClip,r->fp_in))
        {
         sprintf(errbuf,"   ERROR: Problem reading signal data file on line %lld!\n",lineNo);
/*       fprintf(stderr,"Read length = %d, Left = %d Readstart = %d\n",readLen, left,readStart);
         fprintf(stderr,"Lines = %lld Samples = %lld, rightClip = %d, leftClip = %d window = %d\n"
             ,r->nLines, r->nSamples, rightClip, leftClip, windowShift); */
         printErr(errbuf);
        }
    leftClip-=left;
    rightClip-=left;

/*Fill the left side with zeros.*/
    for (x=0;x<leftClip;x++)
        destArr[x]=czero;

/*Unpack the read-in data into destArr:*/
    if (r->flipIQ=='y')
        /*is CCSD data (one byte Q, next byte I)*/
        for (x=leftClip;x<rightClip;x++)
        {
            int index=2*(x-leftClip);
            destArr[x].real=agcScale*(r->inputArr[index+1]-r->dcOffsetQ);
            destArr[x].imag=agcScale*(r->inputArr[index]-r->dcOffsetI);
        }
    else /*if (r->flipIQ=='n')*/
        /*is Raw data (one byte I, next byte Q)*/
        for (x=leftClip;x<rightClip;x++)
        {
            int index=2*(x-leftClip);
            destArr[x].real=agcScale*(r->inputArr[index]-r->dcOffsetI);
            destArr[x].imag=agcScale*(r->inputArr[index+1]-r->dcOffsetQ);
        }

/*Fill the right side with zeros.*/
    for (x=rightClip;x<readLen;x++)
        destArr[x]=czero;
}
예제 #15
0
/*******************************************************************************
 * Get x number of lines of data (any data type) and fill a pre-allocated array
 * with it. The data is assumed to be in big endian format and will be converted
 * to the native machine's format. The line_number argument is the zero-indexed
 * line number to get. The dest argument must be a pointer to existing memory.
 * Returns the amount of samples successfully read & converted. */
int get_data_lines(FILE *file, meta_parameters *meta,
       int line_number, int num_lines_to_get,
       int sample_number, int num_samples_to_get,
       void *dest, int dest_data_type)
{
  int ii;               /* Sample index.  */
  int samples_gotten=0; /* Number of samples retrieved */
  int line_samples_gotten;
  size_t sample_size;   /* Sample size in bytes.  */
  void *temp_buffer;    /* Buffer for unconverted data.  */
  int sample_count = meta->general->sample_count;
  int line_count = meta->general->line_count;
  int band_count = meta->general->band_count;
  int data_type    = meta->general->data_type;
  int num_lines_left = line_count * band_count - line_number;
  int num_samples_left = sample_count - sample_number;
  long long offset;

  // Check whether data conversion is possible
  if ((data_type>=COMPLEX_BYTE) && (dest_data_type<=REAL64))
    asfPrintError("\nget_data_lines: Cannot put complex data"
      " into a simple data buffer. Exiting.\n\n");
  if ((data_type<=REAL64) && (dest_data_type>=COMPLEX_BYTE))
    asfPrintError("\nget_data_lines: Cannot put simple data"
      " into a complex data buffer. Exiting.\n\n");
  // Make sure not to go outside the image
  if (line_number > (line_count * band_count))
    asfPrintError("\nget_data_lines: Cannot read line %d "
      "in a file of %d lines. Exiting.\n",
      line_number, line_count*band_count);
  if (sample_number < 0 || sample_number > meta->general->sample_count)
    asfPrintError("\nget_data_lines: Cannot read sample %d "
      "in a file of %d lines. Exiting.\n",
      sample_number, sample_count);
  if (num_lines_to_get > num_lines_left)
    asfPrintError("\nget_data_lines: Cannot read %d lines. "
      "Only %d lines left in file. Exiting.\n",
      num_lines_to_get, num_lines_left);
  if (num_samples_to_get > num_samples_left)
    asfPrintError("\nget_data_lines: Cannot read %d samples. "
      "Only %d samples left in file. Exiting.\n",
      num_samples_to_get, num_samples_left);

  /* Determine sample size.  */
  sample_size = data_type2sample_size(data_type);

  temp_buffer = MALLOC( sample_size * num_lines_to_get * num_samples_to_get);


  // Scan to the beginning of the line sample.
  for (ii=0; ii<num_lines_to_get; ii++) {
    offset = (long long)sample_size *
        ((long long)sample_count * ((long long)line_number + (long long)ii) + (long long)sample_number);
    if (offset<0) {
        asfPrintError("File offset overflow error ...file is too large to read.\n"
                      "offset = %ld (sample_size * (sample_count * (line_number + ii) + sample_number)\n"
                      "sample_size = %d\n"
                      "sample_count = %d\n"
                      "line_number = %d\n"
                      "ii = %d\n"
                      "sample_number = %d\n",
                      offset, sample_size, sample_count, line_number, ii, sample_number);
    }
    FSEEK64(file, offset, SEEK_SET);
    line_samples_gotten = FREAD(temp_buffer+ii*num_samples_to_get*sample_size,
        sample_size, num_samples_to_get, file);
    samples_gotten += line_samples_gotten;
  }

  /* Fill in destination array.  */
  switch (data_type) {
    case REAL32:
      for ( ii=0; ii<samples_gotten; ii++ ) {
        ieee_big32(((float*)temp_buffer)[ii]);
        switch (dest_data_type) {
         case ASF_BYTE:((unsigned char*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case INTEGER16:((short int*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case INTEGER32:((int*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case REAL32:((float*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case REAL64:((double*)dest)[ii] = ((float*)temp_buffer)[ii];break;
        }
      }
      break;
    case COMPLEX_REAL32:
      for ( ii=0; ii<samples_gotten*2; ii++ ) {
        ieee_big32(((float*)temp_buffer)[ii]);
        switch (dest_data_type) {
         case COMPLEX_BYTE:((unsigned char*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER16:((short int*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER32:((int*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case COMPLEX_REAL32:((float*)dest)[ii] = ((float*)temp_buffer)[ii];break;
         case COMPLEX_REAL64:((double*)dest)[ii] = ((float*)temp_buffer)[ii];break;
        }
      }
      break;
    case ASF_BYTE:
      for ( ii=0; ii<samples_gotten; ii++ ) {
        switch (dest_data_type) {
         case ASF_BYTE:((unsigned char*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case INTEGER16:((short int*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case INTEGER32:((int*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case REAL32:((float*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case REAL64:((double*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
        }
      }
     break;
    case INTEGER16:
      for ( ii=0; ii<samples_gotten; ii++ ) {
        big16(((short int *)temp_buffer)[ii]);
        switch (dest_data_type) {
         case ASF_BYTE:((unsigned char*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case INTEGER16:((short int*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case INTEGER32:((int*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case REAL32:((float*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case REAL64:((double*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
        }
      }
      break;
    case INTEGER32:
      for ( ii=0; ii<samples_gotten; ii++ ) {
        big32(((int *)temp_buffer)[ii]);
        switch (dest_data_type) {
         case ASF_BYTE:((unsigned char*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case INTEGER16:((short int*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case INTEGER32:((int*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case REAL32:((float*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case REAL64:((double*)dest)[ii] = ((int*)temp_buffer)[ii];break;
        }
      }
      break;
    case REAL64:
      for ( ii=0; ii<samples_gotten; ii++ ) {
        ieee_big64(((double*)temp_buffer)[ii]);
        switch (dest_data_type) {
         case ASF_BYTE:((unsigned char*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case INTEGER16:((short int*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case INTEGER32:((int*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case REAL32:((float*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case REAL64:((double*)dest)[ii] = ((double*)temp_buffer)[ii];break;
        }
      }
    case COMPLEX_BYTE:
      for ( ii=0; ii<samples_gotten*2; ii++ ) {
        switch (dest_data_type) {
         case COMPLEX_BYTE:((unsigned char*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER16:((short int*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER32:((int*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case COMPLEX_REAL32:((float*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
         case COMPLEX_REAL64:((double*)dest)[ii] = ((unsigned char*)temp_buffer)[ii];break;
        }
      }
      break;
    case COMPLEX_INTEGER16:
      for ( ii=0; ii<samples_gotten*2; ii++ ) {
        big16(((short int *)temp_buffer)[ii]);
         switch (dest_data_type) {
         case COMPLEX_BYTE:((unsigned char*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER16:((short int*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER32:((int*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case COMPLEX_REAL32:((float*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
         case COMPLEX_REAL64:((double*)dest)[ii] = ((short int*)temp_buffer)[ii];break;
        }
      }
      break;
    case COMPLEX_INTEGER32:
      for ( ii=0; ii<samples_gotten*2; ii++ ) {
        big32(((int *)temp_buffer)[ii]);
        switch (dest_data_type) {
         case COMPLEX_BYTE:((unsigned char*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER16:((short int*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER32:((int*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case COMPLEX_REAL32:((float*)dest)[ii] = ((int*)temp_buffer)[ii];break;
         case COMPLEX_REAL64:((double*)dest)[ii] = ((int*)temp_buffer)[ii];break;
        }
      }
      break;
    case COMPLEX_REAL64:
      for ( ii=0; ii<samples_gotten*2; ii++ ) {
        ieee_big64(((double*)temp_buffer)[ii]);
        switch (dest_data_type) {
         case COMPLEX_BYTE:((unsigned char*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER16:((short int*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case COMPLEX_INTEGER32:((int*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case COMPLEX_REAL32:((float*)dest)[ii] = ((double*)temp_buffer)[ii];break;
         case COMPLEX_REAL64:((double*)dest)[ii] = ((double*)temp_buffer)[ii];break;
        }
      }
  }

  FREE(temp_buffer);
  return samples_gotten;
}
예제 #16
0
/*******************************************************************************
 * Write x number of lines of any data type to file in the data format specified
 * by the meta structure. It is always written in big endian format. Returns the
 * amount of samples successfully converted & written. Will not write more lines
 * than specified in the supplied meta struct. */
static int put_data_lines(FILE *file, meta_parameters *meta, int band_number,
                          int line_number_in_band, int num_lines_to_put,
                          const void *source, int source_data_type)
{
  int ii;               /* Sample index.                       */
  int samples_put;      /* Number of samples written           */
  size_t sample_size;   /* Sample size in bytes.               */
  void *out_buffer;     /* Buffer of converted data to write.  */
  int sample_count       = meta->general->sample_count;
  int data_type          = meta->general->data_type;
  int num_samples_to_put = num_lines_to_put * sample_count;
  int line_number        = meta->general->line_count * band_number +
                               line_number_in_band;

  if ((source_data_type>=COMPLEX_BYTE) && (data_type<=REAL64)) {
    printf("\nput_data_lines: Cannot put complex data into a simple data file. Exiting.\n\n");
    exit(EXIT_FAILURE);
  }
  if ((source_data_type<=REAL64) && (data_type>=COMPLEX_BYTE)) {
    printf("\nput_data_lines: Cannot put simple data into a complex data file. Exiting.\n\n");
    exit(EXIT_FAILURE);
  }

  // Write out all optical data as byte image.
  // They don't have a larger dynamic range than that.
  if (meta->optical)
    data_type = ASF_BYTE;

  /* Determine sample size.  */
  sample_size = data_type2sample_size(data_type);

  /* Make sure not to make file bigger than meta says it should be */
  if (line_number > meta->general->line_count * meta->general->band_count) {
    printf("\nput_data_lines: Cannot write line %d of band %d in a\n"
           "file that should be %d lines. Exiting.\n",
           line_number, band_number,
           meta->general->line_count * meta->general->band_count);
    exit(EXIT_FAILURE);
  }
  if ((line_number+num_lines_to_put) >
      meta->general->line_count * meta->general->band_count)
  {
    num_samples_to_put = (meta->general->line_count - line_number)
                          * sample_count;
  }

  FSEEK64(file, (long long)sample_size*sample_count*line_number, SEEK_SET);
  out_buffer = MALLOC( sample_size * sample_count * num_lines_to_put );

  /* Fill in destination array.  */
  switch (data_type) {
    case REAL32:
      for ( ii=0; ii<num_samples_to_put; ii++ ) {
        switch (source_data_type) {
         case ASF_BYTE:((float*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case INTEGER16:((float*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case INTEGER32:((float*)out_buffer)[ii] = ((int*)source)[ii];break;
         case REAL32:((float*)out_buffer)[ii] = ((float*)source)[ii];break;
         case REAL64:((float*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        ieee_big32( ((float*)out_buffer)[ii] );
      }
      break;
    case COMPLEX_REAL32:
      for ( ii=0; ii<num_samples_to_put*2; ii++ ) {
        switch (source_data_type) {
         case COMPLEX_BYTE:((float*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case COMPLEX_INTEGER16:((float*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case COMPLEX_INTEGER32:((float*)out_buffer)[ii] = ((int*)source)[ii];break;
         case COMPLEX_REAL32:((float*)out_buffer)[ii] = ((float*)source)[ii];break;
         case COMPLEX_REAL64:((float*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        ieee_big32( ((float*)out_buffer)[ii] );
      }
      break;
    case ASF_BYTE:
      for ( ii=0; ii<num_samples_to_put; ii++ ) {
        switch (source_data_type) {
         case ASF_BYTE:((unsigned char*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case INTEGER16:((unsigned char*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case INTEGER32:((unsigned char*)out_buffer)[ii] = ((int*)source)[ii];break;
         case REAL32:((unsigned char*)out_buffer)[ii] = ((float*)source)[ii];break;
         case REAL64:((unsigned char*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
      }
      break;
    case INTEGER16:
      for ( ii=0; ii<num_samples_to_put; ii++ ) {
        switch (source_data_type) {
         case ASF_BYTE:((short int*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case INTEGER16:((short int*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case INTEGER32:((short int*)out_buffer)[ii] = ((int*)source)[ii];break;
         case REAL32:((short int*)out_buffer)[ii] = ((float*)source)[ii];break;
         case REAL64:((short int*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        big16( ((short int*)out_buffer)[ii] );
      }
      break;
    case INTEGER32:
      for ( ii=0; ii<num_samples_to_put; ii++ ) {
        switch (source_data_type) {
         case ASF_BYTE:((int*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case INTEGER16:((int*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case INTEGER32:((int*)out_buffer)[ii] = ((int*)source)[ii];break;
         case REAL32:((int*)out_buffer)[ii] = ((float*)source)[ii];break;
         case REAL64:((int*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        big32( ((int*)out_buffer)[ii] );
      }
      break;
    case REAL64:
      for ( ii=0; ii<num_samples_to_put; ii++ ) {
        switch (source_data_type) {
         case ASF_BYTE:((double*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case INTEGER16:((double*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case INTEGER32:((double*)out_buffer)[ii] = ((int*)source)[ii];break;
         case REAL32:((double*)out_buffer)[ii] = ((float*)source)[ii];break;
         case REAL64:((double*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        ieee_big64( ((double*)out_buffer)[ii] );
      }
      break;
    case COMPLEX_BYTE:
      for ( ii=0; ii<num_samples_to_put*2; ii++ )
        switch (source_data_type) {
         case COMPLEX_BYTE:((unsigned char*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case COMPLEX_INTEGER16:((unsigned char*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case COMPLEX_INTEGER32:((unsigned char*)out_buffer)[ii] = ((int*)source)[ii];break;
         case COMPLEX_REAL32:((unsigned char*)out_buffer)[ii] = ((float*)source)[ii];break;
         case COMPLEX_REAL64:((unsigned char*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
     break;
    case COMPLEX_INTEGER16:
      for ( ii=0; ii<num_samples_to_put*2; ii++ ) {
        switch (source_data_type) {
         case COMPLEX_BYTE:((short int*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case COMPLEX_INTEGER16:((short int*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case COMPLEX_INTEGER32:((short int*)out_buffer)[ii] = ((int*)source)[ii];break;
         case COMPLEX_REAL32:((short int*)out_buffer)[ii] = ((float*)source)[ii];break;
         case COMPLEX_REAL64:((short int*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        big16( ((short int*)out_buffer)[ii] );
      }
      break;
    case COMPLEX_INTEGER32:
      for ( ii=0; ii<num_samples_to_put*2; ii++ ) {
        switch (source_data_type) {
         case COMPLEX_BYTE:((int*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case COMPLEX_INTEGER16:((int*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case COMPLEX_INTEGER32:((int*)out_buffer)[ii] = ((int*)source)[ii];break;
         case COMPLEX_REAL32:((int*)out_buffer)[ii] = ((float*)source)[ii];break;
         case COMPLEX_REAL64:((int*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        big32( ((int*)out_buffer)[ii] );
      }
      break;
    case COMPLEX_REAL64:
      for ( ii=0; ii<num_samples_to_put*2; ii++ ) {
        switch (source_data_type) {
         case COMPLEX_BYTE:((double*)out_buffer)[ii] = ((unsigned char*)source)[ii];break;
         case COMPLEX_INTEGER16:((double*)out_buffer)[ii] = ((short int*)source)[ii];break;
         case COMPLEX_INTEGER32:((double*)out_buffer)[ii] = ((int*)source)[ii];break;
         case COMPLEX_REAL32:((double*)out_buffer)[ii] = ((float*)source)[ii];break;
         case COMPLEX_REAL64:((double*)out_buffer)[ii] = ((double*)source)[ii];break;
        }
        ieee_big64( ((double*)out_buffer)[ii] );
      }
      break;
  }
  samples_put = FWRITE(out_buffer, sample_size, num_samples_to_put, file);
  FREE(out_buffer);

  if ( samples_put != num_samples_to_put ) {
    printf("put_data_lines: failed to write the correct number of samples\n");
  }

  return samples_put;
}
예제 #17
0
lasErr FUNCTION c_lsclos (FILE **fd, const char *hostname, int *action)
{
FILE *fdtemp;
int	clen, dlen, total_len, empty,  more, nbytes;
int	buf_size = 1024;
char	tempfile[CMLEN];
char	*buffer;
char    dtype[TYPL];
char	header[HDRL];
char	*key=NULL;
char	msgtxt[ERRLEN + 1];
char	*ptr;

switch (*action)
    {
    case 0:					/***  normal close    ***/
	FCLOSE(*fd);
	break;

    case 1:					/***  crunch file     ***/
	FSEEK64(*fd, 0, 0);

	strcpy(tempfile,hostname);
	strcat(tempfile,"_temp");

	fdtemp = FOPEN (tempfile, "w");

	buffer = MALLOC((unsigned)buf_size);

	empty = 1;
	more = 1;
	while (more)
	    {
 	    nbytes = fread(header,sizeof(char),HDRL,*fd);
	    if (nbytes == 0)
	       break;

	    if (nbytes == -1)
	       {
	       c_errmsg("Error reading header record from label services file",
                         "lsclos-read",NON_FATAL);
	       return(E_FAIL);
	       }

	    clen = dlen = 0;
            if (((ptr = strchr(header,'/')) != NULL ) && ((int)(ptr - header) < LENL))
                sscanf(header,"%d/%d%s",&clen,&dlen,dtype); 
            else
                sscanf(header,"%d%s",&dlen,dtype); 

            key = squeeze(header+LENL+TYPL,strlen(header+LENL+TYPL));
	    total_len = clen + dlen;

	    if (strcmp(key,"DELETED") != 0)		/* copy record	*/
		{					/* to new file	*/
		if (total_len > buf_size)
		    {
		    free(buffer);
		    buf_size = total_len;

		    buffer = MALLOC((unsigned)buf_size);
		    }

		FREAD(buffer,1,total_len,*fd);

		FWRITE(header,1,HDRL,fdtemp);
		FWRITE(buffer,1,nbytes,fdtemp);

		empty = 0;
		}
	    else					/* skip record	*/ 
		{
		if (fseek(*fd, (int)total_len, 1) == -1)
		    {
		    c_errmsg("Error seeking in label services file",
			     "lsclos-seek",NON_FATAL);
		    return(E_FAIL);
		    }
		}
	    }

        free(buffer);

	if (fclose(*fd) != 0)
	    {
	    c_errmsg("Error closing label services file","lsclos-close",
			NON_FATAL);
	    return(E_FAIL);
	    }

	if (fclose(fdtemp) != 0)
	    {
	    sprintf(msgtxt,"Error closing temporary file %s",tempfile);
	    c_errmsg(msgtxt,"lsclos-close",NON_FATAL);
	    return(E_FAIL);
	    }

	 if (unlink(hostname) == -1)
	     {
	     sprintf(msgtxt,"Error deleting label services file %s",
		     hostname);
	     c_errmsg(msgtxt,"lsclos-delete",NON_FATAL);
	     return(E_FAIL);
	     }

	if (!empty)					/***  delete file   ***/
	   {
	   if (rename(tempfile,hostname) != E_SUCC)
	       {
	       sprintf(msgtxt,"Error renaming file %s to %s",
		        tempfile,hostname);
	       c_errmsg(msgtxt,"lsclos-rename",NON_FATAL);
	       return(E_FAIL);
	       }
           }
	else
	   if (unlink(tempfile) == -1)
	      {
	      sprintf(msgtxt,"Error deleting label services file %s",
		     hostname);
	      c_errmsg(msgtxt,"lsclos-delete",NON_FATAL);
	      return(E_FAIL);
	      }

	free(key);
	break;

    case 2:					/***  delete file     ***/
	if (unlink(hostname) == -1)
	    {
	    sprintf(msgtxt,"Error deleting label services file %s",
		    hostname);
	    c_errmsg(msgtxt,"lsclos-delete",NON_FATAL);
	    return(E_FAIL);
	    }
	break;
    }

return(E_SUCC);
}
예제 #18
0
int main(int argc, char *argv[])
{
  meta_parameters *meta, *meta_old, *meta_stat;
	char fnm1[BUF],fnm2[BUF],fnm3[BUF],fnm4[BUF];
	char imgfile[BUF],metaFile[BUF],cmd[BUF],metaIn[BUF],metaOut[BUF];
	FILE *fiamp, *fiphase, *foamp, *fophase, *flas;
	int ll=0, ls=1;   /* look line and sample */
	int sl=STEPLINE, ss=STEPSAMPLE;   /* step line and sample */
	int i,line, sample;
	int row, col, ampFlag = 0;
	long long nitems, newitems, inWid, inLen, outWid, outLen;
	long long ds/*,samplesRead*/;       /* input data size, number of samples read so far.*/
	long long red_offset, grn_offset, blu_offset;
	register float *ampIn, *phaseIn, ampScale;
	float *ampOut, *phaseOut,*ampBuf,Sin[256],Cos[256];
	float avg, percent=5.0;
	RGBDATA *table, *imgData;
	Uchar *redPtr, *grnPtr, *bluPtr;
	complexFloat z;
	struct DDR newddr;
	register float tmp,zImag,zReal,ampI;
	register int index,offset;
	const float convers=256.0/(2*3.14159265358979);
   
	logflag = 0;

  /* parse command line */
  while (currArg < (argc-2)) {
    char *key = argv[currArg++];
    if (strmatch(key,"-log")) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = 1;
    }
    else if (strmatch(key,"-look")) {
      CHECK_ARG(1);
      if (2!=sscanf(GET_ARG(1),"%dx%d",&ll,&ls)) {
        printf("   ***ERROR: -look '%s' does not look like line x sample (e.g. '10x2').\n",GET_ARG(1));
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-step")) {
      CHECK_ARG(1);
      if (2!=sscanf(GET_ARG(1),"%dx%d",&sl,&ss)) {
        printf("   ***ERROR: -step '%s' does not look like line x sample (e.g. '5x1').\n",GET_ARG(1));
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-meta")) {
      CHECK_ARG(1);
      if (1!=sscanf(GET_ARG(1),"%s",metaFile)) {
        printf("   ***ERROR: Could not open '%s'.\n",GET_ARG(1));
        usage(argv[0]);
      }
      strcat(metaFile, "");
      ls = ss = 1;
      ll = sl = lzInt(metaFile, "sar.look_count:", NULL);
    }
    else if (strmatch(key,"-amplitude")) {
      printf("   Will remove amplitude part of color image\n");
      ampFlag = 1;
    }
    else {printf("\n   ***Invalid option:  %s\n",argv[currArg-1]); usage(argv[0]);}
  }
  if ((argc-currArg) < 2) {printf("   Insufficient arguments.\n"); usage(argv[0]);}

	system("date");
	printf("Program: multilook\n\n");
	if (logflag) {
	  StartWatchLog(fLog);
	  printLog("Program: multilook\n\n");
	}

	/* Create filenames and open files for reading */
  	create_name(fnm1,argv[currArg],"_amp.img");
  	create_name(fnm2,argv[currArg],"_phase.img");
	meta_stat = meta_read(fnm1);
	meta_old = meta_read(fnm2);
	meta = meta_read(fnm2);
  	create_name(fnm3,argv[++currArg],"_amp.img");
  	create_name(fnm4,argv[currArg],"_phase.img");
  	create_name(imgfile,argv[currArg],"_rgb.img");
	create_name(metaOut,argv[currArg],"_rgb.meta");
 	
	inWid = meta->general->sample_count;
	inLen = meta->general->line_count;
  	meta->general->sample_count /= ss;
  	meta->general->line_count /= sl;
	outWid = meta->general->sample_count;
	outLen = meta->general->line_count;
  
	/* Create new metadata file for the amplitude and phase.*/
	meta->sar->line_increment = 1;
	meta->sar->sample_increment = 1;
	meta->sar->azimuth_time_per_pixel *= sl;
	meta->general->x_pixel_size *= ss;
	meta->general->y_pixel_size *= sl;
	create_name(metaIn,argv[currArg],"_amp.meta");
	meta_write(meta, metaIn);
	create_name(metaIn,argv[currArg],"_phase.meta");
	meta_write(meta, metaIn);

        meta2ddr(meta, &newddr);

	/* Create 3-band image's DDR.
	   Currently metadata file don't know anything about multiband imagery.
	   We will need to convert the current version for single band amplitude
	   image back to metadata version 0.9 and change a couple of values 
	sprintf(cmd, "convert_meta %s 1.3 %s 0.9", metaIn, metaOut);
	asfSystem(cmd);
        */
	
	newddr.dtype=EBYTE;
	newddr.nbands=3;
	c_putddr(imgfile,&newddr);
  
	fiamp = fopenImage(fnm1,"rb");
	fiphase = fopenImage(fnm2,"rb");
	foamp = fopenImage(fnm3,"wb");
	fophase = fopenImage(fnm4,"wb");
	flas = fopenImage(imgfile,"wb");

	/*
	* create data buffers 
	*/
	for (i=0;i<256;i++)
	{
		float phas=((float)i)/256.0*(2*3.14159265358979);
		Sin[i]=sin(phas);
		Cos[i]=cos(phas);
	}
  
	/* set data variables */
	ampScale = 1.0/(ll*ls);
	nitems   = (ll-sl)*inWid;
	newitems = sl*inWid;
  
	ds       = sizeof(float);
	ampIn    = (float *)MALLOC(ds*(newitems+nitems+ls));
	phaseIn  = (float *)MALLOC(ds*(newitems+nitems+ls));
	ampOut   = (float *)MALLOC(ds*outWid);
	ampBuf   = (float *)MALLOC(ds*outWid);
	phaseOut = (float *)MALLOC(ds*outWid);
	table    = (RGBDATA *)MALLOC(sizeof(RGBDATA)*MAXENTRIES);
	imgData  = (RGBDATA *)MALLOC(sizeof(RGBDATA)*outWid);
	redPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	grnPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	bluPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	
        /* calculate mean value */
        if (meta_stat->stats)
          avg = meta_stat->stats->band_stats[0].mean;
        else {
          sprintf(cmd, "stats -overmeta -overstat \"%s\"\n", fnm1);
          asfSystem(cmd);
          meta_free(meta_stat);
          meta_stat = meta_read(fnm1);
          avg = meta_stat->stats->band_stats[0].mean;
        }

	/* create a colortable to be used with c2i */
	colortable(table);
  
	/* start conversion */
/*	printf("   Skipping every %d col and %d row\n",ss,sl);
	printf("   Looking at every %d col and %d row\n",ls,ll);*/
  	printf("   Input is %lld lines by %lld samples\n",inLen,inWid);
	printf("   Ouput is %lld lines by %lld samples\n\n",outLen,outWid);
	if (logflag) {
  	  sprintf(logbuf, "   Input is %lld lines by %lld samples\n",inLen,inWid);
	  printLog(logbuf);
	  sprintf(logbuf, "   Ouput is %lld lines by %lld samples\n\n",outLen,outWid);
	  printLog(logbuf);
	}
 	
	/*
	* Run through all lines in which data needs to be read so that
	* amount of data will be equal to ll * inWid.
	*/
	for(line=0; line<outLen; line++)
	{

		/* Read in a ll*inWid size chunk */
		get_float_lines(fiamp, meta_old, line*sl, ll, ampIn);
		get_float_lines(fiphase, meta_old, line*sl, ll, phaseIn);

		/* begin adding data */
		for (sample=0; sample<outWid; sample++)
		{ 
			tmp = 0.0, zReal=0.0, zImag=0.0;
			/* add up looking area */
			for (col=0;col<ls;col++)
			{
				offset=sample*ss+col;
				for (row=0;row<ll;row++)
				{
					ampI=ampIn[offset];
					index=0xFF&((int)(phaseIn[offset]*convers));
					tmp += ampI * ampI;
					zReal += ampI * Cos[index];
					zImag += ampI * Sin[index];
					offset+=inWid;
 				}
			}
     
			/* get phase from complex values */
			z.real=zReal;
			z.imag=zImag;
			/* place in output buffer */
		/*	ampOut[sample] = sqrt(tmp*ampScale); */
			ampOut[sample] = Cabs(z)*ampScale; 
			phaseOut[sample] = Cphase(z);
			if(!ampFlag)
				ampBuf[sample]=ampOut[sample];
			else
				ampBuf[sample]=avg*1.5;		
		}
    
		/* convert amp & phase to RGB. */
		if (!c2i(ampBuf,phaseOut,imgData,table,outWid,avg))
			Exit("ml: Error in c2i()");

		/* write out data to file */
		put_float_line(foamp, meta, line, ampOut);
		put_float_line(fophase, meta, line, phaseOut);

		if ((line*100/outLen)>percent) {
			printf("   Completed %3.0f percent\n", percent);
			percent+=5.0;
		}
		
		for (i=0;i<outWid;i++)
		{
			redPtr[i] = imgData[i].red;
			grnPtr[i] = imgData[i].green;
			bluPtr[i] = imgData[i].blue;
		} 
		red_offset=(long long)(line*outWid);
		grn_offset=(long long)(line*outWid+outWid*outLen);
		blu_offset=(long long)(line*outWid+(2*outWid*outLen));

		FSEEK64(flas,red_offset,SEEK_SET);
		ASF_FWRITE(redPtr,1,outWid,flas);
		FSEEK64(flas,grn_offset,SEEK_SET);
		ASF_FWRITE(grnPtr,1,outWid,flas);
		FSEEK64(flas,blu_offset,SEEK_SET);
		ASF_FWRITE(bluPtr,1,outWid,flas);
    
		/* reposition data for next read */
		for (i=0;i<nitems;i++)
		{
			ampIn[i] = ampIn[i + newitems];
			phaseIn[i] = phaseIn[i + newitems];
		}
		
	}
  
	/* 
	* free up unneeded memory and prepare to write 
	* a 3 sequential band image
	*/
/*	printf("\n\tdone with multilook\n");
	printf("writing out LAS/RGB image file\n");*
	printf("   Completed 100 percent\n\n   Wrote %lld bytes of data\n\n", 
	       (long long)(outLen*outWid*4));
	if (logflag) {
	  sprintf(logbuf, "   Wrote %lld bytes of data\n\n", 
		  (long long)(outLen*outWid*4));
	  printLog(logbuf);
	  StopWatchLog(fLog);
	  FCLOSE(fLog);
	}
*/

	FREE(ampIn);
	FREE(phaseIn);
	FREE(ampOut);
        FREE(ampBuf);
	FREE(phaseOut);
	FREE(table);
	FCLOSE(fiamp);
	FCLOSE(fiphase);
	FCLOSE(foamp);
	FCLOSE(fophase);
  
	/* free all memory, close files, print out time elapsed */
	FREE(redPtr);
	FREE(grnPtr);
	FREE(bluPtr);
	FREE(imgData);
	FCLOSE(flas);

        meta_free(meta);
        meta_free(meta_stat);
        meta_free(meta_old);

	return 0;
}
예제 #19
0
Nrrd* LSMReader::Convert(int t, int c, bool get_max)
{
    Nrrd *data = 0;
    FILE* pfile = 0;
    if (!WFOPEN(&pfile, m_path_name.c_str(), L"rb"))
        return 0;

    int i, j;

    if (t>=0 && t<m_time_num &&
            c>=0 && c<m_chan_num &&
            m_slice_num > 0 &&
            m_x_size > 0 &&
            m_y_size > 0 &&
            t<(int)m_lsm_info.size() &&
            c<(int)m_lsm_info[t].size())
    {
        //allocate memory for nrrd
        switch (m_datatype)
        {
        case 1://8-bit
        {
            unsigned long long mem_size = (unsigned long long)m_x_size*
                                          (unsigned long long)m_y_size*(unsigned long long)m_slice_num;
            unsigned char *val = new (std::nothrow) unsigned char[mem_size];
            ChannelInfo *cinfo = &m_lsm_info[t][c];
            for (i=0; i<(int)cinfo->size(); i++)
            {
                if (m_l4gb?
                        FSEEK64(pfile, ((uint64_t((*cinfo)[i].offset_high))<<32)+(*cinfo)[i].offset, SEEK_SET)==0:
                        fseek(pfile, (*cinfo)[i].offset, SEEK_SET)==0)
                {
                    unsigned int val_pos = m_x_size*m_y_size*i;
                    if (m_compression==1)
                        fread(val+val_pos, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                    else if (m_compression==5)
                    {
                        unsigned char* tif = new (std::nothrow) unsigned char[(*cinfo)[i].size];
                        fread(tif, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                        LZWDecode(tif, val+val_pos, (*cinfo)[i].size);
                        for (j=0; j<m_y_size; j++)
                            DecodeAcc8(val+val_pos+j*m_x_size, m_x_size,1);
                        delete []tif;
                    }
                }
            }
            //create nrrd
            data = nrrdNew();
            nrrdWrap(data, val, nrrdTypeUChar, 3, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoSpacing, m_xspc, m_yspc, m_zspc);
            nrrdAxisInfoSet(data, nrrdAxisInfoMax, m_xspc*m_x_size, m_yspc*m_y_size, m_zspc*m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoMin, 0.0, 0.0, 0.0);
            nrrdAxisInfoSet(data, nrrdAxisInfoSize, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
        }
        break;
        case 2://16-bit
        case 3:
        {
            unsigned long long mem_size = (unsigned long long)m_x_size*
                                          (unsigned long long)m_y_size*(unsigned long long)m_slice_num;
            unsigned short *val = new (std::nothrow) unsigned short[mem_size];
            ChannelInfo *cinfo = &m_lsm_info[t][c];
            for (i=0; i<(int)cinfo->size(); i++)
            {
                if (m_l4gb?
                        FSEEK64(pfile, ((uint64_t((*cinfo)[i].offset_high))<<32)+(*cinfo)[i].offset, SEEK_SET)==0:
                        fseek(pfile, (*cinfo)[i].offset, SEEK_SET)==0)
                {
                    unsigned int val_pos = m_x_size*m_y_size*i;
                    if (m_compression==1)
                        fread(val+val_pos, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                    else if (m_compression==5)
                    {
                        unsigned char* tif = new (std::nothrow) unsigned char[(*cinfo)[i].size];
                        fread(tif, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                        LZWDecode(tif, (tidata_t)(val+val_pos), (*cinfo)[i].size);
                        for (j=0; j<m_y_size; j++)
                            DecodeAcc16((tidata_t)(val+val_pos+j*m_x_size), m_x_size,1);
                        delete []tif;
                    }
                }
            }
            //create nrrd
            data = nrrdNew();
            nrrdWrap(data, val, nrrdTypeUShort, 3, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoSpacing, m_xspc, m_yspc, m_zspc);
            nrrdAxisInfoSet(data, nrrdAxisInfoMax, m_xspc*m_x_size, m_yspc*m_y_size, m_zspc*m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoMin, 0.0, 0.0, 0.0);
            nrrdAxisInfoSet(data, nrrdAxisInfoSize, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
        }
        break;
        }
    }

    fclose(pfile);

    return data;
}
예제 #20
0
int read_asf_client(int row_start, int n_rows_to_get,
                    void *dest_void, void *read_client_info,
                    meta_parameters *meta, int data_type)
{
    ReadAsfClientInfo *info = (ReadAsfClientInfo*) read_client_info;
    int nl = meta->general->line_count;
    int ns = meta->general->sample_count;

    if (meta->general->data_type == ASF_BYTE) {
        unsigned char *dest = (unsigned char*)dest_void;
        if (data_type==GREYSCALE_BYTE) {
            // reading byte data directly into the byte cache
            FSEEK64(info->fp, ns*(row_start + nl*info->band_gs), SEEK_SET);
            FREAD(dest, sizeof(unsigned char), n_rows_to_get*ns, info->fp);
        }
        else {
            // will have to figure this one out
            assert(!info->ml);

            // Here we have to read three separate strips of the
            // file to compose into the byte cache (which has interleaved
            // rgb values -- red vals coming from the first strip we read,
            // green from the second, and blues from the third.
            // So, we need a temporary buffer to place the values, so they
            // can be interleaved (i.e., we can't read directly into the
            // cache's memory)
            unsigned char *buf = MALLOC(sizeof(unsigned char)*ns);

            // first set the cache's memory to all zeros, this way any
            // rgb channels we don't populate will end up black
            memset(dest, 0, n_rows_to_get*ns*3);

            // red
            if (info->band_r >= 0) {
                int i,j,off = ns*(row_start + nl*info->band_r);
                for (i=0; i<n_rows_to_get; ++i) {
                    int k = 3*ns*i;
                    FSEEK64(info->fp, off + i*ns, SEEK_SET);
                    FREAD(buf, sizeof(unsigned char), ns, info->fp);
                    for (j=0; j<ns; ++j, k += 3)
                        dest[k] = buf[j];
                }
            }

            // green
            if (info->band_g >= 0) {
                int i,j,off = ns*(row_start + nl*info->band_g);
                for (i=0; i<n_rows_to_get; ++i) {
                    int k = 3*ns*i+1;
                    FSEEK64(info->fp, off + i*ns, SEEK_SET);
                    FREAD(buf, sizeof(unsigned char), ns, info->fp);
                    for (j=0; j<ns; ++j, k += 3)
                        dest[k] = buf[j];
                }
            }

            // blue
            if (info->band_b >= 0) {
                int i,j,off = ns*(row_start + nl*info->band_b);
                for (i=0; i<n_rows_to_get; ++i) {
                    int k = 3*ns*i+2;
                    FSEEK64(info->fp, off + i*ns, SEEK_SET);
                    FREAD(buf, sizeof(unsigned char), ns, info->fp);
                    for (j=0; j<ns; ++j, k += 3)
                        dest[k] = buf[j];
                }
            }

            free(buf);
        }
    } else {
        float *dest = (float*)dest_void;
        if (data_type==GREYSCALE_FLOAT) {
            // this is the normal case, just reading in a strip of lines
            // from the file directly into the floating point cache
            get_asf_lines(info, meta, row_start + nl*info->band_gs,
                          n_rows_to_get, dest);
        } else {
            // grabbing 3 channels floating point data
            assert(data_type==RGB_FLOAT);

            // first set the cache's memory to all zeros, this way any
            // rgb channels we don't populate will end up black
            memset(dest, 0, n_rows_to_get*ns*3*sizeof(float));
            float *buf = MALLOC(sizeof(float)*ns);
            int i,j,k;

            if (info->band_r >= 0) {
                for (i=0; i<n_rows_to_get; ++i) {
                    get_asf_line(info, meta, row_start + nl*info->band_r + i, buf);
                    for (j=0, k=3*ns*i; j<ns; ++j, k += 3)
                        dest[k] = buf[j];
                }
            }

            if (info->band_g >= 0) {
                for (i=0; i<n_rows_to_get; ++i) {
                    get_asf_line(info, meta, row_start + nl*info->band_g + i, buf);
                    for (j=0, k=3*ns*i+1; j<ns; ++j, k += 3)
                        dest[k] = buf[j];
                }
            }

            if (info->band_b >= 0) {
                for (i=0; i<n_rows_to_get; ++i) {
                    get_asf_line(info, meta, row_start + nl*info->band_b + i, buf);
                    for (j=0, k=3*ns*i+2; j<ns; ++j, k += 3)
                        dest[k] = buf[j];
                }
            }

            free(buf);
        }
    }

    return TRUE;
}
예제 #21
0
// reads a file from ark into currently open file descriptor "destFd"
bool ArkFile::ReadFile(FILE* destFd, const FileEntry& entry, bool performDecrypts)
{
	if( !IsOpen() )
		return false;
	
	if(destFd == NULL)
		return false;
	
	// test for possible encrypted song files
	bool is_mogg_file	= performDecrypts && (strstr(entry.Arkname(), ".mogg") != 0);
	bool is_pss_file	= performDecrypts && (strstr(entry.Arkname(), ".pss") != 0);
	bool is_vgs_file	= performDecrypts && (strstr(entry.Arkname(), ".vgs") != 0);
	
	if( entry.IsExternal() )
	{
		// read out file from external file on pc
		FILE* src_fd = fopen(entry.Filename(), "rb");
		if(src_fd == NULL)
			return false;

		s64 filesize;
		if( !performDecrypts && entry.Encrypted() )
		{
			// external file is in decrypted form on pc
			// but is required to be read out in encrypted form
			// this occurs when an external file is added to an ark then the ark is "saved as"
			unsigned char* temp = new unsigned char[(int)entry.Arksize()];
			memcpy(temp, &G_CRYPT_KEY, 4);
			if( fread( temp+4, 1, (int)entry.Filesize(), src_fd) != entry.Filesize() )
			{
				delete[] temp;
				return false;
			}
			if( mNewEncryption )
				dtb_crypt_new(temp, (int)entry.Arksize());
			else
				dtb_crypt_old(temp, (int)entry.Arksize());
			if( fwrite(temp, 1, (int)entry.Arksize(), destFd) != entry.Arksize() )
			{
				delete[] temp;
				return false;
			}
			delete[] temp;
			return true;
		}
		else if( performDecrypts && entry.Encrypted() )
		{
			// external file is in decrypted form on pc
			// but is required to be read out in decrypted form
			// so just read it straight out
			filesize = entry.Filesize();
		}
		else if( !entry.Encrypted() )
		{
			// external file either isnt encrypted
			filesize = entry.Arksize();
		}
		for(s64 i=0; i<filesize; i+=MS_WORK_BUFFER_SIZE)
		{
			int read_size = (int)(min(filesize-i, MS_WORK_BUFFER_SIZE));
			if( fread( mpWorkBuff, 1, read_size, src_fd) != read_size ||
				fwrite(mpWorkBuff, 1, read_size, destFd) != read_size )
			{
				fclose(src_fd);
				return false;
			}
		}
		
		bool read_result = true;
		
		// decrypt output song files if they need to be
		if(is_mogg_file)
		{
			s64 end_file_loc = FTELL64(destFd);
			FSEEK64(destFd, -entry.Arksize(), SEEK_CUR);
			if( IsMoggEncrypted(destFd) )
				read_result = DecryptMogg(destFd);
			else
				FSEEK64(destFd, end_file_loc, SEEK_SET);
		}
		else if(is_pss_file)
		{
			s64 end_file_loc = FTELL64(destFd);
			FSEEK64(destFd, -entry.Arksize(), SEEK_CUR);
			if( IsPssEncrypted(destFd) )
				read_result = DecryptPss(destFd);
			else
				FSEEK64(destFd, end_file_loc, SEEK_SET);
		}
		else if(is_vgs_file)
		{
			s64 end_file_loc = FTELL64(destFd);
			FSEEK64(destFd, -entry.Arksize(), SEEK_CUR);
			if( IsVgsEncrypted(destFd) )
				read_result = DecryptVgs(destFd);
			else
				FSEEK64(destFd, end_file_loc, SEEK_SET);
		}
		
		// close external source file
		fclose(src_fd);
		return read_result;
	}
	else
	{
		// read out file from inside ark file
		FILE* src_fd = GetHandleFromOffset(entry.Offset(), true);
		if(src_fd == NULL)
			return false;
		
		if( performDecrypts && entry.Encrypted() )
		{
			// file needs to be decrypted
			unsigned char* temp = new unsigned char[(int)entry.Arksize()];
			if( fread( temp, 1, (int)entry.Arksize(), src_fd) != entry.Arksize() )
			{
				delete[] temp;
				return false;
			}
			if( mNewEncryption )
				dtb_crypt_new(temp, (int)entry.Arksize());
			else
				dtb_crypt_old(temp, (int)entry.Arksize());
			if( fwrite(temp+4, 1, (int)entry.Filesize(), destFd) != entry.Filesize() )
			{
				delete[] temp;
				return false;
			}
			delete[] temp;
			return true;
		}
		else
		{
			for(s64 i=0; i<entry.Arksize(); i+=MS_WORK_BUFFER_SIZE)
			{
				int read_size = (int)(min(entry.Arksize()-i, MS_WORK_BUFFER_SIZE));
				if( fread( mpWorkBuff, 1, read_size, src_fd) != read_size ||
					fwrite(mpWorkBuff, 1, read_size, destFd) != read_size )
				{
					return false;
				}
			}
			bool read_result = true;
			if(is_mogg_file)
			{
				s64 end_file_loc = FTELL64(destFd);
				FSEEK64(destFd, -entry.Arksize(), SEEK_CUR);
				if( IsMoggEncrypted(destFd) )
					read_result = DecryptMogg(destFd);
				else
					FSEEK64(destFd, end_file_loc, SEEK_SET);
			}
			else if(is_pss_file)
			{
				s64 end_file_loc = FTELL64(destFd);
				FSEEK64(destFd, -entry.Arksize(), SEEK_CUR);
				if( IsPssEncrypted(destFd) )
					read_result = DecryptPss(destFd);
				else
					FSEEK64(destFd, end_file_loc, SEEK_SET);
			}
			else if(is_vgs_file)
			{
				s64 end_file_loc = FTELL64(destFd);
				FSEEK64(destFd, -entry.Arksize(), SEEK_CUR);
				if( IsVgsEncrypted(destFd) )
					read_result = DecryptVgs(destFd);
				else
					FSEEK64(destFd, end_file_loc, SEEK_SET);
			}
			return read_result;
		}
	}
}
예제 #22
0
// from a given offset into an ark, the correct file handle is returned
// which is pointing at the correct offset in that file
// (will seek to a new offset outside of current bounds)
// 
// args:	offset into ark
//			flag or whether to seek outside existing file sizes
// returns:	file handle if successful
//			NULL if error
FILE* ArkFile::GetHandleFromOffset(s64 offset, bool offsetMustExist)
{
	s64 filesize;
	for(int i=0; i<(int)mArkHandles.size(); i++)
	{
		if((filesize=GetFilesize(mArkHandles[i])) < 0)
			return NULL;
		if(offset >= filesize)
		{
			// if there is still another ark file after this one
			// then update the offset to be in that ark file
			if(i+1 < (int)mArkHandles.size())
				offset -= filesize;
			else
				break;
		}
		else
		{
			FSEEK64(mArkHandles[i], offset, SEEK_SET);
			return mArkHandles[i];
		}
	}
	
	// offset is outside of the current file space
	if(offsetMustExist)
		return NULL;
	
	// check if we need to open a new ark file
	char zero[1] = {0};
	FILE* fd = NULL;
	if(offset >= mMaxArkSize &&
		mMaxArkSize != 0)
	{
		// pad the current ark file up to the max ark size limit,
		// then create a new ark file and seek to the required offset in it
		fd = mArkHandles[mArkHandles.size()-1];
		FSEEK64(fd, 0, SEEK_END);
		if(FTELL64(fd) < mMaxArkSize)
		{
			FSEEK64(fd, mMaxArkSize-1, SEEK_SET);
			fwrite(zero, 1, 1, fd);
		}
		offset -= mMaxArkSize;
		char new_filename[260];
		sprintf(new_filename, "%s%cMAIN_%d.ARK", mDirname, DIRSEPCHAR, (int) mArkHandles.size());
		FILE* fd = fopen(new_filename, "w+b");
		if(fd == NULL)
			return NULL;
		mArkHandles.push_back(fd);
		if(offset > 0)
		{
			FSEEK64(fd, offset-1, SEEK_SET);
			fwrite(zero, 1, 1, fd);
		}
		return fd;
	}
	else
	{
		// according to posix specifications, an fseek followed by an fwrite
		// should make a file grow to the new end of file mark.
		// (check the file needs to grow first though)
		fd = mArkHandles[mArkHandles.size()-1];
		FSEEK64(fd, 0, SEEK_END);
		if(FTELL64(fd) < offset)
		{
			FSEEK64(fd, offset-1, SEEK_SET);
			fwrite(zero, 1, 1, fd);
		}
		else
		{
			FSEEK64(fd, offset, SEEK_SET);
		}
		return fd;
	}
}
예제 #23
0
/******************************************************************************
fillOutGetRec:
    Given a file name, returns a "getRec", which you can pass to
getSignalLine to fetch a line of signal data.
*/
getRec * fillOutGetRec(char file[])
{
    getRec *r=(getRec *)MALLOC (sizeof(getRec));
    char name_ASF[1024],name_RAW[1024];
    FILE *fp_ASF, *fp_RAW;
    int skip_second_if=0;

    create_name(name_ASF,file,".D");
    /* Lower case fopen used to control if statement */
    fp_ASF=fopen(name_ASF,"rb");

    create_name(name_RAW,file,".img");
    /* Lower case fopen used to control if statement */
    fp_RAW=fopen(name_RAW,"rb");

    r->lines=NULL;
    if (fp_ASF!=NULL)
    {
        struct        IOF_VFDR ifiledr;
        r->flipIQ='y';
        r->sampleSize=2;
        r->fp_in=fp_ASF;
        get_ifiledr(file,&ifiledr);
        if(!quietflag)printf("Looking for %s...\n",name_ASF);

    /**Make sure input file is a CCSD file and not a CEOS**/
        if (strcmp(ifiledr.formcode,"CI*2")!=0)
        {
          fprintf(stderr, "  %s is not a CCSD file.\n", name_ASF);
          if (!quietflag)printf("Looking for %s...\n",name_RAW);
        }
         else
        {
        if (!quietflag)
          printf("   Found ASF CCSD file '%s'...\n",name_ASF);
        skip_second_if++;
        r->lineSize=ifiledr.reclen;
        r->nSamples=ifiledr.datgroup;
        FSEEK64(r->fp_in,0,SEEK_END);
        r->nLines=FTELL64(r->fp_in)/r->lineSize;/*Automatically figure out number of lines in file.*/
        r->header=ifiledr.reclen+(ifiledr.reclen - ifiledr.sardata);
        r->dcOffsetI=r->dcOffsetQ=15.5;
        }
    }
    if ((fp_RAW!=NULL)&&(!skip_second_if))
    {
        long long bytesInFile;

        if (!quietflag) printf("   Found Raw, manual file '%s'...\n",name_RAW);

        r->header=0;/*Assume a zero-byte header*/
        r->dcOffsetI=r->dcOffsetQ=15.5;
        r->flipIQ='n';
        r->sampleSize=2;
        r->fp_in=fp_RAW;
        FSEEK64(r->fp_in,0,SEEK_END);
        bytesInFile=FTELL64(r->fp_in);

        getSignalFormat(file,bytesInFile,r);
    }
    r->inputArr=(unsigned char *)MALLOC(r->sampleSize*r->nSamples);
    return r;
}