Example #1
0
static _rti_colormap_arg
_rti_colormap_arg_init(rt_raster raster) {
	_rti_colormap_arg arg = NULL;

	arg = rtalloc(sizeof(struct _rti_colormap_arg_t));
	if (arg == NULL) {
		rterror("_rti_colormap_arg_init: Could not allocate memory for _rti_color_arg");
		return NULL;
	}

	arg->band = NULL;
	arg->nodataentry = NULL;
	arg->hasnodata = 0;
	arg->nodataval = 0;

	if (raster == NULL)
		arg->raster = NULL;
	/* raster provided */
	else {
		arg->raster = rt_raster_clone(raster, 0);
		if (arg->raster == NULL) {
			rterror("_rti_colormap_arg_init: Could not create output raster");
			return NULL;
		}
	}

	arg->nexpr = 0;
	arg->expr = NULL;

	arg->npos = 0;
	arg->pos = NULL;

	return arg;
}
Example #2
0
static int
_rti_iterator_arg_empty_init(_rti_iterator_arg _param) {
	int x = 0;
	int y = 0;

	_param->empty.values = rtalloc(sizeof(double *) * _param->dimension.rows);
	_param->empty.nodata = rtalloc(sizeof(int *) * _param->dimension.rows);
	if (_param->empty.values == NULL || _param->empty.nodata == NULL) {
		rterror("_rti_iterator_arg_empty_init: Could not allocate memory for empty values and NODATA");
		return 0;
	}

	for (y = 0; y < _param->dimension.rows; y++) {
		_param->empty.values[y] = rtalloc(sizeof(double) * _param->dimension.columns);
		_param->empty.nodata[y] = rtalloc(sizeof(int) * _param->dimension.columns);

		if (_param->empty.values[y] == NULL || _param->empty.nodata[y] == NULL) {
			rterror("_rti_iterator_arg_empty_init: Could not allocate memory for elements of empty values and NODATA");
			return 0;
		}

		for (x = 0; x < _param->dimension.columns; x++) {
			_param->empty.values[y][x] = 0;
			_param->empty.nodata[y][x] = 1;
		}
	}

	return 1;
}
Example #3
0
static int
getfsample(double sampleno, float *c, int input)
{
	int RECSIZE = bufsize[input];
	int BPREC = RECSIZE * sizeof(float);
	int BPFRAME = sfchans(&sfdesc[input]) * sizeof(float);
	int FPREC = RECSIZE/(float)sfchans(&sfdesc[input]);

	int sample,i,j,nbytes;
	float *array = (float *)sndbuf[input];
	float fraction,tempfloat1,tempfloat2;
	static int oldsample = 0;
	static int endsample = 0;
	extern float swapfloat();

	sample = (int)sampleno;
	fraction = sampleno - (double)sample;
	if(!((sample >= oldsample) && (sample < endsample))) {
		/* sflseek (sfheader.h) assumes header size, so can't use it */
		if(lseek(sfd[input], (sample * BPFRAME) + headersize[input],
							SEEK_SET) <= 0) {
			rterror(NULL,"badlseek on inputfile\n");
			closesf();
		}
		nbytes = read(sfd[input], (char *)array, BPREC);
		if (nbytes == -1) {
			perror("getfsample: read");
			return 0;
		}
		if (nbytes == 0) {
			rterror(NULL, "reached eof on input file\n");
			return 0;
		}
		if (nbytes < BPREC)     /* zero out rest of sndbuf */
			for (i = nbytes; i < BPREC; i++)
				sndbuf[input][i] = 0;
		oldsample = sample;
		endsample = oldsample + FPREC - 1;
		}
	for(i = (sample-oldsample)*sfchans(&sfdesc[input]),j=0; 
					j<sfchans(&sfdesc[input]); i++,j++)  {
	  if (swap_bytes[input]) {
	    tempfloat1 = *(array+i);
	    byte_reverse4(&tempfloat1);
	    tempfloat2 = (*(array+i+sfchans(&sfdesc[input])));
	    byte_reverse4(&tempfloat2)
	      *(c+j) = tempfloat1 + fraction * (tempfloat2-tempfloat1);
	  }
	  else {
	    *(c+j) = *(array+i) + fraction * 
	      (*(array+i+sfchans(&sfdesc[input])) - *(array+i));
	  }
	}
	return(1);
}
Example #4
0
int KFProcessBind::DoBind(KFDataParseBind *dpb, KFBindJudge *bj, KFNetwork *net) 
{
    if (!bj || !net) return -1;
    rtinfo("=========== Start check bind judge ================");
    rtdebug("Enter do bindjudge");
    int ret = dpb->KFDataParseBindGenerateData(bj);
    if (ret < 0) return -2;
    const char *data = dpb->KFDataParseBindGenerateData();
    if (data)
    {
        rtdebug("data is : %s", data);
        char outData[2048] = {0};
        int  iDataLen = 0;
//        ret = net->KFNetworkRequest((char*)data, 0);
        ret = net->KFNetworkSendRequest((char*)data, 0, outData, &iDataLen);
        if (ret != 200)
        {
            rterror("error bindjudge [%s] ret: [%d]", outData, ret);
            return -3;
        }
        else
        {
            rtdebug("result data: %s, %d", outData, iDataLen);

            ret = dpb->KFDataParseResult(outData, iDataLen);
            if (ret < 0)
            {
                char *errorCode = dpb->KFDataParseCmdErrorCode();
                const char *resultCode = dpb->KFDataParseResultCode().c_str();
                rterror("parse bindjudge failed %d , errorcode [%s] resultCode [%s]", ret, errorCode, resultCode);
                return -4;
            }
            else
            {
                std::string result = dpb->BindResult();
                if (result.compare("Y") == 0) {
                    return 1;
                } 
                else if (result.compare("S") == 0) {
                    return -5;
                } // "S"
                else if (result.compare("N") == 0) {
                    return -6;
                } // "N"
            }
        }
    }
    rtdebug("Exit do bindjudge");
    return 0;
}
Example #5
0
int jk_conn_tcp_recv(JKConnTCP conn, char *recvData, long *recvLen, int bCycle)
{
    if (!conn || !recvData || !recvLen) return -1;

    int sockfd = conn->sockFD;
    long containLen = *recvLen;
    *recvLen = 0;
    do {
        char data[1024] = {0};
        int lendata = 1024;
        int nBytes = recv(sockfd, data, lendata, 0);
        if (nBytes == 0) continue;
        if (nBytes == -1) {
            rterror("Read data error %s", strerror(errno));
            conn->status = 0;
            return -2;
        }
        memcpy(recvData + *recvLen, data, nBytes);
        *recvLen += nBytes;

        if (*recvLen >= containLen) {
            return 1;
        }
    } while(bCycle);

    return 0;
}
int KFDataParseQueryIP::KFDataParseQueryIPResult(const char *result, int len) {
    char data[10240] = {0};
    // check if has common error
    strncpy(data, result, len);
    Json::Reader jrd;
    Json::Value json_result;
    jrd.parse(data, json_result, 0);
    int ret = this->KFDataParseGeneralError(json_result);
    if (ret < 0) {
        // Result is fail. do something.
        return ret;
    }
    ret = this->KFDataParseHeadValid(json_result);
    if (ret < 0) {
        return ret;
    }

    ret = this->KFDataParseResultError(json_result[KF_STR_MSGBODY][KF_STR_RESULT]);
    if (ret < 0) {
        return ret;
    }

    Json::Value jData = json_result[KF_STR_MSGBODY][KF_STR_RESULT];
    if (jData[KF_STR_RESULTDATA] != Json::nullValue) {
        rtdebug("Start to parse resultData");
        Json::Value json_rdata = jData[KF_STR_RESULTDATA];
        KFDataParseIPProperties *prop = &this->stIPS[0];
        this->iIPCnts = 0;
        for(int it = 0; it < json_rdata.size(); ++it) {
            Json::Value rd = json_rdata[it];
            if (rd[KF_STR_BELONGGROUP] != Json::nullValue) {
                prop->iBelongGroup = atoi(rd[KF_STR_BELONGGROUP].asString().c_str());
            }
            Json::Value distance = rd[KF_STR_DISTANCE];
            if (distance != Json::nullValue) {
                snprintf(prop->szDistance, sizeof(prop->szDistance), "%s", distance.asString().c_str());
            }
            Json::Value lat = rd[KF_STR_LATITUDE];
            if (lat != Json::nullValue) {
                prop->fLatitude = atof(lat.asString().c_str());
            }
            Json::Value longi = rd[KF_STR_LONGITUDE];
            if (longi != Json::nullValue) {
                prop->fLongitude = atof(longi.asString().c_str());
            }
            Json::Value sip = rd[KF_STR_SERVERIP];
            if (sip != Json::nullValue) {
                snprintf(prop->szIP, sizeof(prop->szIP), "%s", sip.asString().c_str());
                rtdebug("The ip is [%s]", prop->szIP);
            }
            this->iIPCnts++;
            prop++;
        }
    } else {
        rterror("didn't give result data when success");
        return -2;
    }

    return 0;
}
Example #7
0
int *ivector(long int nh)
/* allocate a integer vector with subscript range v[0..nh-1] */
{
  int *v;
  v=(int *)malloc((size_t) (nh*sizeof(int)));
  if (!v) rterror("allocation failure in ivector()");
  return (v);
}
Example #8
0
char *cvector(long int nh)
/* allocate a character vector with subscript range v[0..nh-1] */
{
  char *v;
  v=(char *)malloc((size_t) (nh*sizeof(char)));
  if (!v) rterror("allocation failure in cvector()");
  return (v);
}
Example #9
0
static int
_rti_iterator_arg_callback_init(_rti_iterator_arg _param) {
	int i = 0;

	_param->arg = rtalloc(sizeof(struct rt_iterator_arg_t));
	if (_param->arg == NULL) {
		rterror("_rti_iterator_arg_callback_init: Could not allocate memory for rt_iterator_arg");
		return 0;
	}

	_param->arg->values = NULL;
	_param->arg->nodata = NULL;
	_param->arg->src_pixel = NULL;

	/* initialize argument components */
	_param->arg->values = rtalloc(sizeof(double **) * _param->count);
	_param->arg->nodata = rtalloc(sizeof(int **) * _param->count);
	_param->arg->src_pixel = rtalloc(sizeof(int *) * _param->count);
	if (_param->arg->values == NULL || _param->arg->nodata == NULL || _param->arg->src_pixel == NULL) {
		rterror("_rti_iterator_arg_callback_init: Could not allocate memory for element of rt_iterator_arg");
		return 0;
	}
	memset(_param->arg->values, 0, sizeof(double **) * _param->count);
	memset(_param->arg->nodata, 0, sizeof(int **) * _param->count);

	/* initialize pos */
	for (i = 0; i < _param->count; i++) {

		_param->arg->src_pixel[i] = rtalloc(sizeof(int) * 2);
		if (_param->arg->src_pixel[i] == NULL) {
			rterror("_rti_iterator_arg_callback_init: Could not allocate memory for position elements of rt_iterator_arg");
			return 0;
		}
		memset(_param->arg->src_pixel[i], 0, sizeof(int) * 2);
	}

	_param->arg->rasters = _param->count;
	_param->arg->rows = _param->dimension.rows;
	_param->arg->columns = _param->dimension.columns;

	_param->arg->dst_pixel[0] = 0;
	_param->arg->dst_pixel[1] = 0;

	return 1;
}
Example #10
0
double *dvector(long int nh)
/* allocate a double vector with subscript range v[0..nh-1]*/
{
  double *v;

  v=(double *)malloc((size_t) (nh*sizeof(double)));
  if (!v) rterror("allocation failure in dvector()");
  return (v);
}
Example #11
0
float *vector(long int nh)
/* allocate a float vector with subscript range v[0..nh-1] */
{
  float *v;

  v=(float *)malloc((size_t) (nh*sizeof(float)));
  if (!v) rterror("allocation failure in vector()");
  return (v);
}
Example #12
0
int *ivectorc(long int nh)
/* allocate a integer vector with subscript range v[0..nh-1] */
/* and initialize to zero */
{
  int *v;
  v=(int *)calloc(1, (size_t) (nh*sizeof(int)));
  if (!v) rterror("allocation failure in ivectorc()");
  return (v);
}
Example #13
0
double dataset(float *p, int n_args, double *pp)
/* p1=dataset name, p2=npoles */
{
	int i, set;
	char *name=DOUBLE_TO_STRING(pp[0]);

	if (name == NULL) {
		rterror("dataset", "NULL file name");
		return -1;
	}

	// Search all open dataset slots for matching name
	for (set = 0; set < maxDataSets && strlen(g_dataset_names[set]); ++set) {
		if (strcmp(name, g_dataset_names[set]) == 0) {
			g_currentDataset = set;
			::rtcmix_advise("dataset", "Using already open dataset at slot %d", set);
			return g_datasets[g_currentDataset]->getFrameCount();
		}
	}
	if (set >= maxDataSets) {
		::rterror("dataset", "Maximum number of datasets exceeded");
		return -1;
	}

	// OK, this is a new set that we will put in a new slot

	g_currentDataset = set;

	strcpy(g_dataset_names[g_currentDataset],name);

	int npolesGuess = 0;
	if(n_args>1)	/* if no npoles specified, it will be retrieved from */
		npolesGuess= (int) p[1];	/* the header (if USE_HEADERS #defined) */

	DataSet *dataSet = new DataSet;
	
	int frms = dataSet->open(name, npolesGuess, RTcmix::sr());
	
	if (frms < 0)
	{
		if (dataSet->getNPoles() == 0) {
			::rterror("dataset",
				"For this file, you must specify the correct value for npoles in p[1].");
		}
		return -1;
	}

	::rtcmix_advise("dataset", "File has %d poles and %d frames.",
			dataSet->getNPoles(), frms);
	
	// Add to dataset list.
	g_datasets[g_currentDataset] = dataSet;

	dataSet->ref();	// Note:  For now, datasets are never destroyed during run.

	return (double) frms;
}
Example #14
0
unsigned long int *lvector(long int nh)
/* allocate an unsigned long int vector with subscript range v[0..nh-1] */
{
  unsigned long int *v;

  v=(unsigned long int *)malloc((size_t) (nh*sizeof(unsigned long int)));
  if (!v) rterror("allocation failure in lvector()");
  return (v);
}
Example #15
0
double *dvectorc(long int nh)
/* allocate a double vector with subscript range v[0..nh-1]
 * and initialize to zero */
{
  double *v;

  v=(double *)calloc(1, (size_t) (nh*sizeof(double)));
  if (!v) rterror("allocation failure in dvectorc()");
  return (v);
}
Example #16
0
int MBASE::alloc_firfilters()
{
   /* allocate memory for FIR filters and zero delays */
   for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 13; j++) {
         m_vectors[i][j].Firtaps = new double[g_Nterms[j] + 1];
		 if (m_vectors[i][j].Firtaps == NULL) {
		 	rterror("MBASE (alloc_firfilters/Firtaps)", "Memory failure during setup");
			return -1;
		 }
		 memset(m_vectors[i][j].Firtaps, 0, (g_Nterms[j] + 1) * sizeof(double));
         m_vectors[i][j].Fircoeffs = new double[g_Nterms[j]];
		 if (m_vectors[i][j].Fircoeffs == NULL) {
		 	rterror("MBASE (alloc_firfilters/Fircoeffs)", "Memory failure during setup");
			return -1;
		 }
      }
   }
   return 0;
}
Example #17
0
/* Sets aside the memory needed for tap delay
*/
int MBASE::alloc_delays()
{
	assert(m_tapsize > 0);
    m_tapDelay = new double[m_tapsize + 8];
	if (m_tapDelay == NULL) {
		rterror("MBASE (alloc_delays)", "Memory failure during setup");
		return -1;
	}
	memset(m_tapDelay, 0, (m_tapsize + 8) * sizeof(double));
	return 0;
}
Example #18
0
float gammq(float a, float x)
{
 float gamser,gammcf,gln;

 if (x < 0.0 || a <= 0.0) rterror("Invalid arguments in routine gammq");
 if (x < (a+1.0)) {
    gser(&gamser,a,x,&gln);
    return 1.0-gamser;
 } else {
    gcf(&gammcf,a,x,&gln);
    return gammcf;
 }
}
Example #19
0
/* Sets aside the memory needed for tap delay and the delays in RVB
*/
int BASE::alloc_delays()
{
	assert(m_tapsize > 0);
	m_tapDelay = new double[m_tapsize + 8];
	if (m_tapDelay == NULL) {
		rterror("BASE (alloc_delays)", "Memory failure during setup");
		return -1;
	}
	memset(m_tapDelay, 0, (m_tapsize + 8) * sizeof(double));

   /* allocate memory for reverb delay lines */
   for (int i = 0; i < 2; i++) {
	  for (int j = 0; j < 6; j++) {
		 m_rvbData[i][j].Rvb_del = new double[rvbdelsize];
		 if (m_rvbData[i][j].Rvb_del == NULL) {
			rterror("BASE (alloc_delays/Rvb_del)", "Memory failure during setup");
			return -1;
		 }
		 memset(m_rvbData[i][j].Rvb_del, 0, sizeof(double) * rvbdelsize);
	  }
   }
   return 0;
}
Example #20
0
void dstddev(double *datavec, int n, double *ave, double *sdev, double *var)
{
 void nrerror(char error_text[]);
 int j;
 double s,p;

 if (n <= 1) rterror("n must be at least 2 in stddev");
 s=0.0;		/* First pass to get the mean */
 for (j=0;j<n;j++) { s += *(datavec+j);}
 *ave=s/n;
 *var=0;		/* Second pass to get the variance */
 for (j=0;j<n;j++) {
   s=*(datavec+j)-(*ave);
   *var += (p=s*s);
 }
 *var = (*var)/(n-1);
 *sdev = sqrt(*var);	/* Put the pieces together according to the conventional*/
 			/* definitions */
 return;
}
Example #21
0
int PFSCHED::init(double p[], int n_args)
{
// about ths RTBUFSAMPS+1 nonsense:
// 	when a PFSCHED note finishes, it de-allocates the PFields associated
// 	with it.  This is generally not a problem (because the 'connected'
// 	instrument/note drawing from the PField only needs the PField for
// 	the duration specified in the PFSCHED note), but if the duration is
// 	less than one RTBUFSAMP then the PFSCHED note will finish and deallocate
// 	*before* the other instrument gets a chance to read through the
// 	'connected' PField.  Instead of rewriting a huge amount of the PField
// 	code to handle the ref counters, etc. I just make sure that the
// 	PFSCHED note will last at least one buffer longer than the time
// 	computed for the PField to be read.  Almost no additional load
// 	on the CPU, see the run() method below.

	if (rtsetoutput(p[0], p[1]+((double)(RTBUFSAMPS+1)/SR), this) == -1)
		return DONT_SCHEDULE;

	// if set_dq_flag is 1, then the dqflag of pfbusses[] will be set to
	// signal de-queuing at end of this duration/envelope
	if (n_args > 4) set_dq_flag = 1;
	else set_dq_flag = 0;

	pfbus = p[2];

	if (pfbus_is_connected[pfbus] != 1) {
		rterror("PFSCHED", "pfbus %d not connected", pfbus);
		return DONT_SCHEDULE;
	}


	pfbusses[pfbus].drawflag = 0; // the 'connected' note will read when == 1
//	pfbusses[pfbus].thepfield = &((*_pfields)[3]);
//	pfbusses[pfbus].thepfield = &(getPField(3)); // this is the PField to read
	PFSCHEDpfield = &(getPField(3)); // this is the PField to read

	// set the other fields in ::run in case multiple PFSCHEDs on one pfbus
	firsttime = 1;

	return nSamps();
}
Example #22
0
static _rti_iterator_arg
_rti_iterator_arg_init() {
	_rti_iterator_arg _param;

	_param = rtalloc(sizeof(struct _rti_iterator_arg_t));
	if (_param == NULL) {
		rterror("_rti_iterator_arg_init: Could not allocate memory for _rti_iterator_arg");
		return NULL;
	}

	_param->count = 0;

	_param->raster = NULL;
	_param->isempty = NULL;
	_param->offset = NULL;
	_param->width = NULL;
	_param->height = NULL;

	_param->band.rtband = NULL;
	_param->band.hasnodata = NULL;
	_param->band.isnodata = NULL;
	_param->band.nodataval = NULL;
	_param->band.minval = NULL;

	_param->distance.x = 0;
	_param->distance.y = 0;

	_param->dimension.rows = 0;
	_param->dimension.columns = 0;

	_param->empty.values = NULL;
	_param->empty.nodata = NULL;

	_param->arg = NULL;

	return _param;
}
Example #23
0
ErrCode
RTcmix::check_bus_inst_config(BusSlot *slot, Bool visit) {
	int i,j,aux_ctr,out_ctr;
	short *in_check_list;
	short in_check_count;
	CheckQueue *in_check_queue,*last;
	static Bool Visited[MAXBUS];
	Bool Checked[MAXBUS];
	short r_p_count=0;

	/* If we haven't gotten a config yet ... allocate the graph array */
	/* and the playback order list */
	Bus_Config_Status.lock();
	if (Bus_Config_Status == NO) {
		for (i=0;i<MAXBUS;i++) {
			CheckNode *t_node = new CheckNode;
			pthread_mutex_lock(&bus_in_config_lock);
			Bus_In_Config[i] = t_node;
			t_node->ref();
			pthread_mutex_unlock(&bus_in_config_lock);
		}
		Bus_Config_Status = YES;
	}
	Bus_Config_Status.unlock();

	aux_ctr = out_ctr = 0;
	j=0;
	for(i=0;i<MAXBUS;i++) {
		if (visit)
			Visited[i] = NO;
		Checked[i] = NO;
		pthread_mutex_lock(&revplay_lock);
		RevPlay[i] = -1;
		pthread_mutex_unlock(&revplay_lock);
		pthread_mutex_lock(&out_in_use_lock);
		if (OutInUse[i]) {  // DJT For scheduling
			pthread_mutex_lock(&to_out_lock);
			ToOutPlayList[out_ctr++] = i;
			pthread_mutex_unlock(&to_out_lock);
		}
		pthread_mutex_unlock(&out_in_use_lock);
		pthread_mutex_lock(&aux_out_in_use_lock);
		if (AuxOutInUse[i]) {
			pthread_mutex_lock(&to_aux_lock);
			ToAuxPlayList[aux_ctr++] = i;
			pthread_mutex_unlock(&to_aux_lock);
		}
		pthread_mutex_unlock(&aux_out_in_use_lock);
	}

	/* Put the slot being checked on the list of "to be checked" */
	CheckNode *t_node = new CheckNode(slot->auxin, slot->auxin_count);
	last = in_check_queue = new CheckQueue(t_node);
	CheckQueue *savedQueueHead = in_check_queue;

	/* Go down the list of things (nodes) to be checked */
	while (in_check_queue) {
		CheckNode *t_check_node = in_check_queue->node;
		in_check_list = t_check_node->bus_list;
		in_check_count = t_check_node->bus_count;

		for (i=0;i<in_check_count;i++) {
			short t_in = in_check_list[i];

			/* Compare to each of the input slot's output channels */
			for (j=0;(j<slot->auxout_count) && (!Checked[t_in]);j++) {
				const short t_out = slot->auxout[j];
#ifdef PRINTALL
				printf("check_bus_inst_config: checking in=%d out=%d\n",t_in,t_out);
#endif
				/* If they're equal, then return the error */
				if (t_in == t_out) {
					rterror(NULL, "ERROR:  bus_config loop ... config not allowed.\n");
					return LOOP_ERR;
				}
			}
			if (!Checked[t_in]) {
				Checked[t_in] = YES;
			}

			/* If this input channel has other input channels */
			/* put them on the list "to be checked" */

			pthread_mutex_lock(&bus_in_config_lock);
			if ((Bus_In_Config[t_in]->bus_count > 0) && !Visited[t_in]) {
#ifdef PRINTALL
				printf("check_bus_inst_config: adding Bus[%d] to list\n",t_in);
#endif
				pthread_mutex_lock(&has_parent_lock);
				if (HasParent[t_in]) {
#ifdef PRINTPLAY
					printf("check_bus_inst_config: RevPlay[%d] = %d\n",r_p_count,t_in);
#endif
					pthread_mutex_lock(&revplay_lock);
					RevPlay[r_p_count++] = t_in;
					pthread_mutex_unlock(&revplay_lock);
				}
				pthread_mutex_unlock(&has_parent_lock);
				Visited[t_in] = YES;
				CheckQueue *t_queue = new CheckQueue(Bus_In_Config[t_in]);
				last->next = t_queue;
				last = t_queue;
			}
			pthread_mutex_unlock(&bus_in_config_lock);
		}
#ifdef PRINTALL
		printf("check_bus_inst_config: popping ...\n");
#endif
		in_check_queue = in_check_queue->next;
	}

#ifdef PRINTALL
	printf("check_bus_inst_config: cleaning up\n");
#endif
	// Now clean up
	CheckQueue *queue = savedQueueHead;
	while (queue) {
		CheckQueue *next = queue->next;
		delete queue;
		queue = next;
	}
	
	return NO_ERR;
}
/* This routine is used in the Minc score to open up a file for
   writing by RT instruments.  pp[0] is a pointer to the soundfile
   name, disguised as a double by the crafty Minc.  (p[] is passed in
   just for fun.)  Optional string arguments follow the filename,
   and parse_rtoutput_args processes these. See the comment at the
   top of this file for the meaning of these arguments.

   If "clobber" mode is on, we delete an existing file with the
   specified file name, creating a header according to what
   parse_rtoutput_args determines.

   Returns -1.0 if a file is already open for writing. Dies if there
   is any other error.
*/
double
RTcmix::rtoutput(float p[], int n_args, double pp[])
{
   int         error;
   struct stat statbuf;

   if (rtfileit == 1) {
      rterror("rtoutput", "A soundfile is already open for writing...");
      return -1;
   }

   /* flag set to -1 until we reach end of function.  This way, if anything
      fails along the way, we leave this set as we want it.
   */
   rtfileit = -1;

   if (SR == 0) {
      die("rtoutput", "You must call rtsetparams before rtoutput.");
      return -1;
   }

   error = parse_rtoutput_args(n_args, pp);
   if (error)
      return -1;          /* already reported in parse_rtoutput_args */

   error = stat(rtoutsfname, &statbuf);

   if (error) {
      if (errno == ENOENT) { 
         ;              /* File doesn't exist -- no problem */
      }
      else {
         rterror("rtoutput", "Error accessing file \"%s\": %s",
                                                rtoutsfname, strerror(errno));
         return -1;  /* was exit() */
      }
   }
   else {               /* File exists; find out whether we can clobber it */
      if (!get_bool_option(kOptionClobber)) {
         rterror("rtoutput", "\n%s", CLOBBER_WARNING);
         return -1;
      }
      else {
         /* make sure it's a regular file */
		  //JRG commented out!
         //if (!S_ISREG(statbuf.st_mode)) {
         //   rterror("rtoutput", "\"%s\" isn't a regular file; won't clobber it",
         //                                                        rtoutsfname);
         //   return -1;
         //}
      }
   }

   // If user has chosen to turn off audio playback, we delete
   // the device that might have been created during rtsetparams().
   if (!Option::record() && !Option::play()) {
       delete audioDevice;
	   audioDevice = NULL;
   }
   AudioDevice *dev;
   if ((dev = create_audio_file_device(audioDevice,
				   				rtoutsfname, output_header_type,
                                output_data_format, NCHANS, SR,
                                normalize_output_floats,
                                get_bool_option(kOptionCheckPeaks))) == NULL)
      return -1;  /* failed! */

   audioDevice = dev;

   rtfileit = 1;  /* here we finally set this to 1 */

   return 1;
}
/* -------------------------------------------------- parse_rtoutput_args --- */
int
RTcmix::parse_rtoutput_args(int nargs, double pp[])
{
   int   i, j, matched;
   int   normfloat_requested;
   char  *arg;

   if (nargs == 0) {
      rterror("rtoutput", "you didn't specify a file name!");
      return -1;
   }

   rtoutsfname = DOUBLE_TO_STRING(pp[0]);
   if (rtoutsfname == NULL)
   {
      rterror("rtoutput", "NULL file name!");
      return -1;
   }

   output_header_type = header_type_from_filename(rtoutsfname);
   if (output_header_type == -1)
      return -1;
   if (output_header_type == -2)
      output_header_type = DEFAULT_HEADER_TYPE;
   output_data_format = DEFAULT_DATA_FORMAT;

   normfloat_requested = 0;

   for (i = 1; i < nargs; i++) {
      arg = DOUBLE_TO_STRING(pp[i]);

      matched = 0;
      for (j = 0; j < num_params; j++) {
         if (strcasecmp(param_list[j].arg, arg) == 0) {
            matched = 1;
            break;
         }
      }
      if (!matched) {
         rterror("rtoutput", "unrecognized argument \"%s\"", arg);
         return -1;
      }

      switch (param_list[j].type) {
         case HEADER_TYPE:
            output_header_type = param_list[j].value;
            break;
         case DATA_FORMAT:
            output_data_format = param_list[j].value;
            if (output_data_format == MUS_BFLOAT
                           && strcasecmp(param_list[j].arg, "normfloat") == 0)
               normfloat_requested = 1;
            break;
         case ENDIANNESS:  /* currently unused */
            break;
         default:
            break;
      }
   }

   /* Handle some special cases. */

   /* If "wav", make data format little-endian. */
   if (output_header_type == MUS_RIFF) {
      switch (output_data_format) {
         case MUS_BSHORT:
            output_data_format = MUS_LSHORT;
            break;
         case MUS_B24INT:
            output_data_format = MUS_L24INT;
            break;
         case MUS_BFLOAT:
            output_data_format = MUS_LFLOAT;
            break;
      }
   }

   /* If AIFF, use AIFC only if explicitly requested, or if
      the data format is float.
   */
   if (output_header_type == MUS_AIFF && output_data_format == MUS_BFLOAT)
      output_header_type = MUS_AIFC;

   /* If writing to a float file, decide whether to normalize the
      samples, i.e., to divide them all by 32768 so as to make the
      normal range fall between -1.0 and +1.0. This is what Snd
      and sndlib like to see, but it's not the old cmix way.
   */
   if (normfloat_requested)
      normalize_output_floats = 1;

   is_float_format = IS_FLOAT_FORMAT(output_data_format);

#ifdef ALLBUG
   fprintf(stderr, "name: %s, head: %d, data: %d, norm: %d\n",
                   rtoutsfname, output_header_type, output_data_format,
                   normalize_output_floats);
#endif

   return 0;
}
Example #26
0
static int
getisample(double sampleno, float *c, int input)
{

	ssize_t RECSIZE = bufsize[input];
	ssize_t BPREC = RECSIZE * sizeof(short);
	ssize_t BPFRAME = sfchans(&sfdesc[input]) * sizeof(short);
	ssize_t FPREC = RECSIZE/sfchans(&sfdesc[input]);

	int sample,i,j;
    ssize_t nbytes;
	signed short *array = (short *)sndbuf[input];
	float tempsample1;
	float tempsample2;
	float fraction;
	static int oldsample = 0;
	static int endsample = 0;

	sample = (int)sampleno;
	fraction = sampleno - (double)sample;
	if(!((sample >= oldsample) && (sample < endsample))) {
		/* sflseek (sfheader.h) assumes header size, so can't use it */
		if(lseek(sfd[input], (sample * BPFRAME) + headersize[input],
							SEEK_SET) <= 0) {
			rterror(NULL, "badlseek on inputfile\n");
			closesf();
		}
		nbytes = read(sfd[input], (char *)array, BPREC);
		if (nbytes == -1) {
			perror("getisample: read");
			return 0;
		}
		if (nbytes == 0) {
			rterror(NULL, "reached eof on input file\n");
			return 0;
		}
		if (nbytes < BPREC) {    /* zero out rest of sndbuf */
			ssize_t n;
			for (n = nbytes; n < BPREC; n++)
				sndbuf[input][n] = 0;
		}
		oldsample = sample;
		endsample = oldsample + FPREC - 1;
		}
	for(i=(sample-oldsample)*sfchans(&sfdesc[input]),j=0; 
	    j<sfchans(&sfdesc[input]); i++,j++)  {
	  
	  if (swap_bytes[input]) {
	    tempsample1 = (signed short)reverse_int2(array+i);
	    tempsample2 = (signed short)reverse_int2(array+i+sfchans(&sfdesc[input]));
	    *(c+j) = tempsample1 + fraction * 
	      ((float)((signed short)tempsample2 - tempsample1));
	  }
	  else {
	    *(c+j) = (float)*(array+i) + fraction * 
	      ((float) *(array+i+sfchans(&sfdesc[input])) - 
	       (float) *(array+i));
	  }
	}
	return(1);

}
Example #27
0
/**
 * n-raster iterator.
 * The raster returned should be freed by the caller
 *
 * @param itrset : set of rt_iterator objects.
 * @param itrcount : number of objects in itrset.
 * @param extenttype : type of extent for the output raster.
 * @param customextent : raster specifying custom extent.
 * is only used if extenttype is ET_CUSTOM.
 * @param pixtype : the desired pixel type of the output raster's band.
 * @param hasnodata : indicates if the band has nodata value
 * @param nodataval : the nodata value, will be appropriately
 * truncated to fit the pixtype size.
 * @param distancex : the number of pixels around the specified pixel
 * along the X axis
 * @param distancey : the number of pixels around the specified pixel
 * along the Y axis
 * @param mask : the object of mask
 * @param userarg : pointer to any argument that is passed as-is to callback.
 * @param callback : callback function for actual processing of pixel values.
 * @param *rtnraster : return one band raster from iterator process
 *
 * The callback function _must_ have the following signature.
 *
 *    int FNAME(rt_iterator_arg arg, void *userarg, double *value, int *nodata)
 *
 * The callback function _must_ return zero (error) or non-zero (success)
 * indicating whether the function ran successfully.
 * The parameters passed to the callback function are as follows.
 *
 * - rt_iterator_arg arg: struct containing pixel values, NODATA flags and metadata
 * - void *userarg: NULL or calling function provides to rt_raster_iterator() for use by callback function
 * - double *value: value of pixel to be burned by rt_raster_iterator()
 * - int *nodata: flag (0 or 1) indicating that pixel to be burned is NODATA
 *
 * @return ES_NONE on success, ES_ERROR on error
 */
rt_errorstate
rt_raster_iterator(
	rt_iterator itrset, uint16_t itrcount,
	rt_extenttype extenttype, rt_raster customextent,
	rt_pixtype pixtype,
	uint8_t hasnodata, double nodataval,
	uint16_t distancex, uint16_t distancey,
	rt_mask mask,
	void *userarg,
	int (*callback)(
		rt_iterator_arg arg,
		void *userarg,
		double *value,
		int *nodata
	),
	rt_raster *rtnraster
) {
	/* output raster */
	rt_raster rtnrast = NULL;
	/* output raster's band */
	rt_band rtnband = NULL;

	/* working raster */
	rt_raster rast = NULL;

	_rti_iterator_arg _param = NULL;
	int allnull = 0;
	int allempty = 0;
	int aligned = 0;
	double offset[4] = {0.};
	rt_pixel npixels;

	int i = 0;
	int status = 0;
	int inextent = 0;
	int x = 0;
	int y = 0;
	int _x = 0;
	int _y = 0;

	int _width = 0;
	int _height = 0;

	double minval;
	double value;
	int isnodata;
	int nodata;

	RASTER_DEBUG(3, "Starting...");

	assert(itrset != NULL && itrcount > 0);
	assert(rtnraster != NULL);

	/* init rtnraster to NULL */
	*rtnraster = NULL;

	/* check that callback function is not NULL */
	if (callback == NULL) {
		rterror("rt_raster_iterator: Callback function not provided");
		return ES_ERROR;
	}

	/* check that custom extent is provided if extenttype = ET_CUSTOM */
	if (extenttype == ET_CUSTOM && rt_raster_is_empty(customextent)) {
		rterror("rt_raster_iterator: Custom extent cannot be empty if extent type is ET_CUSTOM");
		return ES_ERROR;
	}

	/* check that pixtype != PT_END */
	if (pixtype == PT_END) {
		rterror("rt_raster_iterator: Pixel type cannot be PT_END");
		return ES_ERROR;
	}

	/* initialize _param */
	if ((_param = _rti_iterator_arg_init()) == NULL) {
		rterror("rt_raster_iterator: Could not initialize internal variables");
		return ES_ERROR;
	}

	/* fill _param */
	if (!_rti_iterator_arg_populate(_param, itrset, itrcount, distancex, distancey, &allnull, &allempty)) {
		rterror("rt_raster_iterator: Could not populate for internal variables");
		_rti_iterator_arg_destroy(_param);
		return ES_ERROR;
	}

	/* shortcut if all null, return NULL */
	if (allnull == itrcount) {
		RASTER_DEBUG(3, "all rasters are NULL, returning NULL");

		_rti_iterator_arg_destroy(_param);

		return ES_NONE;
	}
	/* shortcut if all empty, return empty raster */
	else if (allempty == itrcount) {
		RASTER_DEBUG(3, "all rasters are empty, returning empty raster");

		_rti_iterator_arg_destroy(_param);

		rtnrast = rt_raster_new(0, 0);
		if (rtnrast == NULL) {
			rterror("rt_raster_iterator: Could not create empty raster");
			return ES_ERROR;
		}
		rt_raster_set_scale(rtnrast, 0, 0);

		*rtnraster = rtnrast;
		return ES_NONE;
	}

	/* check that all rasters are aligned */
	RASTER_DEBUG(3, "checking alignment of all rasters");
	rast = NULL;

	/* find raster to use as reference */
	/* use custom if provided */
	if (extenttype == ET_CUSTOM) {
		RASTER_DEBUG(4, "using custom extent as reference raster");
		rast = customextent;
	}
	/* use first valid one in _param->raster */
	else {
		for (i = 0; i < itrcount; i++) {
			if (!_param->isempty[i]) {
				RASTER_DEBUGF(4, "using raster at index %d as reference raster", i);
				rast = _param->raster[i];
				break;
			}
		}
	}

	/* no rasters found, SHOULD NEVER BE HERE! */
	if (rast == NULL) {
		rterror("rt_raster_iterator: Could not find reference raster to use for alignment tests");

		_rti_iterator_arg_destroy(_param);

		return ES_ERROR;
	}

	do {
		aligned = 1;

		/* check custom first if set. also skip if rasters are the same */
		if (extenttype == ET_CUSTOM && rast != customextent) {
			if (rt_raster_same_alignment(rast, customextent, &aligned, NULL) != ES_NONE) {
				rterror("rt_raster_iterator: Could not test for alignment between reference raster and custom extent");

				_rti_iterator_arg_destroy(_param);

				return ES_ERROR;
			}

			RASTER_DEBUGF(5, "custom extent alignment: %d", aligned);
			if (!aligned)
				break;
		}

		for (i = 0; i < itrcount; i++) {
			/* skip NULL rasters and if rasters are the same */
			if (_param->isempty[i] || rast == _param->raster[i])
				continue;

			if (rt_raster_same_alignment(rast, _param->raster[i], &aligned, NULL) != ES_NONE) {
				rterror("rt_raster_iterator: Could not test for alignment between reference raster and raster %d", i);

				_rti_iterator_arg_destroy(_param);

				return ES_ERROR;
			}
			RASTER_DEBUGF(5, "raster at index %d alignment: %d", i, aligned);

			/* abort checking since a raster isn't aligned */
			if (!aligned)
				break;
		}
	}
	while (0);

	/* not aligned, error */
	if (!aligned) {
		rterror("rt_raster_iterator: The set of rasters provided (custom extent included, if appropriate) do not have the same alignment");

		_rti_iterator_arg_destroy(_param);

		return ES_ERROR;
	}

	/* use extenttype to build output raster (no bands though) */
	i = -1;
	switch (extenttype) {
		case ET_INTERSECTION:
		case ET_UNION:
			/* make copy of first "real" raster */
			rtnrast = rtalloc(sizeof(struct rt_raster_t));
			if (rtnrast == NULL) {
				rterror("rt_raster_iterator: Could not allocate memory for output raster");

				_rti_iterator_arg_destroy(_param);

				return ES_ERROR;
			}

			for (i = 0; i < itrcount; i++) {
				if (!_param->isempty[i]) {
					memcpy(rtnrast, _param->raster[i], sizeof(struct rt_raster_serialized_t));
					break;
				}
			}
			rtnrast->numBands = 0;
			rtnrast->bands = NULL;

			/* get extent of output raster */
			rast = NULL;
			for (i = i + 1; i < itrcount; i++) {
				if (_param->isempty[i])
					continue;

				status = rt_raster_from_two_rasters(rtnrast, _param->raster[i], extenttype, &rast, NULL);
				rtdealloc(rtnrast);

				if (rast == NULL || status != ES_NONE) {
					rterror("rt_raster_iterator: Could not compute %s extent of rasters",
						extenttype == ET_UNION ? "union" : "intersection"
					);

					_rti_iterator_arg_destroy(_param);

					return ES_ERROR;
				}
				else if (rt_raster_is_empty(rast)) {
					rtinfo("rt_raster_iterator: Computed raster for %s extent is empty",
						extenttype == ET_UNION ? "union" : "intersection"
					);

					_rti_iterator_arg_destroy(_param);

					*rtnraster = rast;
					return ES_NONE;
				}

				rtnrast = rast;
				rast = NULL;
			}

			break;
		/*
			first, second and last have similar checks
			and continue into custom
		*/
		case ET_FIRST:
			i = 0;
		case ET_SECOND:
			if (i < 0) {
				if (itrcount < 2)
					i = 0;
				else
					i = 1;
			}
		case ET_LAST:
			if (i < 0) i = itrcount - 1;
			
			/* input raster is null, return NULL */
			if (_param->raster[i] == NULL) {
				RASTER_DEBUGF(3, "returning NULL as %s raster is NULL and extent type is ET_%s",
					(i == 0 ? "first" : (i == 1 ? "second" : "last")),
					(i == 0 ? "FIRST" : (i == 1 ? "SECOND" : "LAST"))
				);

				_rti_iterator_arg_destroy(_param);

				return ES_NONE;
			}
			/* input raster is empty, return empty raster */
			else if (_param->isempty[i]) {
				RASTER_DEBUGF(3, "returning empty raster as %s raster is empty and extent type is ET_%s",
					(i == 0 ? "first" : (i == 1 ? "second" : "last")),
					(i == 0 ? "FIRST" : (i == 1 ? "SECOND" : "LAST"))
				);

				_rti_iterator_arg_destroy(_param);

				rtnrast = rt_raster_new(0, 0);
				if (rtnrast == NULL) {
					rterror("rt_raster_iterator: Could not create empty raster");
					return ES_ERROR;
				}
				rt_raster_set_scale(rtnrast, 0, 0);

				*rtnraster = rtnrast;
				return ES_NONE;
			}
		/* copy the custom extent raster */
		case ET_CUSTOM:
			rtnrast = rtalloc(sizeof(struct rt_raster_t));
			if (rtnrast == NULL) {
				rterror("rt_raster_iterator: Could not allocate memory for output raster");

				_rti_iterator_arg_destroy(_param);

				return ES_ERROR;
			}

			switch (extenttype) {
				case ET_CUSTOM:
					memcpy(rtnrast, customextent, sizeof(struct rt_raster_serialized_t));
					break;
				/* first, second, last */
				default:
					memcpy(rtnrast, _param->raster[i], sizeof(struct rt_raster_serialized_t));
					break;
			}
			rtnrast->numBands = 0;
			rtnrast->bands = NULL;
			break;
	}

	_width = rt_raster_get_width(rtnrast);
	_height = rt_raster_get_height(rtnrast);

	RASTER_DEBUGF(4, "rtnrast (width, height, ulx, uly, scalex, scaley, skewx, skewy, srid) = (%d, %d, %f, %f, %f, %f, %f, %f, %d)",
		_width,
		_height,
		rt_raster_get_x_offset(rtnrast),
		rt_raster_get_y_offset(rtnrast),
		rt_raster_get_x_scale(rtnrast),
		rt_raster_get_y_scale(rtnrast),
		rt_raster_get_x_skew(rtnrast),
		rt_raster_get_y_skew(rtnrast),
		rt_raster_get_srid(rtnrast)
	);

	/* init values and NODATA for use with empty rasters */
	if (!_rti_iterator_arg_empty_init(_param)) {
		rterror("rt_raster_iterator: Could not initialize empty values and NODATA");

		_rti_iterator_arg_destroy(_param);
		rt_raster_destroy(rtnrast);
		
		return ES_ERROR;
	}

	/* create output band */
	if (rt_raster_generate_new_band(
		rtnrast,
		pixtype,
		nodataval,
		hasnodata, nodataval,
		0
	) < 0) {
		rterror("rt_raster_iterator: Could not add new band to output raster");

		_rti_iterator_arg_destroy(_param);
		rt_raster_destroy(rtnrast);

		return ES_ERROR;
	}

	/* get output band */
	rtnband = rt_raster_get_band(rtnrast, 0);
	if (rtnband == NULL) {
		rterror("rt_raster_iterator: Could not get new band from output raster");

		_rti_iterator_arg_destroy(_param);
		rt_raster_destroy(rtnrast);

		return ES_ERROR;
	}

	/* output band's minimum value */
	minval = rt_band_get_min_value(rtnband);

	/* initialize argument for callback function */
	if (!_rti_iterator_arg_callback_init(_param)) {
		rterror("rt_raster_iterator: Could not initialize callback function argument");

		_rti_iterator_arg_destroy(_param);
		rt_band_destroy(rtnband);
		rt_raster_destroy(rtnrast);

		return ES_ERROR;
	}

	/* fill _param->offset */
	for (i = 0; i < itrcount; i++) {
		if (_param->isempty[i])
			continue;

		status = rt_raster_from_two_rasters(rtnrast, _param->raster[i], ET_FIRST, &rast, offset);
		rtdealloc(rast);
		if (status != ES_NONE) {
			rterror("rt_raster_iterator: Could not compute raster offsets");

			_rti_iterator_arg_destroy(_param);
			rt_band_destroy(rtnband);
			rt_raster_destroy(rtnrast);

			return ES_ERROR;
		}

		_param->offset[i][0] = offset[2];
		_param->offset[i][1] = offset[3];
		RASTER_DEBUGF(4, "rast %d offset: %f %f", i, offset[2], offset[3]);
	}

	/* loop over each pixel (POI) of output raster */
	/* _x,_y are for output raster */
	/* x,y are for input raster */
	for (_y = 0; _y < _height; _y++) {
		for (_x = 0; _x < _width; _x++) {
			RASTER_DEBUGF(4, "iterating output pixel (x, y) = (%d, %d)", _x, _y);
			_param->arg->dst_pixel[0] = _x;
			_param->arg->dst_pixel[1] = _y;

			/* loop through each input raster */
			for (i = 0; i < itrcount; i++) {
				RASTER_DEBUGF(4, "raster %d", i);

				/*
					empty raster
					OR band does not exist and flag set to use NODATA
					OR band is NODATA
				*/
				if (
					_param->isempty[i] ||
					(_param->band.rtband[i] == NULL && itrset[i].nbnodata) ||
					_param->band.isnodata[i]
				) {
					RASTER_DEBUG(4, "empty raster, band does not exist or band is NODATA. using empty values and NODATA");
					
					x = _x;
					y = _y;

					_param->arg->values[i] = _param->empty.values;
					_param->arg->nodata[i] = _param->empty.nodata;

					continue;
				}

				/* input raster's X,Y */
				x = _x - (int) _param->offset[i][0];
				y = _y - (int) _param->offset[i][1];
				RASTER_DEBUGF(4, "source pixel (x, y) = (%d, %d)", x, y);

				_param->arg->src_pixel[i][0] = x;
				_param->arg->src_pixel[i][1] = y;

				/* neighborhood */
				npixels = NULL;
				status = 0;
				if (distancex > 0 && distancey > 0) {
					RASTER_DEBUG(4, "getting neighborhood");

					status = rt_band_get_nearest_pixel(
						_param->band.rtband[i],
						x, y,
						distancex, distancey,
						1,
						&npixels
					);
					if (status < 0) {
						rterror("rt_raster_iterator: Could not get pixel neighborhood");

						_rti_iterator_arg_destroy(_param);
						rt_band_destroy(rtnband);
						rt_raster_destroy(rtnrast);

						return ES_ERROR;
					}
				}

				/* get value of POI */
				/* get pixel's value */
				if (
					(x >= 0 && x < _param->width[i]) &&
					(y >= 0 && y < _param->height[i])
				) {
					RASTER_DEBUG(4, "getting value of POI");
					if (rt_band_get_pixel(
						_param->band.rtband[i],
						x, y,
						&value,
						&isnodata
					) != ES_NONE) {
						rterror("rt_raster_iterator: Could not get the pixel value of band");

						_rti_iterator_arg_destroy(_param);
						rt_band_destroy(rtnband);
						rt_raster_destroy(rtnrast);

						return ES_ERROR;
					}
					inextent = 1;
				}
				/* outside band extent, set to NODATA */
				else {
					RASTER_DEBUG(4, "Outside band extent, setting value to NODATA");
					/* has NODATA, use NODATA */
					if (_param->band.hasnodata[i])
						value = _param->band.nodataval[i];
					/* no NODATA, use min possible value */
					else
						value = _param->band.minval[i];

					inextent = 0;
					isnodata = 1;
				}

				/* add pixel to neighborhood */
				status++;
				if (status > 1)
					npixels = (rt_pixel) rtrealloc(npixels, sizeof(struct rt_pixel_t) * status);
				else
					npixels = (rt_pixel) rtalloc(sizeof(struct rt_pixel_t));

				if (npixels == NULL) {
					rterror("rt_raster_iterator: Could not reallocate memory for neighborhood");

					_rti_iterator_arg_destroy(_param);
					rt_band_destroy(rtnband);
					rt_raster_destroy(rtnrast);

					return ES_ERROR;
				}

				npixels[status - 1].x = x;
				npixels[status - 1].y = y;
				npixels[status - 1].nodata = 1;
				npixels[status - 1].value = value;

				/* set nodata flag */
				if ((!_param->band.hasnodata[i] && inextent) || !isnodata) {
					npixels[status - 1].nodata = 0;
				}
				RASTER_DEBUGF(4, "value, nodata: %f, %d", value, npixels[status - 1].nodata);

				/* convert set of rt_pixel to 2D array */
				status = rt_pixel_set_to_array(
					npixels, status,mask,
					x, y,
					distancex, distancey,
					&(_param->arg->values[i]),
					&(_param->arg->nodata[i]),
					NULL, NULL
				);
				rtdealloc(npixels);
				if (status != ES_NONE) {
					rterror("rt_raster_iterator: Could not create 2D array of neighborhood");

					_rti_iterator_arg_destroy(_param);
					rt_band_destroy(rtnband);
					rt_raster_destroy(rtnrast);

					return ES_ERROR;
				}
			}
	
			/* callback */
			RASTER_DEBUG(4, "calling callback function");
			value = 0;
			nodata = 0;
			status = callback(_param->arg, userarg, &value, &nodata);

			/* free memory from callback */
			_rti_iterator_arg_callback_clean(_param);

			/* handle callback status */
			if (status == 0) {
				rterror("rt_raster_iterator: Callback function returned an error");

				_rti_iterator_arg_destroy(_param);
				rt_band_destroy(rtnband);
				rt_raster_destroy(rtnrast);

				return ES_ERROR;
			}

			/* burn value to pixel */
			status = 0;
			if (!nodata) {
				status = rt_band_set_pixel(rtnband, _x, _y, value, NULL);
				RASTER_DEBUGF(4, "burning pixel (%d, %d) with value: %f", _x, _y, value);
			}
			else if (!hasnodata) {
				status = rt_band_set_pixel(rtnband, _x, _y, minval, NULL);
				RASTER_DEBUGF(4, "burning pixel (%d, %d) with minval: %f", _x, _y, minval);
			}
			else {
				RASTER_DEBUGF(4, "NOT burning pixel (%d, %d)", _x, _y);
			}
			if (status != ES_NONE) {
				rterror("rt_raster_iterator: Could not set pixel value");

				_rti_iterator_arg_destroy(_param);
				rt_band_destroy(rtnband);
				rt_raster_destroy(rtnrast);

				return ES_ERROR;
			}
		}
	}

	/* lots of cleanup */
	_rti_iterator_arg_destroy(_param);

	*rtnraster = rtnrast;
	return ES_NONE;
}
Example #28
0
static int
_rti_iterator_arg_populate(
	_rti_iterator_arg _param,
	rt_iterator itrset, uint16_t itrcount,
	uint16_t distancex, uint16_t distancey,
	int *allnull, int *allempty
) {
	int i = 0;
	int hasband = 0;

	_param->count = itrcount;
	_param->distance.x = distancex;
	_param->distance.y = distancey;
	_param->dimension.columns = distancex * 2 + 1;
	_param->dimension.rows = distancey * 2 + 1;

	/* allocate memory for children */
	_param->raster = rtalloc(sizeof(rt_raster) * itrcount);
	_param->isempty = rtalloc(sizeof(int) * itrcount);
	_param->width = rtalloc(sizeof(int) * itrcount);
	_param->height = rtalloc(sizeof(int) * itrcount);

	_param->offset = rtalloc(sizeof(double *) * itrcount);

	_param->band.rtband = rtalloc(sizeof(rt_band) * itrcount);
	_param->band.hasnodata = rtalloc(sizeof(int) * itrcount);
	_param->band.isnodata = rtalloc(sizeof(int) * itrcount);
	_param->band.nodataval = rtalloc(sizeof(double) * itrcount);
	_param->band.minval = rtalloc(sizeof(double) * itrcount);

	if (
		_param->raster == NULL ||
		_param->isempty == NULL ||
		_param->width == NULL ||
		_param->height == NULL ||
		_param->offset == NULL ||
		_param->band.rtband == NULL ||
		_param->band.hasnodata == NULL ||
		_param->band.isnodata == NULL ||
		_param->band.nodataval == NULL ||
		_param->band.minval == NULL
	) {
		rterror("_rti_iterator_arg_populate: Could not allocate memory for children of _rti_iterator_arg");
		return 0;
	}

	*allnull = 0;
	*allempty = 0;

	/*
		check input rasters
			not empty, band # is valid
			copy raster pointers and set flags
	*/
	for (i = 0; i < itrcount; i++) {
		/* initialize elements */
		_param->raster[i] = NULL;
		_param->isempty[i] = 0;
		_param->width[i] = 0;
		_param->height[i] = 0;

		_param->offset[i] = NULL;

		_param->band.rtband[i] = NULL;
		_param->band.hasnodata[i] = 0;
		_param->band.isnodata[i] = 0;
		_param->band.nodataval[i] = 0;
		_param->band.minval[i] = 0;

		/* set isempty */
		if (itrset[i].raster == NULL) {
			_param->isempty[i] = 1;

			(*allnull)++;
			(*allempty)++;

			continue;
		}
		else if (rt_raster_is_empty(itrset[i].raster)) {
			_param->isempty[i] = 1;

			(*allempty)++;

			continue;
		}

		/* check band number */
		hasband = rt_raster_has_band(itrset[i].raster, itrset[i].nband);
		if (!hasband) {
			if (!itrset[i].nbnodata) {
				rterror("_rti_iterator_arg_populate: Band %d not found for raster %d", itrset[i].nband, i);
				return 0;
			}
			else {
				RASTER_DEBUGF(4, "Band %d not found for raster %d. Using NODATA", itrset[i].nband, i);
			}
		}

		_param->raster[i] = itrset[i].raster;
		if (hasband) {
			_param->band.rtband[i] = rt_raster_get_band(itrset[i].raster, itrset[i].nband);
			if (_param->band.rtband[i] == NULL) {
				rterror("_rti_iterator_arg_populate: Could not get band %d for raster %d", itrset[i].nband, i);
				return 0;
			}

			/* hasnodata */
			_param->band.hasnodata[i] = rt_band_get_hasnodata_flag(_param->band.rtband[i]);

			/* hasnodata = TRUE */
			if (_param->band.hasnodata[i]) {
				/* nodataval */
				rt_band_get_nodata(_param->band.rtband[i], &(_param->band.nodataval[i]));

				/* isnodata */
				_param->band.isnodata[i] = rt_band_get_isnodata_flag(_param->band.rtband[i]);
			}
			/* hasnodata = FALSE */
			else {
				/* minval */
				_param->band.minval[i] = rt_band_get_min_value(_param->band.rtband[i]);
			}
		}

		/* width, height */
		_param->width[i] = rt_raster_get_width(_param->raster[i]);
		_param->height[i] = rt_raster_get_height(_param->raster[i]);

		/* init offset */
		_param->offset[i] = rtalloc(sizeof(double) * 2);
		if (_param->offset[i] == NULL) {
			rterror("_rti_iterator_arg_populate: Could not allocate memory for offsets");
			return 0;
		}
	}

	return 1;
}
Example #29
0
  /**
   * For Lua instruments, the run method also performs the Lua 
   * portion of the init method. That is because the init 
   * method is called from the main RTcmix thread whereas the 
   * run method is called from the traverse thread, but Lua 
   * is not thread-safe and our Lua state management code
   * creates a separate Lua state for each thread.
   */
  virtual int run()
  {
    //advise("LUAINST::run", "Began (thread %p)...", pthread_self());
    int result = 0;
    if (state.parameters[2] != 0.0) 
      {
	state.inputSampleCount = RTBUFSAMPS * inputChannels();
	rtgetin(state.input, this, state.inputSampleCount);
      }
    lua_State *L = manageLuaState();
    LuaInstrumentClass_t &luaInstrumentClass = manageLuaInstrumentClass(L, state.name);
    if (!luaInstrumentClass.initialized) 
      {
	const char *luacode = luaCodeForInstrumentNames[state.name].c_str();
	advise("LUAINST", "Defining Lua instrument code:\n\n%0.120s\n...\n", luacode);
	result = luaL_dostring(L, luacode);
	if (result == 0)
	  {
	    char init_function[0x100];
	    std::snprintf(init_function, 0x100, "%s_init", state.name);
	    lua_getglobal(L, init_function);
	    if (!lua_isnil(L, 1))
	      {
		luaInstrumentClass.init_key = luaL_ref(L, LUA_REGISTRYINDEX);
		lua_pop(L, 1);
	      }
	    else
	      {
		exit(die("LUAINST", "Failed to register: %s.", init_function));
	      }
	    char run_function[0x100];
	    std::snprintf(run_function, 0x100, "%s_run", state.name);
	    lua_getglobal(L, run_function);
	    if (!lua_isnil(L, 1))
	      {
		luaInstrumentClass.run_key = luaL_ref(L, LUA_REGISTRYINDEX);
		lua_pop(L, 1);
	      }
	    else
	      {
		exit(die("LUAINST", "Failed to register: %s.", run_function));
	      }
	  }
	else
	  {
	    warn("LUAINST", "Failed with: %d\n", result);
	  }
	luaInstrumentClass.initialized = true;
      }
    if (!state.initialized) 
      {
	lua_rawgeti(L, LUA_REGISTRYINDEX, luaInstrumentClass.init_key);
	lua_pushlightuserdata(L, &state);
	if (lua_pcall(L, 1, 1, 0) != 0)
	  {
	    rterror("LUAINST", "Lua error in \"%s_init\": %s.\n", state.name, lua_tostring(L, -1));
	  }
	result = lua_tonumber(L, -1);
	lua_pop(L, 1);
	state.initialized = true;
      }
    state.startFrame = state.endFrame;
    long frameCount = framesToRun();
    state.endFrame += frameCount;
    doupdate();
    lua_rawgeti(L, LUA_REGISTRYINDEX, luaInstrumentClass.run_key);
    lua_pushlightuserdata(L, &state);
    if (lua_pcall(L, 1, 1, 0) != 0)
      {
	die("LUAINST", "Lua error in \"%s_run\": %s with key %p frame %i.\n", state.name, lua_tostring(L, -1), luaInstrumentClass.run_key, state.currentFrame);
	exit(-1);
      }
    result = lua_tonumber(L, -1);
    lua_pop(L, 1);
    rtbaddout(state.output, frameCount);
    increment(frameCount);
    return framesToRun();
  }
Example #30
0
/**
 * Returns new band with values reclassified
 *
 * @param srcband : the band who's values will be reclassified
 * @param pixtype : pixel type of the new band
 * @param hasnodata : indicates if the band has a nodata value
 * @param nodataval : nodata value for the new band
 * @param exprset : array of rt_reclassexpr structs
 * @param exprcount : number of elements in expr
 *
 * @return a new rt_band or NULL on error
 */
rt_band
rt_band_reclass(
	rt_band srcband, rt_pixtype pixtype,
	uint32_t hasnodata, double nodataval,
	rt_reclassexpr *exprset, int exprcount
) {
	rt_band band = NULL;
	uint32_t width = 0;
	uint32_t height = 0;
	int numval = 0;
	int memsize = 0;
	void *mem = NULL;
	uint32_t src_hasnodata = 0;
	double src_nodataval = 0.0;
	int isnodata = 0;

	int rtn;
	uint32_t x;
	uint32_t y;
	int i;
	double or = 0;
	double ov = 0;
	double nr = 0;
	double nv = 0;
	int do_nv = 0;
	rt_reclassexpr expr = NULL;

	assert(NULL != srcband);
	assert(NULL != exprset && exprcount > 0);
	RASTER_DEBUGF(4, "exprcount = %d", exprcount);
	RASTER_DEBUGF(4, "exprset @ %p", exprset);

	/* source nodata */
	src_hasnodata = rt_band_get_hasnodata_flag(srcband);
	if (src_hasnodata)
		rt_band_get_nodata(srcband, &src_nodataval);

	/* size of memory block to allocate */
	width = rt_band_get_width(srcband);
	height = rt_band_get_height(srcband);
	numval = width * height;
	memsize = rt_pixtype_size(pixtype) * numval;
	mem = (int *) rtalloc(memsize);
	if (!mem) {
		rterror("rt_band_reclass: Could not allocate memory for band");
		return 0;
	}

	/* initialize to zero */
	if (!hasnodata) {
		memset(mem, 0, memsize);
	}
	/* initialize to nodataval */
	else {
		int32_t checkvalint = 0;
		uint32_t checkvaluint = 0;
		double checkvaldouble = 0;
		float checkvalfloat = 0;

		switch (pixtype) {
			case PT_1BB:
			{
				uint8_t *ptr = mem;
				uint8_t clamped_initval = rt_util_clamp_to_1BB(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_2BUI:
			{
				uint8_t *ptr = mem;
				uint8_t clamped_initval = rt_util_clamp_to_2BUI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_4BUI:
			{
				uint8_t *ptr = mem;
				uint8_t clamped_initval = rt_util_clamp_to_4BUI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_8BSI:
			{
				int8_t *ptr = mem;
				int8_t clamped_initval = rt_util_clamp_to_8BSI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_8BUI:
			{
				uint8_t *ptr = mem;
				uint8_t clamped_initval = rt_util_clamp_to_8BUI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_16BSI:
			{
				int16_t *ptr = mem;
				int16_t clamped_initval = rt_util_clamp_to_16BSI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_16BUI:
			{
				uint16_t *ptr = mem;
				uint16_t clamped_initval = rt_util_clamp_to_16BUI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_32BSI:
			{
				int32_t *ptr = mem;
				int32_t clamped_initval = rt_util_clamp_to_32BSI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalint = ptr[0];
				break;
			}
			case PT_32BUI:
			{
				uint32_t *ptr = mem;
				uint32_t clamped_initval = rt_util_clamp_to_32BUI(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvaluint = ptr[0];
				break;
			}
			case PT_32BF:
			{
				float *ptr = mem;
				float clamped_initval = rt_util_clamp_to_32F(nodataval);
				for (i = 0; i < numval; i++)
					ptr[i] = clamped_initval;
				checkvalfloat = ptr[0];
				break;
			}
			case PT_64BF:
			{
				double *ptr = mem;
				for (i = 0; i < numval; i++)
					ptr[i] = nodataval;
				checkvaldouble = ptr[0];
				break;
			}
			default:
			{
				rterror("rt_band_reclass: Unknown pixeltype %d", pixtype);
				rtdealloc(mem);
				return 0;
			}
		}

		/* Overflow checking */
		rt_util_dbl_trunc_warning(
			nodataval,
			checkvalint, checkvaluint,
			checkvalfloat, checkvaldouble,
			pixtype
		);
	}
	RASTER_DEBUGF(3, "rt_band_reclass: width = %d height = %d", width, height);

	band = rt_band_new_inline(width, height, pixtype, hasnodata, nodataval, mem);
	if (!band) {
		rterror("rt_band_reclass: Could not create new band");
		rtdealloc(mem);
		return 0;
	}
	rt_band_set_ownsdata_flag(band, 1); /* we DO own this data!!! */
	RASTER_DEBUGF(3, "rt_band_reclass: new band @ %p", band);

	for (x = 0; x < width; x++) {
		for (y = 0; y < height; y++) {
			rtn = rt_band_get_pixel(srcband, x, y, &ov, &isnodata);

			/* error getting value, skip */
			if (rtn != ES_NONE) {
				RASTER_DEBUGF(3, "Cannot get value at %d, %d", x, y);
				continue;
			}
			RASTER_DEBUGF(4, "(x, y, ov, isnodata) = (%d, %d, %f, %d)", x, y, ov, isnodata);

			do {
				do_nv = 0;

				/* no data*/
				if (hasnodata && isnodata) {
					do_nv = 1;
					break;
				}

				for (i = 0; i < exprcount; i++) {
					expr = exprset[i];

					/* ov matches min and max*/
					if (
						FLT_EQ(expr->src.min, ov) &&
						FLT_EQ(expr->src.max, ov)
					) {
						do_nv = 1;
						break;
					}

					/* process min */
					if ((
						expr->src.exc_min && (
							expr->src.min > ov ||
							FLT_EQ(expr->src.min, ov)
						)) || (
						expr->src.inc_min && (
							expr->src.min < ov ||
							FLT_EQ(expr->src.min, ov)
						)) || (
						expr->src.min < ov
					)) {
						/* process max */
						if ((
							expr->src.exc_max && (
								ov > expr->src.max ||
								FLT_EQ(expr->src.max, ov)
							)) || (
								expr->src.inc_max && (
								ov < expr->src.max ||
								FLT_EQ(expr->src.max, ov)
							)) || (
							ov < expr->src.max
						)) {
							do_nv = 1;
							break;
						}
					}
				}
			}
			while (0);

			/* no expression matched, do not continue */
			if (!do_nv) continue;
			RASTER_DEBUGF(3, "Using exprset[%d] unless NODATA", i);

			/* converting a value from one range to another range
			OldRange = (OldMax - OldMin)
			NewRange = (NewMax - NewMin)
			NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
			*/

			/* NODATA */
			if (hasnodata && isnodata) {
				nv = nodataval;
			}
			/*
				"src" min and max is the same, prevent division by zero
				set nv to "dst" min, which should be the same as "dst" max
			*/
			else if (FLT_EQ(expr->src.max, expr->src.min)) {
				nv = expr->dst.min;
			}
			else {
				or = expr->src.max - expr->src.min;
				nr = expr->dst.max - expr->dst.min;
				nv = (((ov - expr->src.min) * nr) / or) + expr->dst.min;

				/* if dst range is from high to low */
				if (expr->dst.min > expr->dst.max) {
					if (nv > expr->dst.min)
						nv = expr->dst.min;
					else if (nv < expr->dst.max)
						nv = expr->dst.max;
				}
				/* if dst range is from low to high */
				else {
					if (nv < expr->dst.min)
						nv = expr->dst.min;
					else if (nv > expr->dst.max)
						nv = expr->dst.max;
				}
			}

			/* round the value for integers */
			switch (pixtype) {
				case PT_1BB:
				case PT_2BUI:
				case PT_4BUI:
				case PT_8BSI:
				case PT_8BUI:
				case PT_16BSI:
				case PT_16BUI:
				case PT_32BSI:
				case PT_32BUI:
					nv = round(nv);
					break;
				default:
					break;
			}

			RASTER_DEBUGF(4, "(%d, %d) ov: %f or: %f - %f nr: %f - %f nv: %f"
				, x
				, y
				, ov
				, (NULL != expr) ? expr->src.min : 0
				, (NULL != expr) ? expr->src.max : 0
				, (NULL != expr) ? expr->dst.min : 0
				, (NULL != expr) ? expr->dst.max : 0
				, nv
			);
			if (rt_band_set_pixel(band, x, y, nv, NULL) != ES_NONE) {
				rterror("rt_band_reclass: Could not assign value to new band");
				rt_band_destroy(band);
				rtdealloc(mem);
				return 0;
			}

			expr = NULL;
		}
	}

	return band;
}