// Methods bound to input/inlets
t_jit_err jit_pcl_voxel_matrix_calc(t_jit_pcl_voxel *x, void *inputs, void *outputs)
{
    t_jit_err			err = JIT_ERR_NONE;
    long				in_savelock;
    long				out_savelock;
    t_jit_matrix_info	in_minfo;
    t_jit_matrix_info	out_minfo;
    char				*in_bp;
    char				*out_bp;
    long				i, j;
    long				dimcount;
    long				planecount;
    long				dim[JIT_MATRIX_MAX_DIMCOUNT];
    void				*in_matrix;
    void				*out_matrix;
    
    long rowstride;
    char *fip;
    float *fop;
    
    
    in_matrix 	= jit_object_method(inputs,_jit_sym_getindex,0);
    out_matrix 	= jit_object_method(outputs,_jit_sym_getindex,0);
    
    if (x && in_matrix && out_matrix)
    {
        in_savelock = (long) jit_object_method(in_matrix, _jit_sym_lock, 1);
        out_savelock = (long) jit_object_method(out_matrix, _jit_sym_lock, 1);
        
        jit_object_method(in_matrix, _jit_sym_getinfo, &in_minfo);
        jit_object_method(in_matrix, _jit_sym_getdata, &in_bp);
        
        if (!in_bp) {
            err=JIT_ERR_INVALID_INPUT;
            goto out;
        }
        
        //get dimensions/planecount
        dimcount   = in_minfo.dimcount;
        planecount = in_minfo.planecount;
        
        if( planecount < 3 )
        {
            object_error((t_object *)x, "jit.pcl requires at least a 3 plane matrix (xyz)");
            goto out;
        }
        if( in_minfo.type != _jit_sym_float32)
        {
            object_error((t_object *)x, "received: %s jit.pcl uses only float32 matrixes", in_minfo.type->s_name );
            goto out;
        }
        
        //if dimsize is 1, treat as infinite domain across that dimension.
        //otherwise truncate if less than the output dimsize
        
        for (i=0; i<dimcount; i++) {
            dim[i] = in_minfo.dim[i];
            if ( in_minfo.dim[i]<dim[i] && in_minfo.dim[i]>1) {
                dim[i] = in_minfo.dim[i];
            }
        }
        
        //******
        // PCL stuff
        if (planecount == 3)
        {
            pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
            cloud->width    = (uint32_t)dim[0];
            cloud->height   = (uint32_t)dim[1];
            cloud->points.resize (cloud->width * cloud->height);
            
            rowstride = in_minfo.dimstride[1];// >> 2L;
            size_t count = 0;
            
            for (j = 0; j < dim[0]; j++)
            {
                fip =  in_bp + j * in_minfo.dimstride[0];
                
                for( i = 0; i < dim[1]; i++)
                {
                    cloud->points[count].x = ((float *)fip)[0];
                    cloud->points[count].y = ((float *)fip)[1];
                    cloud->points[count].z = ((float *)fip)[2];
                    count++;
                    fip += rowstride;
                }
            }
            
                //filter
                pcl::VoxelGrid<pcl::PointXYZ> grid;
                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_voxel_ (new pcl::PointCloud<pcl::PointXYZ>);
                
                grid.setLeafSize (x->leafsize, x->leafsize, x->leafsize);
                grid.setInputCloud (cloud);
                grid.filter (*cloud_voxel_);
                
                err = jit_cloud2jit(x, cloud_voxel_, &out_minfo, &out_matrix );
                if( err != JIT_ERR_NONE )
                    goto out;

        }
        else if (planecount == 6)
        {
            pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
            cloud->width    = (uint32_t)dim[0];
            cloud->height   = (uint32_t)dim[1];
            cloud->points.resize (cloud->width * cloud->height);
            
            post("input size %d %d", cloud->width, cloud->height);
            
            rowstride = in_minfo.dimstride[1];// >> 2L;
            size_t count = 0;
            
            for (j = 0; j < dim[0]; j++)
            {
                fip =  in_bp + j * in_minfo.dimstride[0];
                
                for( i = 0; i < dim[1]; i++)
                {
                    cloud->points[count].x = ((float *)fip)[0];
                    cloud->points[count].y = ((float *)fip)[1];
                    cloud->points[count].z = ((float *)fip)[2];
                    cloud->points[count].r = (uint8_t)(((float *)fip)[3] * 255.0);
                    cloud->points[count].g = (uint8_t)(((float *)fip)[4] * 255.0);
                    cloud->points[count].b = (uint8_t)(((float *)fip)[5] * 255.0);
                    count++;
                    fip += rowstride;
                }
            }
            
            //filter
            pcl::VoxelGrid<pcl::PointXYZRGB> grid;
            pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_voxel_ (new pcl::PointCloud<pcl::PointXYZRGB>);
            
            grid.setLeafSize (x->leafsize, x->leafsize, x->leafsize);
            grid.setInputCloud (cloud);
            grid.filter (*cloud_voxel_);
            
            /*
            pcl::IndicesConstPtr voxel_indices;
            voxel_indices = grid.getIndices();
            */
            
            post("output size %d %d", cloud_voxel_->width, cloud_voxel_->height);

            err = jit_xyzrgb2jit(x, cloud_voxel_, &out_minfo, &out_matrix );
            if( err != JIT_ERR_NONE )
                goto out;
            
        }
        // unable to make use of jitter's parallel methods since we need all the data together
        //jit_parallel_ndim_simplecalc2((method)jit_pcl_voxel_calculate_ndim,
        //	x, dimcount, dim, planecount, &in_minfo, in_bp, &out_minfo, out_bp,
        //	0 /* flags1 */, 0 /* flags2 */);
        
    }
    else
        return JIT_ERR_INVALID_PTR;
    
out:
    jit_object_method( out_matrix, _jit_sym_lock, out_savelock );
    jit_object_method( in_matrix, _jit_sym_lock, in_savelock );
    return err;
}
void irextract_process (t_irextract *x, t_symbol *rec_buffer, t_atom_long num_channels, double sample_rate)
{
	FFT_SETUP_D fft_setup;
	
	FFT_SPLIT_COMPLEX_D spectrum_1;
	FFT_SPLIT_COMPLEX_D spectrum_2;
	FFT_SPLIT_COMPLEX_D spectrum_3;

	void *excitation_sig;
	double *out_mem;
	float *rec_mem;
	float *filter_in;
	
	t_symbol *filter = filter_retriever(x->deconvolve_filter_specifier);
	
	double filter_specifier[HIRT_MAX_SPECIFIER_ITEMS];
	double range_specifier[HIRT_MAX_SPECIFIER_ITEMS];
	
	double test_pow;
	double max_pow;
	double deconvolve_phase = phase_retriever(x->deconvolve_phase);
	
	long deconvolve_mode = x->deconvolve_mode;
	long bandlimit = x->measure_mode == SWEEP ? x->bandlimit : 0;
	
	AH_SIntPtr rec_length = buffer_length(rec_buffer);
	AH_SIntPtr gen_length = 0;
	AH_SIntPtr filter_length = buffer_length(filter);
	AH_SIntPtr out_length_samps;
	
	AH_UIntPtr fft_size; 
	AH_UIntPtr fft_size_log2;
	AH_UIntPtr i;
	
	if (buffer_check((t_object *)x, rec_buffer) || !rec_length)
		return;
	
	switch (x->measure_mode)
	{	
		case SWEEP:
			gen_length = ess_get_length(&x->sweep_params);
			break;
			
		case MLS:
			gen_length = mls_get_length(&x->max_length_params);
			break;
			
		case NOISE:
			gen_length = coloured_noise_get_length(&x->noise_params);
			break;
	}
	
	// Check and calculate lengths
	
	fft_size = calculate_fft_size(rec_length + gen_length, &fft_size_log2);
	
	if (rec_length % num_channels)
		object_warn ((t_object *) x, "buffer length is not a multiple of the number of channels - number may be wrong");
		
	if (((rec_length / num_channels) - gen_length) < 1)
	{
		object_error ((t_object *) x, "buffer is not long enough for generated signal");
		return;
	}
	
	out_length_samps = ((rec_length / num_channels) - gen_length);
	
	if (x->out_length)
	{
		if (out_length_samps < (x->out_length * sample_rate))
			object_warn ((t_object *) x, "buffer is not long enough for requested output length");
		else
			out_length_samps = (AH_SIntPtr) (x->out_length * sample_rate);
	}
	
	// Allocate Temporary Memory
	
	fft_setup = hisstools_create_setup_d(fft_size_log2);
		
	excitation_sig = malloc(((gen_length > filter_length) ? gen_length : filter_length) * sizeof(double));
	
	spectrum_1.realp = ALIGNED_MALLOC((sizeof(double) * fft_size * 4));
	spectrum_1.imagp = spectrum_1.realp + (fft_size >> 1);
	spectrum_2.realp = spectrum_1.imagp + (fft_size >> 1);
	spectrum_2.imagp = spectrum_2.realp + (fft_size >> 1);
	spectrum_3.realp = spectrum_2.imagp + (fft_size >> 1);
	spectrum_3.imagp = spectrum_3.realp + fft_size;
		
	rec_mem = (float *) malloc(rec_length * sizeof(float));
	
	filter_in = filter_length ? ALIGNED_MALLOC(sizeof(float *) * filter_length) : 0; 
	
	if (!fft_setup || !excitation_sig || !spectrum_1.realp || (filter_length && !filter_in))
	{
		object_error ((t_object *) x, "could not allocate temporary memory for processing");
		
		hisstools_destroy_setup_d(fft_setup);
		free(excitation_sig);
		ALIGNED_FREE(spectrum_1.realp);
		ALIGNED_FREE(filter_in);
	
		return;
	}
	
	x->fft_size = fft_size;
	x->sample_rate = sample_rate;
	x->out_length_samps = out_length_samps;
	x->gen_length = gen_length;
	
	// Allocate output memory and get record memory
	
	out_mem = grow_mem_swap(&x->out_mem, fft_size * sizeof(double), fft_size);
	
	if (!out_mem) 
	{
		object_error ((t_object *) x, "could not allocate memory for output storage");
		free(excitation_sig);
		hisstools_destroy_setup_d(fft_setup);
		return;
	}

	// Generate Signal
	
	switch (x->measure_mode)
	{
		case SWEEP:
			ess_gen(&x->sweep_params, excitation_sig, true);
			break;
			
		case MLS:
			mls_gen(&x->max_length_params, excitation_sig, true);
			break;
			
		case NOISE:
			coloured_noise_gen(&x->noise_params, excitation_sig, true);
			break;
	}
	
	// Transform excitation signal into complex spectrum 2
	
	time_to_halfspectrum_double(fft_setup, excitation_sig, gen_length, spectrum_2, fft_size);
			 
	if (bandlimit)
	{
		// Calculate standard filter for bandlimited deconvolution (sweep * inv sweep)
		
		ess_igen(&x->sweep_params, excitation_sig, true, true);
		time_to_halfspectrum_double(fft_setup, excitation_sig, gen_length, spectrum_3, fft_size);
		convolve(spectrum_3, spectrum_2, fft_size, SPECTRUM_REAL);
							
		// Calculate full power spectrum from half spectrum - convert filter to have the required phase
		
		power_full_spectrum_from_half_spectrum(spectrum_3, fft_size);		
		variable_phase_from_power_spectrum(fft_setup, spectrum_3, fft_size, deconvolve_phase, true);	
		
		// Convert back to real format
		
		spectrum_3.imagp[0] = spectrum_3.realp[fft_size >> 1];		
	}
	else 
	{
		// Find maximum power to scale 
		
		for (i = 1, max_pow = 0; i < (fft_size >> 1); i++)
Beispiel #3
0
void omax_object_createIOReport(t_object *x, t_symbol *msg, int argc, t_atom *argv, long *buflen, char **buf)
{
	t_symbol *classname = object_classname(x);
	if(!classname){
		return;
	}
	t_hashtab *ht = omax_class_getHashtab(classname->s_name);
	if(!ht){
		return;
	}
	long nkeys = 0;
	t_symbol **keys = NULL;
	hashtab_getkeys(ht, &nkeys, &keys);

	t_osc_bndl_u *bndl_u = osc_bundle_u_alloc();
	int i;
	for(i = 0; i < nkeys; i++){
		if(!osc_error_validateAddress(keys[i]->s_name)){
			int j;

			for(j = 0; j < argc; j++){
				t_atom *a = argv + j;
				if(atom_gettype(a) == A_SYM){
					int ret = 0;
					int ao, po;
					if(atom_getsym(a) == gensym("/*")){
						ret = OSC_MATCH_ADDRESS_COMPLETE;
					}else{
						ret = osc_match(atom_getsym(a)->s_name, keys[i]->s_name, &po, &ao);
					}
					if(ret && OSC_MATCH_ADDRESS_COMPLETE){
						t_omax_method *m = NULL;
						hashtab_lookup(ht, keys[i], (t_object **)(&m));
						if(!m){
							continue;
						}
						if(m->type == OMAX_PARAMETER){
							t_object *attr = object_attr_get(x, m->sym);
							long argc = 0;
							t_atom *argv = NULL;
							//m->m.m_fun(ob, attr, &argc, &argv);
							char getter[128];
							sprintf(getter, "get%s", m->sym->s_name);
							long get;
							method f = object_attr_method(x, gensym(getter), (void **)(&attr), &get);
							if(f){
								f(x, attr, &argc, &argv);
								if(argv){
									char address[128];
									sprintf(address, "/%s", m->sym->s_name);
									t_atom a[argc + 1];
									atom_setsym(a, gensym(address));
									memcpy(a + 1, argv, argc * sizeof(t_atom));

									t_osc_msg_u *msg_u = NULL;
									t_osc_err e = omax_util_maxAtomsToOSCMsg_u(&msg_u, ps_oscioreport, argc + 1, a);
									if(e){
										object_error((t_object *)x, "%s", osc_error_string(e));
										if(bndl_u){
											osc_bundle_u_free(bndl_u);
										}
										return;
									}
									osc_bundle_u_addMsg(bndl_u, msg_u);
									sysmem_freeptr(argv);
								}
							}
						}
					}
				}
			}
		}
	}
	//*buflen = pos;
	t_osc_bndl_s *bs = osc_bundle_u_serialize(bndl_u);
	if(bs){
		*buflen = osc_bundle_s_getLen(bs);
		*buf = osc_bundle_s_getPtr(bs);
		osc_bundle_s_free(bs);
	}
	if(bndl_u){
		osc_bundle_u_free(bndl_u);
	}
}
// Methods bound to input/inlets
t_jit_err jit_pcl_segeuclidean_matrix_calc(t_jit_pcl_segeuclidean *x, void *inputs, void *outputs)
{
    t_jit_err			err = JIT_ERR_NONE;
    long				in_savelock;
    long				out_savelock;
    t_jit_matrix_info	in_minfo;
    t_jit_matrix_info	out_minfo;
    char				*in_bp;
    char				*out_bp;
    long				i, j;
    long				dimcount;
    long				planecount;
    long				dim[JIT_MATRIX_MAX_DIMCOUNT];
    void				*in_matrix;
    void				*out_matrix;
    
    long rowstride;
    float *fip, *fop;
    
    
    in_matrix 	= jit_object_method(inputs,_jit_sym_getindex,0);
    out_matrix 	= jit_object_method(outputs,_jit_sym_getindex,0);
    
    if (x && in_matrix && out_matrix)
    {
        in_savelock = (long) jit_object_method(in_matrix, _jit_sym_lock, 1);
        out_savelock = (long) jit_object_method(out_matrix, _jit_sym_lock, 1);
        
        jit_object_method(in_matrix, _jit_sym_getinfo, &in_minfo);
        jit_object_method(in_matrix, _jit_sym_getdata, &in_bp);
        
        if (!in_bp) {
            err=JIT_ERR_INVALID_INPUT;
            goto out;
        }
        
        //get dimensions/planecount
        dimcount   = in_minfo.dimcount;
        planecount = in_minfo.planecount;
        
        if( planecount < 3 )
        {
            object_error((t_object *)x, "jit.pcl requires a 3 plane matrix (xyz)");
            goto out;
        }
        if( in_minfo.type != _jit_sym_float32)
        {
            object_error((t_object *)x, "received: %s jit.pcl uses only float32 matrixes", in_minfo.type->s_name );
            goto out;
        }
        
        //if dimsize is 1, treat as infinite domain across that dimension.
        //otherwise truncate if less than the output dimsize
        
        for (i=0; i<dimcount; i++) {
            dim[i] = in_minfo.dim[i];
            if ( in_minfo.dim[i]<dim[i] && in_minfo.dim[i]>1) {
                dim[i] = in_minfo.dim[i];
            }
        }
        
        //******
        // PCL stuff
        
        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
        cloud->width    = (uint32_t)dim[0];
        cloud->height   = (uint32_t)dim[1];
        cloud->is_dense = false;
        cloud->points.resize (cloud->width * cloud->height);
        
        rowstride = in_minfo.dimstride[1];// >> 2L;
        size_t count = 0;
        
        for (j = 0; j < dim[0]; j++)
        {
            fip =  (float *)(in_bp + j * in_minfo.dimstride[0]);
            
            for( i = 0; i < dim[1]; i++)
            {
                cloud->points[count].x = ((float *)fip)[0];
                cloud->points[count].y = ((float *)fip)[1];
                cloud->points[count].z = ((float *)fip)[2];
        //        cloud->points[count].r = (uint8_t)(((float *)fip)[3] * 255.0);
        //        cloud->points[count].g = (uint8_t)(((float *)fip)[4] * 255.0);
        //        cloud->points[count].b = (uint8_t)(((float *)fip)[5] * 255.0);
                count++;
                fip += rowstride;
            }
        }
        
      
        {

            /*
            //filter
            pcl::VoxelGrid<pcl::PointXYZRGB> grid;
            pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_voxel_ (new pcl::PointCloud<pcl::PointXYZRGB>);
            
            grid.setLeafSize (x->leafsize, x->leafsize, x->leafsize);
            grid.setInputCloud (cloud);
            grid.filter (*cloud_voxel_);
            
            
            pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;
            pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_sor_ (new pcl::PointCloud<pcl::PointXYZRGB>);
            
            sor.setInputCloud(cloud_voxel_);
            sor.setMeanK( (uint32_t)x->npoints );
            sor.setStddevMulThresh(x->stdthresh);
            sor.filter(*cloud_sor_);
            */
            
            pcl::search::KdTree<pcl::PointXYZ>::Ptr kdtree(new pcl::search::KdTree<pcl::PointXYZ>);
            kdtree->setInputCloud(cloud);
            
            // Euclidean clustering object.
            pcl::EuclideanClusterExtraction<pcl::PointXYZ> clustering;
            // Set cluster tolerance to 2cm (small values may cause objects to be divided
            // in several clusters, whereas big values may join objects in a same cluster).
            clustering.setClusterTolerance(x->cluster_tol);
            // Set the minimum and maximum number of points that a cluster can have.
            clustering.setMinClusterSize(10);
            clustering.setMaxClusterSize(25000);
            clustering.setSearchMethod(kdtree);
            clustering.setInputCloud(cloud);
            
            std::vector<pcl::PointIndices> clusters;
            clustering.extract(clusters);
            // For every cluster...
            
            pcl::PointCloud<pcl::PointXYZRGB>::Ptr cluster(new pcl::PointCloud<pcl::PointXYZRGB>);
            cluster->points.resize(cloud->size());
            cluster->width = (uint32_t)cloud->points.size();
            cluster->height = 1;
            cluster->is_dense = true;


            if( clusters.size() > 0 )
            {
                double segment_inc = 255. / clusters.size();
          
                int count = 0;
                int clusterN = 0;
                for (std::vector<pcl::PointIndices>::const_iterator i = clusters.begin(); i != clusters.end(); ++i)
                {

                    for (std::vector<int>::const_iterator p = i->indices.begin(); p != i->indices.end(); ++p)
                    {

                        cluster->points[count].x = cloud->points[ *p ].x;
                        cluster->points[count].y = cloud->points[ *p ].y;
                        cluster->points[count].z = cloud->points[ *p ].z;

                        cluster->points[count].r = (uint8_t)(segment_inc * clusterN);
                        cluster->points[count].g = (uint8_t)(segment_inc * clusterN);
                        cluster->points[count].b = 255;

                        count++;
                    }
                    clusterN++;
                }
            }
            err = jit_xyzrgb2jit(x, cluster, &out_minfo, &out_matrix );
            if( err != JIT_ERR_NONE )
                goto out;
            
        }
      
        // unable to make use of jitter's parallel methods since we need all the data together
        //jit_parallel_ndim_simplecalc2((method)jit_pcl_segeuclidean_calculate_ndim,
        //	x, dimcount, dim, planecount, &in_minfo, in_bp, &out_minfo, out_bp,
        //	0 /* flags1 */, 0 /* flags2 */);
        
    }
    else
        return JIT_ERR_INVALID_PTR;
    
out:
    jit_object_method( out_matrix, _jit_sym_lock, out_savelock );
    jit_object_method( in_matrix, _jit_sym_lock, in_savelock );
    return err;
}
Beispiel #5
0
// we get the text, convert it to an OSC bundle, and then call the paint
// function via qelem_set which converts the OSC bundle back to text.
// We do this so that it's formatted nicely with no unnecessary whitespace
// and tabbed subbundles, etc.
void odisplay_gettext(t_odisplay *x)
{
	long size	= 0;
	char *text	= NULL;
#ifdef OMAX_PD_VERSION
	text = x->textbox->text;
#else
	t_object *textfield = jbox_get_textfield((t_object *)x);
	object_method(textfield, gensym("gettextptr"), &text, &size);
#endif
    
	odisplay_clearBundles(x);
	size = strlen(text); // the value returned in text doesn't make sense
	if(size == 0){
		return;
	}
	char *buf = text;

	if(text[size - 1] != '\n'){
		buf = alloca(size + 2);
		memcpy(buf, text, size);
		buf[size] = '\n';
		buf[size + 1] = '\0';
		size += 2;
	}

	t_osc_bndl_u *bndl_u = NULL;
	t_osc_err e = osc_parser_parseString(size, buf, &bndl_u);
	if(e){
#ifdef OMAX_PD_VERSION
//		x->parse_error = 1;
#endif
		object_error((t_object *)x, "error parsing bundle\n");
		return;
	}
	t_osc_bndl_s *bs = osc_bundle_u_serialize(bndl_u);
	t_osc_bndl_s *bndl_s = NULL;
	osc_bundle_s_deepCopy(&bndl_s, bs);
	odisplay_newBundle(x, bndl_u, bndl_s);
#ifdef OMAX_PD_VERSION
    x->have_new_data = 1;
	jbox_redraw((t_jbox *)x);
#else
	x->have_new_data = 1;
	qelem_set(x->qelem);
#endif
	/*
	if(size > 2){
		int i;
		char *r = text + 1;
		char *w = text + 1;
		char *rm1 = text;
		for(i = 0; i <= size; i++){
			if(*rm1 == ' ' && *r == ' '){
				r++;
			}else{
				*w++ = *r++;
			}
			rm1++;
		}
	}
	*/
}
void model_preset_edit(TTPtr self, t_symbol *msg, long argc, const t_atom *argv)
{
	WrappedModularInstancePtr	x = (WrappedModularInstancePtr)self;
	TTString			*buffer;
	char				title[MAX_FILENAME_CHARS];
	TTObject            aTextHandler;
	TTHashPtr			allPresets;
	TTValue				v, o, args, none;
	TTSymbol			name;
    t_atom              a;
	TTErr				tterr;

	// choose object to edit : default the cuelist
	*EXTRA->toEdit = *EXTRA->presetManager;
	EXTRA->presetName = kTTSymEmpty;

	if (argc && argv) {

		if (atom_gettype(argv) == A_LONG) {

			// get presets names
			EXTRA->presetManager->get("names", v);

			if (atom_getlong(argv) <= (TTInt32) v.size())
				name = v[atom_getlong(argv)-1];

			else {
				object_error((t_object*)x, "%d doesn't exist", atom_getlong(argv));
				return;
			}
		}
		else if (atom_gettype(argv) == A_SYM)
			name = TTSymbol(atom_getsym(argv)->s_name);

		if (name != kTTSymEmpty) {

			// get preset object table
			EXTRA->presetManager->get("presets", v);
			allPresets = TTHashPtr((TTPtr)v[0]);

			if (allPresets) {

				// get cue to edit
				if (!allPresets->lookup(name, v)) {

					// edit a preset
					*EXTRA->toEdit = v[0];
					EXTRA->presetName = name;
				}
				else {
					object_error((t_object*)x, "%s doesn't exist", atom_getsym(argv)->s_name);
					return;
				}
			}
		}
	}

	// only one editor can be open in the same time
	if (!EXTRA->textEditor) {

		EXTRA->textEditor = (t_object*)object_new(_sym_nobox, _sym_jed, x, 0);

		buffer = new TTString();

		// get the buffer handler
		tterr = x->internals->lookup(kTTSym_TextHandler, o);

		if (!tterr) {

			aTextHandler = o[0];

			critical_enter(0);
			aTextHandler.set(kTTSym_object, *EXTRA->toEdit);
			tterr = aTextHandler.send(kTTSym_Write, (TTPtr)buffer, none);
			critical_exit(0);
		}

		// pass the buffer to the editor
		object_method(EXTRA->textEditor, _sym_settext, buffer->c_str(), _sym_utf_8);
		object_attr_setchar(EXTRA->textEditor, gensym("scratch"), 1);

		snprintf(title, MAX_FILENAME_CHARS, "%s preset editor", x->patcherClass.c_str());
		object_attr_setsym(EXTRA->textEditor, _sym_title, gensym(title));

        // output a flag
        atom_setsym(&a, gensym("opened"));
        object_obex_dumpout(self, gensym("editor"), 1, &a);

		buffer->clear();
		delete buffer;
		buffer = NULL;
	}
}
Beispiel #7
0
t_max_err polywave_buf_set(t_polywave *x, t_object *attr, long argc, t_atom *argv)
{

    int i;
    t_symbol *s;

    if(argc && argv)
    {
        if(argc < POLYWAVE_MAX_BUFFERS)
        {
            critical_enter(x->lock);
            if(argc >= x->numbufs)
            {
                i = 0;
                while(i < x->numbufs)
                {
                    if(atom_gettype(argv+i) != A_SYM)
                    {
                        object_error((t_object *)x, "non symbol buffer name");
                        return -1;
                    }
                    
                    s = atom_getsym(argv+i);
                    if(s) {
                        if(s != x->buf_name[i])
                        {
                            buffer_proxy_set_ref(x->buf_proxy[i], s);
                            x->buf_name[i] = s;
                        }
                    } else {
                        object_error((t_object *)x, "must have buffer name");
                    }
                    i++;
                }

                while (i < argc)
                {
                    if(atom_gettype(argv+i) != A_SYM)
                    {
                        object_error((t_object *)x, "non symbol buffer name");
                        return -1;
                    }
                    
                    x->buf_name[i] = atom_getsym(argv+i);
                    if(x->buf_name[i])
                        x->buf_proxy[i] = buffer_proxy_new(x->buf_name[i]);
                    else
                        object_error((t_object *)x, "must have buffer name");
                    
                    i++;
                }
                
                x->numbufs = argc;
                
            }
            else if(argc < x->numbufs)
            {
                i = 0;
                while(i < argc)
                {
                    
                    if(atom_gettype(argv+i) != A_SYM)
                    {
                        object_error((t_object *)x, "non symbol buffer name");
                        return -1;
                    }
                    
                    s = atom_getsym(argv+i);
                    if(s && s != x->buf_name[i] ) {
                        buffer_proxy_set_ref(x->buf_proxy[i], s);
                        x->buf_name[i] = s;
                    } else {
                        //object_error((t_object *)x, "must have buffer name");
                    }
                    i++;
                }
            
            }
            critical_exit(x->lock);
        }
    }
    
    return 0;
}
Beispiel #8
0
void *grans_new(t_symbol *s, long argc, t_atom *argv)
{
    int n;
	t_grans *x = (t_grans *)object_alloc(grans_class);
    
	if (x) {
		dsp_setup((t_pxobject *)x, 8);
        
        x->maxoscillators = DEFAULTMAXOSCILLATORS;
        
        if( argc > 0)
        {
            int i;
            t_atom *ap;
            for (i = 0, ap = argv; i < argc; i++, ap++) {
                if(atom_gettype(ap) == A_LONG)
                {
                    switch(i){
                        case 0:
                            n = atom_getlong(ap);
                            x->maxoscillators = n;
                            // object_post((t_object *)x, "%d oscillators initialized", n);
                            break;
                        case 1:
                            n = atom_getlong(ap);
                            x->numoutlets = n;
                            // object_post((t_object *)x, "%d outlets?", n);
                            
                            while(n--){
                                outlet_new(x, "signal");
                            }
                        default:
                            break;
                    }
                }
            }
            
        }
        else
        {
            x->numoutlets = 1;
            outlet_new(x, "signal");
            // outlet_new(x, "signal");
            
        }
		
        x->ob.z_misc |= Z_NO_INPLACE;
        
        
		x->base = (t_osc *)calloc(x->maxoscillators, sizeof(t_osc));
        //		x->modbase = (t_osc *)calloc(x->maxoscillators, sizeof(t_osc));
        
        x->sinetab = (double *)calloc(STABSZ, sizeof(double));
        x->wind_costab = (double *)calloc(STABSZ, sizeof(double));
        x->expdecaytab = (double *)calloc(STABSZ, sizeof(double));
        x->dampedsinetab = (double *)calloc(STABSZ, sizeof(double));
        x->sincwindow = (double *)calloc(STABSZ, sizeof(double));
        
        double coefshape[NSHAPINGTABS];
        
        PowTableFunction(NSHAPINGTABS, coefshape, 1, 0.0001, 1.0, 2.0);
        
        
        x->exptab = (double **)calloc(NSHAPINGTABS, sizeof(double *));
        
        long i;
        for(i = 0; i < NSHAPINGTABS; i++){
            x->exptab[i] = (double *)calloc(STABSZ, sizeof(double));
            if(x->exptab[i])
            {
                PowTableFunction(STABSZ, x->exptab[i], 1, 0.0001, 1.0, coefshape[i] * 10.0);
            } else {
                object_error((t_object *)x, "could not allocate memory for lookup table");
            }
        }
        
        x->samplerate =  sys_getsr();
        if(x->samplerate<=0)
            x->samplerate = 44100;
        
        
        x->sampleinterval = 1.0 / x->samplerate;
        x->pkw = ( STABSZ * x->sampleinterval ) ;
        
        x->maxhz = (x->samplerate / 2) * x->pkw;
        x->nosc = x->next_nosc = 0;
        
        x->prev_in1 = 0.0;
        
        x->sincripples = 5; //could make this an attribute, or maybe compute sinc in realtime...
        
        Makeoscsinetable(x);
        MakeCosWindow(x);
        MakeExpDecaytable(x);
        MakeDampedSineWindow(x);
        MakeSincWindow(x);
        
        grans_clear(x);
        
        x->always_on = 0;
        
        t_dictionary *d = NULL;
        d = dictionary_new();
        
        if (d) {
            attr_args_dictionary(d, argc, argv);
            attr_dictionary_process(x, d);
            object_free(d);
        }
        
        
        
    } else {
        object_post((t_object *)x, "this is potentially bad!");
    }
    
	return (x);
}
void data_new_address(TTPtr self, t_symbol *relativeAddress)
{
	WrappedModularInstancePtr	x = (WrappedModularInstancePtr)self;
	long		argc = 0; 
	t_atom		*argv = NULL;
	TTUInt32	number;
	TTUInt32	i;
	TTAddress	newAddress = relativeAddress->s_name;
    TTAddress   returnedAddress;
    TTNodePtr   returnedNode = NULL;
    TTNodePtr   returnedContextNode = NULL;
	t_symbol    *instanceAddress;
	TTObject    anObject;
	TTObject    aSubscriber;
	TTValue		v;
    
    x->useInternals = YES;
    x->internals->clear();
    x->internals->setThreadProtection(YES);
    x->cursor = kTTSymEmpty;
    x->arrayAddress = newAddress;
    
    if (x->arrayAddress.getType() == kAddressRelative) {
        
        number = jamoma_parse_bracket(relativeAddress, x->arrayFormatInteger, x->arrayFormatString);
        
        // don't resize to 0
        if (number && number <= MAX_ARRAY_SIZE) {
            
            // Starts iteration on internals
            x->iterateInternals = YES;
            
            x->arraySize = number;
            
            EXTRA->objectsSorted->clear();
            
            for (i = 1; i <= x->arraySize; i++) {
                
                jamoma_edit_numeric_instance(x->arrayFormatInteger, &instanceAddress, i);
                
                // create a data
#ifdef JMOD_MESSAGE
                data_array_create(self, anObject, kTTSym_message, i);
#endif
                
#if JMOD_RETURN
                data_array_create(self, anObject, kTTSym_return, i);
#endif
                
#ifndef JMOD_MESSAGE
#ifndef JMOD_RETURN
                data_array_create(self, anObject, kTTSym_parameter, i);
#endif
#endif

                if (!jamoma_subscriber_create((t_object*)x, anObject, TTAddress(instanceAddress->s_name),  aSubscriber, returnedAddress, &returnedNode, &returnedContextNode)) {
                    
                    if (aSubscriber.valid()) {
                        
                        // append the data to the internals table
                        v = TTValue(anObject);
                        v.append(TTSymbol(instanceAddress->s_name));
                        v.append(aSubscriber);
                        x->internals->append(TTSymbol(instanceAddress->s_name), v);
                        
                        // inverse objects order for iteration purpose (see in data_array_return_value : array mode)
                        EXTRA->objectsSorted->insert(0, anObject);
                    }
                }
            }
            
            // Ends iteration on internals
            x->iterateInternals = NO;
            
            // handle args
            jamoma_ttvalue_to_Atom(x->arrayArgs, &argc, &argv);
            if (argc && argv)
                attr_args_process(x, argc, argv);
            
            // select all datas
            wrappedModularClass_ArraySelect(self, gensym("*"), 0, NULL);
            
#ifndef JMOD_MESSAGE
            // init all datas created dynamically
            if (!EXTRA->firstArray)
                defer((t_object*)x, (method)wrappedModularClass_anything, _sym_init, 0, NULL);
#endif
        }
        else if (number > MAX_ARRAY_SIZE)
            object_error((t_object*)x, "the size is greater than the maximum array size (%d)", MAX_ARRAY_SIZE);
        
        EXTRA->firstArray = NO;
    }
    else
        object_error((t_object*)x, "can't register because %s is not a relative address", relativeAddress->s_name);
}
void WrappedDataClass_new(TTPtr self, long argc, t_atom *argv)
{
	WrappedModularInstancePtr	x = (WrappedModularInstancePtr)self;
	t_symbol					*relativeAddress;
	long						attrstart = attr_args_offset(argc, argv);			// support normal arguments
	TTValue						none;
	
	// check address argument
	relativeAddress = _sym_nothing;
	if (attrstart && argv)
		if (atom_gettype(argv) == A_SYM)
			relativeAddress = atom_getsym(argv);
	
	if (relativeAddress == _sym_nothing) {
		object_error((t_object*)x, "needs a name as first argument");
		x->extra = NULL;
		return;
	}
	
	// add an inlet for the index
	x->inlets = (TTHandle)sysmem_newptr(sizeof(TTPtr) * 1);
	x->inlets[0] = proxy_new(x, 1, &x->index);	// use this member to store index (because index is used for data array)
	
	// Make outlets (before attr_args_process)
	/////////////////////////////////////////////////////////////////////////////////
	
	// Don't create outlets during dynamic changes
	x->outlets = (TTHandle)sysmem_newptr(sizeof(TTPtr) * 2);
	x->outlets[index_out] = outlet_new(x, NULL);					// long outlet to output data index
	x->outlets[data_out] = outlet_new(x, NULL);						// anything outlet to output data
    
    x->useInternals = YES;
    x->internals->setThreadProtection(YES);
	
	x->arraySize = 0;
	x->arrayIndex = 0;
	x->arrayAddress = kTTAdrsEmpty;
	x->arrayArgs = none;
	x->arrayAttrFormat = gensym("single");
	
	// Prepare extra data for parameters and messages
	x->extra = (t_extra*)malloc(sizeof(t_extra));
	
	EXTRA->changingAddress = NO;
	EXTRA->firstArray = YES;
    EXTRA->objectsSorted = new TTList();
	
	// handle args
	if (argc && argv) {
		
		// set the external attribute
		attr_args_process(x, argc, argv);
		
		// keep args to set the wrapped object attributes
		if (argc > 1)
			jamoma_ttvalue_from_Atom(x->arrayArgs, _sym_list, argc--, argv++);
	}
	
	// The following must be deferred because we have to interrogate our box,
	// and our box is not yet valid until we have finished instantiating the object.
	// Trying to use a loadbang method instead is also not fully successful (as of Max 5.0.6)
	defer_low((t_object*)x, (method)data_new_address, relativeAddress, 0, NULL);
}
Beispiel #11
0
int fton_fton(t_fton *x, double f)
{
	char *notes[12];
	if(x->accdntls == 1){
		char *sharps[] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};
		memcpy(notes, sharps, 12 * sizeof(char *));
	} else if (x->accdntls == 0) {
		char *flats[] = {"C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"};
		memcpy(notes, flats, 12 * sizeof(char *));
	} else {
		object_error((t_object *)x, "accidental mode can be 0: flats or 1: sharps only");
		return 0;
	}
	
	double mCents, cents;
	int mNote, oct;
	char *roundCents, *noteSym;
	t_atom outList[2];
	
	if(f){
		mCents = 69 + (12 * log2(fabs(f)/x->a4));
	
		switch (x->centMode) {
			case 1:
				if(mCents > 0){
					asprintf(&roundCents, "%0.5f", mCents);
					mNote = (int)trunc(atof(roundCents) + 0.5);
				} else {
					asprintf(&roundCents, "%0.5f", mCents);
					mNote = (int)trunc(atof(roundCents) - 0.5);
				}
				//post("%d", mNote);
				if(mNote >= 0){
					oct = (mNote / 12) - 1;
					asprintf(&noteSym, "%s%d", notes[mNote%12], oct);
				} else {
					oct = ((mNote+1) / 12) - 2;
					asprintf(&noteSym, "%s%d", notes[(288+mNote)%12], oct);	
				}
//				post("%s", noteSym);
				atom_setsym(outList, gensym(noteSym));

				cents = 100 * (mCents - mNote);
				if (fabs(cents) < 0.001)//round off error tweak
					cents = 0;
				
				char *centSym;
				if(cents >= 0){
					asprintf(&centSym, "%+.2lf", (double)(lround(cents * 1000))/1000.);
				//	post("%s %f", centSym, cents);
					atom_setsym(outList+1, gensym(centSym));
				} else {
					asprintf(&centSym, "%+.2lf", (double)(lround(cents * 1000))/1000.);
				//	post("%s %f", centSym, cents);
					atom_setfloat(outList+1, (float)atof(centSym));
				}
				
				free(centSym);
				break;
			case 0:
				asprintf(&roundCents, "%0.5f", mCents);
				mNote = (int)trunc(atof(roundCents));

				if(mNote >= 0){
					oct = (mNote / 12) - 1;
					asprintf(&noteSym, "%s%d", notes[mNote%12], oct);
				} else {
					oct = ((mNote+1) / 12) - 2;
					asprintf(&noteSym, "%s%d", notes[(288+mNote)%12], oct);	
				}
				atom_setsym(outList, gensym(noteSym));
				
				cents = 100 * (mCents - mNote);
				if (fabs(cents) < 0.001)//round off error tweak
					cents = 0;
				atom_setfloat(outList+1, cents);
				break;
			default:
				break;
		}
		critical_enter(x->lock);
		memcpy(x->n, outList, 2 * sizeof(t_atom));
		critical_exit(x->lock);
		free(noteSym);
		free(roundCents);
		return 1;
	} else {
		outlet_anything(x->outlet, gensym("zero"), 0, NULL);
		free(noteSym);
		free(roundCents);
		return 0;
	}
}
Beispiel #12
0
void fton_list(t_fton *x, t_symbol *s, long argc, t_atom *argv)
{
	long i;
	int safe = 0;
	t_atom *ap;
	t_atom notes[(argc*2)-1];
	t_symbol *first = NULL;
	
	for (i = 0, ap = argv; i < argc; i++, ap++) {
		if(atom_gettype(ap)==A_LONG) {
			safe = fton_fton(x, (double)atom_getlong(ap));
			if(safe){
				if(x->centMode == 1){
					if(!i){
						first = atom_getsym(x->n);
						atom_setsym(notes, atom_getsym(x->n+1));
					} else {
						atom_setsym(notes+((i*2)-1), atom_getsym(x->n));
						atom_setsym(notes+(i*2), atom_getsym(x->n+1));
					}
				} else if(x->centMode == 0){
					if(!i){
						first = atom_getsym(x->n);
						atom_setfloat(notes, atom_getfloat(x->n+1));
					} else {
						atom_setsym(notes+((i*2)-1), atom_getsym(x->n));
						atom_setfloat(notes+(i*2), atom_getfloat(x->n+1));
					}
				}
			} else {
				object_error((t_object *)x, "something's wrong A_LONG");
				break;
			}
		} else if (atom_gettype(ap)==A_FLOAT){
			safe = fton_fton(x, atom_getfloat(ap));
			if(safe){
				if(x->centMode == 1){
					if(!i){
						first = atom_getsym(x->n);
						if(atom_gettype(x->n+1)==A_SYM)
							atom_setsym(notes, atom_getsym(x->n+1));
						else
							atom_setfloat(notes, atom_getfloat(x->n+1));
					} else {
						atom_setsym(notes+((i*2)-1), atom_getsym(x->n));
						if(atom_gettype(x->n+1)==A_SYM)
							atom_setsym(notes+(i*2), atom_getsym(x->n+1));
						else
							atom_setfloat(notes+(i*2), atom_getfloat(x->n+1));						
					}
				} else if(x->centMode == 0){
					if(!i){
						first = atom_getsym(x->n);
						atom_setfloat(notes, atom_getfloat(x->n+1));
					} else {
						atom_setsym(notes+((i*2)-1), atom_getsym(x->n));
						atom_setfloat(notes+(i*2), atom_getfloat(x->n+1));
					}
				}
			} else {
				object_error((t_object *)x, "something's wrong A_FLOAT");
				break;
			}
		} else {
			object_error((t_object *)x, "list must contain frequencies only");
			safe = 0;
			break;
		}
	}
	
	if(safe && argc){
		outlet_anything(x->outlet, first, (argc*2)-1, notes);
	}
}
Beispiel #13
0
	/**@public @memberof t_OMax_learn
	 * @brief Add state in both FO and Data Structure
	 * @remarks Input message in Max5: @c add*/
	void OMax_learn_add(t_OMax_learn *x, t_symbol *s, short ac, t_atom * av)
	{
		/// Check for binding
		if (OMax_learn_bind(x))
		{
			int out;				
			if (ac>0)
			{
				/// Create new Data state from the input message
				switch (x->datatype)
				{
					case LETTERS:
					{
						if (av->a_type == A_SYM)
						{
							int statenb;
							O_char newdata (*atom_getsym(av)->s_name);
							statenb = x->builder.get_data()->get_size()-1;
							if (statenb>0)
								newdata.set_bufferef(statenb);
							else
								newdata.set_bufferef(0);
							newdata.set_duration(1);
							
							ATOMIC_INCREMENT(&((t_OMax_oracle *)(x->oname->s_thing))->wflag);
							ATOMIC_INCREMENT(&((t_OMax_data *)(x->dataname->s_thing))->wflag);
							if (!(((t_OMax_oracle *)(x->oname->s_thing))->readcount)
								&& !(((t_OMax_data *)(x->dataname->s_thing))->readcount))
							{
								/// Add state to both structures
								out = x->builder.add(newdata);
							}
							else
								object_error((t_object *)x,"Oracle %s being read (%d, %d)",x->oname->s_name, ((t_OMax_oracle *)(x->oname->s_thing))->readcount, ((t_OMax_data *)(x->dataname->s_thing))->readcount);
							ATOMIC_DECREMENT(&((t_OMax_oracle *)(x->oname->s_thing))->wflag);
							ATOMIC_DECREMENT(&((t_OMax_data *)(x->dataname->s_thing))->wflag);
						}
						else
							object_error((t_object *)x,"Wrong type of data");
						break;
						
					}
					case MIDI_MONO:
					{
						O_MIDI_mono * newdata = new O_MIDI_mono();
						bool valid = TRUE;
						switch(ac)
						{
							case 6:
								if ((av+5)->a_type == A_LONG)
									((O_label*)newdata)->set_duration(atom_getlong(av+5));
								else
								{
									object_error((t_object *)x, "Error in input, duration must be int");
									valid = FALSE;
									break;
								}
							case 5:
								if ((av+4)->a_type == A_LONG)
									((O_label*)newdata)->set_bufferef(atom_getlong(av+4));
								else
								{
									object_error((t_object *)x, "Error in input, buffer reference must be int");
									valid = FALSE;
									break;
								}
							case 4:
								if ((av+3)->a_type == A_LONG)
									((O_label*)newdata)->set_section(atom_getlong(av+3));
								else
								{
									object_error((t_object *)x, "Error in input, section must be int");
									valid = FALSE;
									break;
								}
							case 3:
								if ((av+2)->a_type == A_LONG)
									((O_label*)newdata)->set_phrase(atom_getlong(av+2));
								else
								{
									object_error((t_object *)x, "Error in input, phrase must be int");
									valid = FALSE;
									break;
								}
							case 2:
								if ((av+1)->a_type == A_LONG)
									newdata->set_velocity(atom_getlong(av+1));
								else
								{
									object_error((t_object *)x, "Error in input, velocity must be int");
									valid = FALSE;
									break;
								}
							case 1:
								if (av->a_type == A_LONG)
									newdata->set_pitch(atom_getlong(av));
								else
								{
									object_error((t_object *)x, "Error in input, pitch must be int");
									valid = FALSE;
								}
								break;
							default:
								object_error((t_object *)x, "Error in input, too many arguments");
								valid = FALSE;
								break;
						}
						ATOMIC_INCREMENT(&((t_OMax_oracle *)(x->oname->s_thing))->wflag);
						ATOMIC_INCREMENT(&((t_OMax_data *)(x->dataname->s_thing))->wflag);
						if (!(((t_OMax_oracle *)(x->oname->s_thing))->readcount)
							&& !(((t_OMax_data *)(x->dataname->s_thing))->readcount))
						{
							/// Add state to both structures
							out = x->builder.add(*newdata);
						}
						else
							object_error((t_object *)x,"Oracle %s being read (%d, %d)",x->oname->s_name, ((t_OMax_oracle *)(x->oname->s_thing))->readcount, ((t_OMax_data *)(x->dataname->s_thing))->readcount);
						ATOMIC_DECREMENT(&((t_OMax_oracle *)(x->oname->s_thing))->wflag);
						ATOMIC_DECREMENT(&((t_OMax_data *)(x->dataname->s_thing))->wflag);
						break;
					}
					case SPECTRAL:
						int pitchin;
						int coeffcount;
						bool valid = TRUE;
						O_spectral * newdata;
						if(ac < (x->nbcoeffs+1)) {
							object_error((t_object *)x, "Missing coefficients");
							valid = FALSE;
						}
						else
						{
							if ((av)->a_type == A_LONG)
								pitchin = atom_getlong(av);
							else
								valid = FALSE;
							list<float> coeffsin;
							for (coeffcount = 0; coeffcount < x->nbcoeffs; coeffcount++)
							{
								if((av+coeffcount+1)->a_type == A_FLOAT)
									coeffsin.push_back(atom_getfloat(av+coeffcount+1));
								else {
									object_error((t_object *)x, "Wrong types in coefficents");
									valid = FALSE;
								}
							}
							newdata = new O_spectral(pitchin, coeffsin);
							if (ac >= x->nbcoeffs+2) {
								if ((av+x->nbcoeffs+1)->a_type == A_LONG)
									((O_label*)newdata)->set_phrase(atom_getlong(av+x->nbcoeffs+1));
								else
								{
									object_error((t_object *)x, "Error in input, phrase must be int");
									valid = FALSE;
								}
								if (ac >= x->nbcoeffs+3) {
									if ((av+x->nbcoeffs+2)->a_type == A_LONG)
										((O_label*)newdata)->set_section(atom_getlong(av+x->nbcoeffs+2));
									else
									{
										object_error((t_object *)x, "Error in input, section must be int");
										valid = FALSE;
									}
									if (ac >= x->nbcoeffs+4) {
										if ((av+x->nbcoeffs+3)->a_type == A_LONG)
											((O_label*)newdata)->set_bufferef(atom_getlong(av+x->nbcoeffs+3));
										else
										{
											object_error((t_object *)x, "Error in input, buffer reference must be int");
											valid = FALSE;
										}
										if (ac == x->nbcoeffs+5) {
											if ((av+x->nbcoeffs+4)->a_type == A_LONG)
												((O_label*)newdata)->set_duration(atom_getlong(av+x->nbcoeffs+4));
											else
											{
												object_error((t_object *)x, "Error in input, duration must be int");
												valid = FALSE;
											}
											
										}
										else {
											object_error((t_object *)x, "Error in input, too many arguments");
											valid = FALSE;
										}
									}}}
						}
						ATOMIC_INCREMENT(&((t_OMax_oracle *)(x->oname->s_thing))->wflag);
						ATOMIC_INCREMENT(&((t_OMax_data *)(x->dataname->s_thing))->wflag);
						if (!(((t_OMax_oracle *)(x->oname->s_thing))->readcount)
							&& !(((t_OMax_data *)(x->dataname->s_thing))->readcount))
						{
							/// Add state to both structures
							out = x->builder.add(*newdata);
						}
						else
							object_error((t_object *)x,"Oracle %s being read (%d, %d)",x->oname->s_name, ((t_OMax_oracle *)(x->oname->s_thing))->readcount, ((t_OMax_data *)(x->dataname->s_thing))->readcount);
						ATOMIC_DECREMENT(&((t_OMax_oracle *)(x->oname->s_thing))->wflag);
						ATOMIC_DECREMENT(&((t_OMax_data *)(x->dataname->s_thing))->wflag);
						break;		
				}
				/// Output the index of the added state (identical in both structures)
				outlet_int(x->stateout, out);
			}
			else
				object_error((t_object *)x,"Error in input, too few arguments");
		}
	}
void irreference_process (t_irreference *x, t_symbol *sym, short argc, t_atom *argv)
{
    FFT_SETUP_D fft_setup;

    FFT_SPLIT_COMPLEX_D spectrum_1;
    FFT_SPLIT_COMPLEX_D spectrum_2;
    FFT_SPLIT_COMPLEX_D spectrum_3;
    FFT_SPLIT_COMPLEX_D spectrum_4;

    void *rec_mem1;
    void *rec_mem2;
    double *out_mem;
    double *out_buf;
    float *filter_in;

    t_symbol *filter = filter_retriever(x->deconvolve_filter_specifier);

    double filter_specifier[HIRT_MAX_SPECIFIER_ITEMS];
    double range_specifier[HIRT_MAX_SPECIFIER_ITEMS];

    double sample_rate = x->sample_rate;
    double deconvolve_phase = phase_retriever(x->deconvolve_phase);
    double deconvolve_delay;

    long deconvolve_mode = deconvolve_mode = x->deconvolve_mode;
    long smoothing_on = x->num_smooth;

    AH_SIntPtr alloc_rec_length = x->T;
    AH_SIntPtr rec_length = x->current_length;
    AH_SIntPtr filter_length = buffer_length(filter);

    AH_UIntPtr fft_size;
    AH_UIntPtr fft_size_log2;
    AH_UIntPtr mem_size;
    AH_UIntPtr i;

    // Sanity check

    if (!rec_length)
        return;

    // Check and calculate lengths

    fft_size = calculate_fft_size(rec_length * 2, &fft_size_log2);
    deconvolve_delay = delay_retriever(x->deconvolve_delay, fft_size, sample_rate);

    // Allocate Temporary Memory

    fft_setup = hisstools_create_setup_d(fft_size_log2);

    spectrum_1.realp = ALIGNED_MALLOC((sizeof(double) * fft_size * 4));
    spectrum_1.imagp = spectrum_1.realp + (fft_size >> 1);
    spectrum_2.realp = spectrum_1.imagp + (fft_size >> 1);
    spectrum_2.imagp = spectrum_2.realp + (fft_size >> 1);
    spectrum_3.realp = spectrum_2.imagp + (fft_size >> 1);
    spectrum_3.imagp = spectrum_3.realp + fft_size;

    filter_in = filter_length ? ALIGNED_MALLOC(sizeof(float *) * filter_length) : 0;

    if (smoothing_on)
    {
        spectrum_4.realp = malloc(sizeof(double) * 2 * fft_size);
        spectrum_4.imagp = spectrum_4.realp + fft_size;
    }
    else
        spectrum_4.realp = 0;

    if (!fft_setup || !spectrum_1.realp || (smoothing_on && !spectrum_4.realp) || (filter_length && !filter_in))
    {
        object_error ((t_object *) x, "could not allocate temporary memory for processing");

        hisstools_destroy_setup_d(fft_setup);
        ALIGNED_FREE(spectrum_1.realp);
        ALIGNED_FREE(filter_in);
        free(spectrum_4.realp);

        return;
    }

    x->fft_size = fft_size;

    // Allocate output memory and get record memory

    rec_mem1 = access_mem_swap(&x->rec_mem, &mem_size);
    out_mem = grow_mem_swap(&x->out_mem, fft_size * x->current_num_active_ins * sizeof(double), fft_size);

    if (!out_mem)
    {
        object_error ((t_object *) x, "could not allocate memory for output storage");
        free(spectrum_1.realp);
        hisstools_destroy_setup_d(fft_setup);
        return;
    }

    // Transform reference into spectrum 2 - [smooth]

    time_to_halfspectrum_double(fft_setup, rec_mem1, rec_length, spectrum_2, fft_size);
    if (smoothing_on)
        irreference_smooth(fft_setup, spectrum_2, spectrum_4, x->smooth_mode, fft_size, x->num_smooth > 1 ? x->smooth[0] : 0., x->num_smooth > 1 ? x->smooth[1] : x->smooth[0]);

    // Fill deconvolution filter specifiers - read filter from buffer (if specified) - make deconvolution filter - delay filter

    fill_power_array_specifier(filter_specifier, x->deconvolve_filter_specifier, x->deconvolve_num_filter_specifiers);
    fill_power_array_specifier(range_specifier, x->deconvolve_range_specifier, x->deconvolve_num_range_specifiers);
    buffer_read(filter, 0, filter_in, fft_size);
    make_deconvolution_filter(fft_setup, spectrum_2, spectrum_3, filter_specifier, range_specifier, 0, filter_in, filter_length, fft_size, SPECTRUM_REAL, deconvolve_mode, deconvolve_phase, sample_rate);
    delay_spectrum(spectrum_3, fft_size, SPECTRUM_REAL, deconvolve_delay);

    // Deconvolve each input

    for (i = 0; i < (AH_UIntPtr) x->current_num_active_ins; i++)
    {
        // Get current input and output buffers

        rec_mem2 = (double *) rec_mem1 + ((i + 1) * alloc_rec_length);
        out_buf = out_mem + (i * fft_size);

        // Do transform into spectrum_1 - [smooth] - deconvolve - [delay] - transform back

        time_to_halfspectrum_double(fft_setup, rec_mem2, rec_length, spectrum_1, fft_size);
        if (smoothing_on)
            irreference_smooth(fft_setup, spectrum_1, spectrum_4, x->smooth_mode, fft_size, x->num_smooth > 1 ? x->smooth[0] : 0., x->num_smooth > 1 ? x->smooth[1] : x->smooth[0]);
        deconvolve_with_filter(spectrum_1, spectrum_2, spectrum_3, fft_size, SPECTRUM_REAL);
        spectrum_to_time(fft_setup, out_buf, spectrum_1, fft_size, SPECTRUM_REAL);
    }

    // Free Memory

    hisstools_destroy_setup_d(fft_setup);
    ALIGNED_FREE(spectrum_1.realp);
    ALIGNED_FREE(filter_in);
    free(spectrum_4.realp);

    // Done

    outlet_bang(x->process_done);
}
Beispiel #15
0
void *pitch_new(t_symbol *s, short argc, t_atom *argv) {
	t_int i, j;
	t_int vs = sys_getblksize(); // get vector size
    t_pitch *x = (t_pitch *)object_alloc(pitch_class);
	if(!x){
		return NULL;
	}

    dsp_setup((t_pxobject *)x,1); // one signal inlet	
	x->x_Fs = sys_getsr();
	x->BufWritePos = 0;
	
	// From fiddle~
    x->x_histphase = 0;
    x->x_dbage = 0;
    x->x_peaked = 0;
    x->x_amplo = DEFAMPLO;
    x->x_amphi = DEFAMPHI;
    x->x_attacktime = DEFATTACKTIME;
    x->x_attackbins = 1; // real value calculated afterward
    x->x_attackthresh = DEFATTACKTHRESH;
    x->x_vibtime = DEFVIBTIME;
    x->x_vibbins = 1;	 // real value calculated afterward
    x->x_vibdepth = DEFVIBDEPTH;
    x->x_npartial = DEFNPARTIAL;
    x->x_attackvalue = 0;

	// More initializations from Fiddle~
    for (i=0; i<MAXNPITCH; i++) {
		x->x_hist[i].h_pitch = x->x_hist[i].h_noted = 0.0f;
		x->x_hist[i].h_age = 0;
		x->x_hist[i].h_wherefrom = NULL;
		
		for (j=0; j<HISTORY; j++)
	    	x->x_hist[i].h_amps[j] = x->x_hist[i].h_pitches[j] = 0.0f;
    }
        
    for (i=0; i<HISTORY; i++) 
    	x->x_dbs[i] = 0.0f;
		
	switch (argc) { // Read arguments
		case 0: 
			x->BufSize = DEFBUFSIZE;
			x->x_overlap = x->BufSize/2;
			x->x_hop = x->BufSize/2;
			x->FFTSize = DEFBUFSIZE;
			x->x_window = DEFWIN;
			x->x_delay = DEFDELAY;
			x->x_npitch = DEFNPITCH;
			x->x_npeakanal = DEFNPEAKANAL;
			x->x_npeakout = DEFNPEAKOUT;
			break;
		case 1:
			readBufSize(x,argv);
			x->x_overlap = x->BufSize/2;
			x->x_hop = x->BufSize/2;
			x->FFTSize = x->BufSize;
			x->x_window = DEFWIN;
			x->x_delay = DEFDELAY;
			x->x_npitch = DEFNPITCH;
			x->x_npeakanal = DEFNPEAKANAL;
			x->x_npeakout = DEFNPEAKOUT;
			break;
		case 2:
			readBufSize(x,argv);
			readx_overlap(x,argv);		
			x->FFTSize = x->BufSize;
			x->x_window = DEFWIN;
			x->x_delay = DEFDELAY;
			x->x_npitch = DEFNPITCH;
			x->x_npeakanal = DEFNPEAKANAL;
			x->x_npeakout = DEFNPEAKOUT;
			break;
		case 3:
			readBufSize(x,argv);
			readx_overlap(x,argv);		
			readFFTSize(x,argv);
			x->x_window = DEFWIN;
			x->x_delay = DEFDELAY;
			x->x_npitch = DEFNPITCH;
			x->x_npeakanal = DEFNPEAKANAL;
			x->x_npeakout = DEFNPEAKOUT;
			break;
		case 4:
			readBufSize(x,argv);
			readx_overlap(x,argv);		
			readFFTSize(x,argv);
			readx_window(x,argv);
			x->x_delay = DEFDELAY;
			x->x_npitch = DEFNPITCH;
			x->x_npeakanal = DEFNPEAKANAL;
			x->x_npeakout = DEFNPEAKOUT;
			break;
		case 5:
			readBufSize(x,argv);
			readx_overlap(x,argv);			
			readFFTSize(x,argv);
			readx_window(x,argv);
			readx_delay(x,argv);
			x->x_npitch = DEFNPITCH;
			x->x_npeakanal = DEFNPEAKANAL;
			x->x_npeakout = DEFNPEAKOUT;
			break;
		case 6:
			readBufSize(x,argv);
			readx_overlap(x,argv);			
			readFFTSize(x,argv);
			readx_window(x,argv);
			readx_delay(x,argv);
			readx_npitch(x,argv);
			x->x_npeakanal = DEFNPEAKANAL;
			x->x_npeakout = DEFNPEAKOUT;
			break;
		case 7:
			readBufSize(x,argv);
			readx_overlap(x,argv);			
			readFFTSize(x,argv);
			readx_window(x,argv);
			readx_delay(x,argv);
			readx_npitch(x,argv);
			readx_npeakanal(x,argv);
			x->x_npeakout = DEFNPEAKOUT;
			break;
		default:
			readBufSize(x,argv);
			readx_overlap(x,argv);			
			readFFTSize(x,argv);
			readx_window(x,argv);
			readx_delay(x,argv);
			readx_npitch(x,argv);
			readx_npeakanal(x,argv);
			readx_npeakout(x,argv);
	}		
	
	if (x->x_npeakout > x->x_npeakanal) {
		object_post((t_object *)x, "Pitch~: You can't output more peaks than you pick...");
		x->x_npeakout = x->x_npeakanal;
	}
	
	// Make an outlet for peaks out
	if (x->x_npeakout)
    	x->x_peakout = listout((t_object *)x); // one list out

	// Make an outlet for Amplitude in dB
	x->x_envout = floatout((t_object *)x);

 	// One outlet for fundamental & amplitude raw values
	if (x->x_npitch)
		x->x_pitchout = listout((t_object *)x);

 	// One outlet for MIDI & frequency cooked pitch
	x->x_noteout = listout((t_object *)x);

	// Make bang outlet for onset detection
	x->x_attackout = bangout((t_object *)x);

	// Just storing the name of the window
	switch(x->x_window) {
		case 0:
			strcpy(x->x_winName,"rectangular");
			break;
		case 1:
			strcpy(x->x_winName,"hanning");
			break;		
		case 2:
			strcpy(x->x_winName,"hamming");
			break;		
		case 3:
			strcpy(x->x_winName,"blackman62");
			break;		
		case 4:
			strcpy(x->x_winName,"blackman70");
			break;		
		case 5:
			strcpy(x->x_winName,"blackman74");
			break;		
		case 6:
			strcpy(x->x_winName,"blackman92");
			break;		
		default:
			strcpy(x->x_winName,"blackman62");
	}
	
	if (x->BufSize < vs) { 
		object_post((t_object *)x, "Pitch~: Buffer size is smaller than the vector size, %d",vs);
		x->BufSize = vs;
	} else if (x->BufSize > 65536) {
		object_post((t_object *)x, "Pitch~: Maximum FFT size is 65536 samples");
		x->BufSize = 65536;
	}
		
	if (x->FFTSize < x->BufSize) {
		object_post((t_object *)x, "Pitch~: FFT size is at least the buffer size, %d",x->BufSize);
		x->FFTSize = x->BufSize;
	}

	if ((x->FFTSize > vs) && (x->FFTSize < 128))  x->FFTSize = 128;
	else if ((x->FFTSize > 128) && (x->FFTSize < 256)) x->FFTSize = 256;
	else if ((x->FFTSize > 256) && (x->FFTSize < 512)) x->FFTSize = 512;
	else if ((x->FFTSize > 512) && (x->FFTSize < 1024)) x->FFTSize = 1024;
	else if ((x->FFTSize > 1024) && (x->FFTSize < 2048)) x->FFTSize = 2048;
	else if ((x->FFTSize > 2048) && (x->FFTSize < 4096)) x->FFTSize = 4096;
	else if ((x->FFTSize > 8192) && (x->FFTSize < 16384)) x->FFTSize = 16384;
	else if ((x->FFTSize > 16384) && (x->FFTSize < 32768)) x->FFTSize = 32768;
	else if ((x->FFTSize > 32768) && (x->FFTSize < 65536)) x->FFTSize = 65536;
	else if (x->FFTSize > 65536) {
		object_post((t_object *)x, "Pitch~: Maximum FFT size is 65536 samples");
		x->FFTSize = 65536;
	}
	
	// Overlap case
	if (x->x_overlap > x->BufSize-vs) {
		object_post((t_object *)x, "Pitch~: You can't overlap so much...");
		x->x_overlap = x->BufSize-vs;
	} else if (x->x_overlap < 1)
		x->x_overlap = 0; 

	x->x_hop = x->BufSize - x->x_overlap;
	x->x_FFTSizeOver2 = x->FFTSize/2;		

	object_post((t_object *)x, "--- Pitch~ ---");	
	object_post((t_object *)x, "	Buffer size = %d",x->BufSize);
	object_post((t_object *)x, "	Hop size = %d",x->x_hop);
	object_post((t_object *)x, "	FFT size = %d",x->FFTSize);
	object_post((t_object *)x, "	Window type = %s",x->x_winName);
	object_post((t_object *)x, "	Initial delay = %d",x->x_delay);
	object_post((t_object *)x, "	Number of pitches = %d",x->x_npitch);
	object_post((t_object *)x, "	Number of peaks to search = %d",x->x_npeakanal);
	object_post((t_object *)x, "	Number of peaks to output = %d",x->x_npeakout);

	// Here comes the choice for altivec optimization or not...
	if (sys_optimize()) { // note that we DON'T divide the vector size by four here

#ifdef __ALTIVEC__ // More code and a new ptr so that x->BufFFT is vector aligned.
#pragma altivec_model on 
		x->x_clock = clock_new(x,(method)pitch_tick_G4); // Call altivec-optimized tick function
		object_post((t_object *)x, "	Using G4-optimized FFT");	
		// Allocate some memory for the altivec FFT
		x->x_A.realp = t_getbytes(x->x_FFTSizeOver2 * sizeof(t_float));
		x->x_A.imagp = t_getbytes(x->x_FFTSizeOver2 * sizeof(t_float));
		x->x_log2n = log2max(x->FFTSize);
      	x->x_setup = create_fftsetup (x->x_log2n, 0);
    	x->x_scaleFactor = (t_float)1.0/(2.0*x->FFTSize);
#pragma altivec_model off
#else
		object_error((t_object *)x, "  No G4 optimization available");
#endif

	} else { // Normal tick function
		x->x_clock = clock_new(x,(method)pitch_tick);
		x->memFFT = (t_float*) sysmem_newptr(CMAX * x->FFTSize * sizeof(t_float)); // memory allocated for normal fft twiddle
	}
	object_post((t_object *)x, "");

	// Allocate memory
	x->Buf1 = (t_int*) sysmem_newptr(x->BufSize * sizeof(t_float)); // Careful these are pointers to integers but the content is floats
	x->Buf2 = (t_int*) sysmem_newptr(x->BufSize * sizeof(t_float));
	x->BufFFT = (t_float*) sysmem_newptr(x->FFTSize * sizeof(t_float));
	x->BufPower = (t_float*) sysmem_newptr((x->FFTSize/2) * sizeof(t_float));
	x->WindFFT = (t_float*) sysmem_newptr(x->BufSize * sizeof(t_float));
	x->peakBuf = (t_peakout*) sysmem_newptr(x->x_npeakout * sizeof(t_peakout)); // from Fiddle~
	x->histBuf = (t_float*) sysmem_newptr((x->FFTSize + BINGUARD) * sizeof(t_float)); // for Fiddle~
		
	// Compute and store Windows
	if (x->x_window != Recta) {
		
		switch (x->x_window) {

			case Hann: 	for (i=0; i<x->BufSize; ++i)
							x->WindFFT[i] = HANNING_W(i,x->BufSize);
 						break;
			case Hamm:	for (i=0; i<x->BufSize; ++i)
							x->WindFFT[i] = HAMMING_W(i,x->BufSize);
						break;
			case Blackman62: for (i=0; i<x->BufSize; ++i)
							x->WindFFT[i] = BLACKMAN62_W(i,x->BufSize);
						break;
			case Blackman70: for (i=0; i<x->BufSize; ++i)
							x->WindFFT[i] = BLACKMAN70_W(i,x->BufSize);
						break;
			case Blackman74: for (i=0; i<x->BufSize; ++i)
							x->WindFFT[i] = BLACKMAN74_W(i,x->BufSize);
						break;
			case Blackman92: for (i=0; i<x->BufSize; ++i)
							x->WindFFT[i] = BLACKMAN92_W(i,x->BufSize);
						break;
		}
	} else {
		for (i=0; i<x->BufSize; ++i) { // Just in case
			x->WindFFT[i] = 1.0f;
		}
	}
	
	// More initializations from Fiddle~
	for (i=0; i<x->x_npeakout; i++)
		x->peakBuf[i].po_freq = x->peakBuf[i].po_amp = 0.0f;
		
    return (x);
}
void irreference_getir_internal (t_irreference *x, t_symbol *sym, short argc, t_atom *argv)
{
    t_buffer_write_error error;
    t_symbol *buffer;

    double *out_mem;

    AH_UIntPtr fft_size = x->fft_size;
    AH_UIntPtr mem_size;

    AH_SIntPtr L;

    t_atom_long in_chan = 1;

    // Get arguments

    if (!argc)
    {
        object_error ((t_object *) x, "no arguments for getir message");
        return;
    }

    if (argc > 1)
        in_chan = atom_getlong(argv++);

    buffer = atom_getsym(argv++);

    // Range check

    if (in_chan < 1 || in_chan > x->current_num_active_ins)
    {
        object_error((t_object *) x, "input channel %ld out of range", in_chan);
        return;
    }

    // Decrement input channel (reference to zero)

    in_chan--;

    if (!fft_size)
    {
        object_error ((t_object *) x, "no stored impulse responses - you may still be recording");
        return;
    }

    // Get and check memory

    out_mem = access_mem_swap(&x->out_mem, &mem_size);

    if (mem_size < fft_size)
    {
        object_error((t_object *) x, "storage memory is not large enough");
        return;
    }

    out_mem += fft_size * in_chan;
    L = (AH_SIntPtr) (x->sample_rate * x->current_out_length);

    // Write to buffer

    error = buffer_write(buffer, out_mem, L, x->write_chan - 1, x->resize, x->sample_rate, 1.);
    buffer_write_error((t_object *) x, buffer, error);
}
void *cmbuffercloud_new(t_symbol *s, long argc, t_atom *argv) {
	t_cmbuffercloud *x = (t_cmbuffercloud *)object_alloc(cmbuffercloud_class); // create the object and allocate required memory
	dsp_setup((t_pxobject *)x, 11); // create 11 inlets
	
	
	if (argc < ARGUMENTS) {
		object_error((t_object *)x, "%d arguments required (sample buffer / window type / max. voices)", ARGUMENTS);
		return NULL;
	}
	
	x->buffer_name = atom_getsymarg(0, argc, argv); // get user supplied argument for sample buffer
	x->window_name = atom_getsymarg(1, argc, argv); // get user supplied argument for window buffer
	x->grains_limit = atom_getintarg(2, argc, argv); // get user supplied argument for maximum grains
	
	// HANDLE ATTRIBUTES
	object_attr_setlong(x, gensym("stereo"), 0); // initialize stereo attribute
	object_attr_setlong(x, gensym("w_interp"), 0); // initialize window interpolation attribute
	object_attr_setlong(x, gensym("s_interp"), 1); // initialize window interpolation attribute
	object_attr_setlong(x, gensym("zero"), 0); // initialize zero crossing attribute
	attr_args_process(x, argc, argv); // get attribute values if supplied as argument
	
	// CHECK IF USER SUPPLIED MAXIMUM GRAINS IS IN THE LEGAL RANGE (1 - MAXGRAINS)
	if (x->grains_limit < 1 || x->grains_limit > MAXGRAINS) {
		object_error((t_object *)x, "maximum grains allowed is %d", MAXGRAINS);
		return NULL;
	}
	
	// CREATE OUTLETS (OUTLETS ARE CREATED FROM RIGHT TO LEFT)
	x->grains_count_out = intout((t_object *)x); // create outlet for number of currently playing grains
	outlet_new((t_object *)x, "signal"); // right signal outlet
	outlet_new((t_object *)x, "signal"); // left signal outlet
	
	// GET SYSTEM SAMPLE RATE
	x->m_sr = sys_getsr() * 0.001; // get the current sample rate and write it into the object structure
	
	/************************************************************************************************************************/
	// ALLOCATE MEMORY FOR THE BUSY ARRAY
	x->busy = (short *)sysmem_newptrclear((MAXGRAINS) * sizeof(short));
	if (x->busy == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE GRAINPOS ARRAY
	x->grainpos = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long));
	if (x->grainpos == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE START ARRAY
	x->start = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long));
	if (x->start == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE smp_length ARRAY
	x->smp_length = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long));
	if (x->smp_length == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE pitch_length ARRAY
	x->pitch_length = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long));
	if (x->pitch_length == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE PAN_LEFT ARRAY
	x->pan_left = (double *)sysmem_newptrclear((MAXGRAINS) * sizeof(double));
	if (x->pan_left == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE PAN_RIGHT ARRAY
	x->pan_right = (double *)sysmem_newptrclear((MAXGRAINS) * sizeof(double));
	if (x->pan_right == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE GAIN ARRAY
	x->gain = (double *)sysmem_newptrclear((MAXGRAINS) * sizeof(double));
	if (x->gain == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE OBJET FLOAT_INLETS ARRAY
	x->object_inlets = (double *)sysmem_newptrclear((FLOAT_INLETS) * sizeof(double));
	if (x->object_inlets == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE GRAIN PARAMETERS ARRAY
	x->grain_params = (double *)sysmem_newptrclear((FLOAT_INLETS) * sizeof(double));
	if (x->grain_params == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE GRAIN PARAMETERS ARRAY
	x->randomized = (double *)sysmem_newptrclear((FLOAT_INLETS / 2) * sizeof(double));
	if (x->randomized == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE TEST VALUES ARRAY
	x->testvalues = (double *)sysmem_newptrclear((FLOAT_INLETS) * sizeof(double));
	if (x->testvalues == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	/************************************************************************************************************************/
	// INITIALIZE VALUES
	x->object_inlets[0] = 0.0; // initialize float inlet value for current start min value
	x->object_inlets[1] = 0.0; // initialize float inlet value for current start max value
	x->object_inlets[2] = 150; // initialize float inlet value for min grain length
	x->object_inlets[3] = 150; // initialize float inlet value for max grain length
	x->object_inlets[4] = 1.0; // initialize inlet value for min pitch
	x->object_inlets[5] = 1.0; // initialize inlet value for min pitch
	x->object_inlets[6] = 0.0; // initialize value for min pan
	x->object_inlets[7] = 0.0; // initialize value for max pan
	x->object_inlets[8] = 1.0; // initialize value for min gain
	x->object_inlets[9] = 1.0; // initialize value for max gain
	x->tr_prev = 0.0; // initialize value for previous trigger sample
	x->grains_count = 0; // initialize the grains count value
	x->grains_limit_old = 0; // initialize value for the routine when grains limit was modified
	x->limit_modified = 0; // initialize channel change flag
	x->buffer_modified = 0; // initialized buffer modified flag
	// initialize the testvalues which are not dependent on sampleRate
	x->testvalues[0] = 0.0; // dummy MIN_START
	x->testvalues[1] = 0.0; // dummy MAX_START
	x->testvalues[4] = MIN_PITCH;
	x->testvalues[5] = MAX_PITCH;
	x->testvalues[6] = MIN_PAN;
	x->testvalues[7] = MAX_PAN;
	x->testvalues[8] = MIN_GAIN;
	x->testvalues[9] = MAX_GAIN;
	
	// calculate constants for panning function
	x->piovr2 = 4.0 * atan(1.0) * 0.5;
	x->root2ovr2 = sqrt(2.0) * 0.5;
	
	x->bang_trigger = 0;
	
	/************************************************************************************************************************/
	// BUFFER REFERENCES
	x->buffer = buffer_ref_new((t_object *)x, x->buffer_name); // write the buffer reference into the object structure
	x->w_buffer = buffer_ref_new((t_object *)x, x->window_name); // write the window buffer reference into the object structure
	
	return x;
}
void ircropfade_process_internal(t_ircropfade *x, t_symbol *sym, short argc, t_atom *argv)
{
    // Load arguments

    t_symbol *target = atom_getsym(argv++);
    t_symbol *source = atom_getsym(argv++);
    t_atom_long crop1 = atom_getlong(argv++);
    t_atom_long crop2 = atom_getlong(argv++);
    double fade_start = atom_getfloat(argv++);
    double in_length = atom_getfloat(argv++);
    double fade_end = atom_getfloat(argv++);
    double out_length = atom_getfloat(argv++);

    // Set fade variables

    double fade_in_lo = fade_start - 1;
    double fade_in_hi = in_length > 0 ? fade_start + in_length : fade_start;
    double fade_out_lo = fade_end;
    double fade_out_hi = out_length > 0 ? fade_end - out_length : fade_end - 1;
    double fade_in_recip = 1. / (fade_in_hi - fade_in_lo);
    double fade_out_recip = 1. / (fade_out_hi - fade_out_lo);

    float *temp1;
    double *temp2;

    t_buffer_write_error error;

    AH_SIntPtr full_length = buffer_length(source);
    AH_SIntPtr final_length;
    AH_SIntPtr i;

    t_atom_long read_chan = x->read_chan - 1;

    double sample_rate = 0;

    // Check source buffer

    if (buffer_check((t_object *) x, source, read_chan))
        return;
    sample_rate = buffer_sample_rate(source);

    crop1 = crop1 < 0 ? 0 : crop1;
    crop2 = crop2 < 0 ? 0 : crop2;
    crop1 = crop1 > full_length - 1 ? full_length - 1: crop1;
    crop2 = crop2 > full_length ? full_length : crop2;

    if (crop1 >= crop2)
        return;

    final_length = crop2 - crop1;

    // Allocate Memory

    temp1 = (float *) ALIGNED_MALLOC(full_length  * sizeof(float) + final_length * sizeof(double));
    temp2 = (double *) (temp1 + full_length);

    // Check momory allocation

    if (!temp1)
    {
        object_error((t_object *)x, "could not allocate temporary memory for processing");
        free(temp1);
        return;
    }

    // Read from buffer

    buffer_read(source, read_chan, (float *) temp1, full_length);

    // Copy with crops / fades to double precision version

    for (i = 0; i < final_length; i++)
    {
        double in_val = temp1[i + crop1];
        double fade_in = calculate_fade((double) (i + crop1), fade_in_lo, fade_in_recip);
        double fade_out = calculate_fade((double) (i + crop1), fade_out_lo, fade_out_recip);

        temp2[i] = in_val * fade_in * fade_out;
    }

    // Copy out to buffer

    error = buffer_write(target, temp2, final_length, x->write_chan - 1, x->resize, sample_rate, 1.);
    buffer_write_error((t_object *)x, target, error);

    // Free Resources

    ALIGNED_FREE(temp1);

    if (!error)
        outlet_bang(x->process_done);
}
Beispiel #19
0
void do_scan(t_sdif_fileinfo *x, FILE *f, char *name) {
	SDIFresult r;
	SDIF_FrameHeader fh;
	int result, i, sawStreamAlready, needToSkip;
	char frameTypeBuffer[5];

	x->x_ns = 0;
		
	while ((r = SDIF_ReadFrameHeader(&fh, f)) == ESDIF_SUCCESS) {
		/* post("** Read frame header: ID %d, time %g, type %c%c%c%c", fh.streamID, fh.time,
			 fh.frameType[0], fh.frameType[1], fh.frameType[2], fh.frameType[3]); */
		
		needToSkip = 1;
		
		if (x->print_NVT_matrices) {
			if (SDIF_Char4Eq(fh.frameType, "1NVT")) {
				needToSkip = 0;  // Will read the matrices in this frame rather than skipping it	
				if (Read1NVTFrame(x, f, name, &fh) == 0) return;
			}

		}
		
		sawStreamAlready = 0;
		for (i = 0; i < x->x_ns; ++i) {
			if (x->x_streamID[i] == fh.streamID) {
				sawStreamAlready = 1;
				// Already saw this stream, so just make sure type is OK
				if (!SDIF_Char4Eq(fh.frameType, x->x_frameType[i])) {
					object_post((t_object *)x, "¥ streamlist: Warning: First frame for stream %ld", fh.streamID);
					post("¥ had type %c%c%c%c, but frame at time %g has type %c%c%c%c",
						 x->x_frameType[i][0], x->x_frameType[i][1],
						 x->x_frameType[i][2], x->x_frameType[i][3],
						 fh.time, fh.frameType[0], fh.frameType[1], fh.frameType[2],
						 fh.frameType[3]);
				}
				break;
			}
		}
				
		if (!sawStreamAlready) {
			if (x->x_ns >= MAX_STREAMS) {
				object_error((t_object *)x, NAME ": SDIF file has more than %ld streams!", MAX_STREAMS);
				return;
			}
			++(x->x_ns);
			x->x_streamID[i] = fh.streamID;
			SDIF_Copy4Bytes(x->x_frameType[i], fh.frameType);
			SDIF_Copy4Bytes(frameTypeBuffer, fh.frameType);
			frameTypeBuffer[4] = '\0';
			x->x_frameTypeSymbol[i] = gensym(frameTypeBuffer);
			x->x_starttime[i] = fh.time;
			x->x_numframes[i] = 0;
		}
		
		x->x_endtime[i] = fh.time;
		++(x->x_numframes[i]);

		if (needToSkip) {
			if (r = SDIF_SkipFrame(&fh, f)) {
				object_post((t_object *)x, NAME ": error skipping frame in SDIF file %s:", name);
				object_post((t_object *)x, "   %s", SDIF_GetErrorString(r));
				return;
			}
		}
	}
	
	if (r != ESDIF_END_OF_DATA) {
		object_post((t_object *)x, NAME ": error reading SDIF file %s:", name);
		object_post((t_object *)x, "%s", SDIF_GetErrorString(r));
	}

	outlet_bang(x->outlet2);
	
	return;
}
Beispiel #20
0
void odisplay_list(t_odisplay *x, t_symbol *list_sym, short argc, t_atom *argv)
{
    object_error((t_object *)x, "o.display doesn't accept non-OSC lists in its inlet");
}
void *cmgrainlabs_new(t_symbol *s, long argc, t_atom *argv) {
	t_cmgrainlabs *x = (t_cmgrainlabs *)object_alloc(cmgrainlabs_class); // create the object and allocate required memory
	dsp_setup((t_pxobject *)x, 11); // create 11 inlets
	
	if (argc < ARGUMENTS) {
		object_error((t_object *)x, "%d arguments required (sample/window/voices)", ARGUMENTS);
		return NULL;
	}
	
	x->buffer_name = atom_getsymarg(0, argc, argv); // get user supplied argument for sample buffer
	x->window_name = atom_getsymarg(1, argc, argv); // get user supplied argument for window buffer
	x->grains_limit = atom_getintarg(2, argc, argv); // get user supplied argument for maximum grains
	
	// HANDLE ATTRIBUTES
	object_attr_setlong(x, gensym("stereo"), 0); // initialize stereo attribute
	object_attr_setlong(x, gensym("w_interp"), 0); // initialize window interpolation attribute
	object_attr_setlong(x, gensym("s_interp"), 1); // initialize window interpolation attribute
	object_attr_setlong(x, gensym("zero"), 0); // initialize zero crossing attribute
	attr_args_process(x, argc, argv); // get attribute values if supplied as argument
	
	// CHECK IF USER SUPPLIED MAXIMUM GRAINS IS IN THE LEGAL RANGE (1 - MAXGRAINS)
	if (x->grains_limit < 1 || x->grains_limit > MAXGRAINS) {
		object_error((t_object *)x, "maximum grains allowed is %d", MAXGRAINS);
		return NULL;
	}
	
	// CREATE OUTLETS (OUTLETS ARE CREATED FROM RIGHT TO LEFT)
	x->grains_count_out = intout((t_object *)x); // create outlet for number of currently playing grains
	outlet_new((t_object *)x, "signal"); // right signal outlet
	outlet_new((t_object *)x, "signal"); // left signal outlet
	
	// GET SYSTEM SAMPLE RATE
	x->m_sr = sys_getsr() * 0.001; // get the current sample rate and write it into the object structure
	
	/************************************************************************************************************************/
	// ALLOCATE MEMORY FOR THE BUSY ARRAY
	x->busy = (short *)sysmem_newptrclear((MAXGRAINS) * sizeof(short *));
	if (x->busy == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE GRAINPOS ARRAY
	x->grainpos = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long *));
	if (x->grainpos == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE START ARRAY
	x->start = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long *));
	if (x->start == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE T_LENGTH ARRAY
	x->t_length = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long *));
	if (x->t_length == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE GR_LENGTH ARRAY
	x->gr_length = (long *)sysmem_newptrclear((MAXGRAINS) * sizeof(long *));
	if (x->gr_length == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE PAN_LEFT ARRAY
	x->pan_left = (double *)sysmem_newptrclear((MAXGRAINS) * sizeof(double *));
	if (x->pan_left == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
	
	// ALLOCATE MEMORY FOR THE PAN_RIGHT ARRAY
	x->pan_right = (double *)sysmem_newptrclear((MAXGRAINS) * sizeof(double *));
	if (x->pan_right == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
    
	// ALLOCATE MEMORY FOR THE GAIN ARRAY
	x->gain = (double *)sysmem_newptrclear((MAXGRAINS) * sizeof(double *));
	if (x->gain == NULL) {
		object_error((t_object *)x, "out of memory");
		return NULL;
	}
		
	/************************************************************************************************************************/
	// INITIALIZE VALUES
	x->startmin_float = 0.0; // initialize float inlet value for current start min value
	x->startmax_float = 0.0; // initialize float inlet value for current start max value
	x->lengthmin_float = 150; // initialize float inlet value for min grain length
	x->lengthmax_float = 150; // initialize float inlet value for max grain length
	x->pitchmin_float = 1.0; // initialize inlet value for min pitch
	x->pitchmax_float = 1.0; // initialize inlet value for min pitch
	x->panmin_float = 0.0; // initialize value for min pan
	x->panmax_float = 0.0; // initialize value for max pan
	x->gainmin_float = 1.0; // initialize value for min gain
	x->gainmax_float = 1.0; // initialize value for max gain
	x->tr_prev = 0.0; // initialize value for previous trigger sample
	x->grains_count = 0; // initialize the grains count value
	x->grains_limit_old = 0; // initialize value for the routine when grains limit was modified
	x->limit_modified = 0; // initialize channel change flag
	x->buffer_modified = 0; // initialized buffer modified flag
	
	/************************************************************************************************************************/
	// BUFFER REFERENCES
	x->buffer = buffer_ref_new((t_object *)x, x->buffer_name); // write the buffer reference into the object structure
	x->w_buffer = buffer_ref_new((t_object *)x, x->window_name); // write the window buffer reference into the object structure
	
	return x;
}
Beispiel #22
0
void *ambipan_tilde_new(t_symbol *s, int argc, t_atom *argv )
{
	int    i, hp, newVersion;
	char   car = 'c';
	
	
	//--------- Allocation de la dataspace ---------------------------//
	
	t_ambipan_tilde *x = (t_ambipan_tilde*)object_alloc(ambipan_tilde_class);
	
	/*********************************************************/
	/*R�cup�ration du nombre de sorties et de haut-parleurs. */
	if( argc >= 1 ){
		if( argv[0].a_type == A_LONG )
			x->N = argv[0].a_w.w_long;
		else x->N = 0;               
	}
	else 
		x->N = Ndefaut;
	
	if( Nmax < x->N || 2 > x->N ){
		x->N = Ndefaut;
		object_error((t_object *)x, "Bad number of loudspeaker setup, %d by default", Ndefaut);
	}
	x->Nout = x->N;  //M�me nombre de sorties et d'haut-parleur.
	
	/*R�cup�ration du type rep�re ************************/
	if( argc >=2 ){
		if( argv[1].a_type == A_SYM )
			car = (char)(atom_getsym(argv+1)->s_name[0]);
		
		if( car == 'c' )
			x->base=1;
		else if( car == 'p' )
			x->base=0;
		else {
			x->base=1;
			object_error((t_object *)x, "Unknown type of coordinates, cartesian by default");
		}
	}
	else 
		x->base = 1; //Cart�sienne par d�faut.
    
	/*R�cup�ration du type des entr�es (pour des questions de compatibilit� avec l'ancienne version) *******************/
	if( argc >=3 && argv[2].a_type == A_SYM){
		object_error((t_object *)x, "The signal/control argument has no effect in this version");
		newVersion = 0;
	} else newVersion = 1;
	
	if (!newVersion) { // si ancienne version : arg 4 = offset, arg 5 = interp time :
		/*R�cup�ration de l'offset ***************************/
		if( argc >= 4 && (atom_gettype(argv+3) == A_FLOAT || atom_gettype(argv+3) == A_LONG) )
			x->offset = fabs(atom_getfloat(argv+3));
		else
			x->offset = (float)OFFSET;
		if( x->offset <= EPSILON ){
			object_error((t_object *)x, "No negative offset please");
			x->offset = (float)OFFSET;;
		}
		
		
		/*R�cup�ration du temps d'interpolation **************/
		if( argc >= 5 && argv[4].a_type == A_LONG )
			x->dtime = (int)(argv[4].a_w.w_long*sys_getsr()/1000.);
		else
			x->dtime = DTIME*sys_getsr()/1000.;
		if( x->dtime <= 0 ) //Pas de temps d'interpolation nul ou n�gatif.
			x->dtime = 1;
	}
	else { // si ancienne version : arg 3 = offset, arg 4 = interp time :
		/*R�cup�ration de l'offset ***************************/
        if( argc >= 3 && (atom_gettype(argv+2) == A_FLOAT || atom_gettype(argv+2) == A_LONG) )
            x->offset = fabs(atom_getfloat(argv+2));
		else
			x->offset = (float)OFFSET;
		if( x->offset <= EPSILON ){
			object_error((t_object *)x, "No negative offset please");
			x->offset = (float)OFFSET;;
		}
		
		
		/*R�cup�ration du temps d'interpolation **************/
		if( argc >= 4 && argv[3].a_type == A_LONG )
			x->dtime = (int)(argv[3].a_w.w_long*sys_getsr()/1000.);
		else
			x->dtime = DTIME*sys_getsr()/1000.;
		if( x->dtime <= 0 ) //Pas de temps d'interpolation nul ou negatif.
			x->dtime = 1;
	}

	
	/*********************************************************/
	/*Initialisation des donn�es de la classe. ***************/
	for( hp = x->N-1; hp >= 0; hp--) //Initialisation des P
		x->P[hp] = 0;
	
	x->mute= 0;             //entr�es signal non mut�es
	x->y   = Ydefaut;       //initialisation de y
	x->phi = Phidefaut;     //initialisation de phi
	
	//Initialisation des angles des haut-parleurs et des rayons,
	for( hp=0; hp<x->N; hp++)
	 {
		x->teta[hp] = (float)( Pi*( .5 + (1 - 2*hp )/(float)x->N) );
		x->dist[hp] = 1;
	 }
	
	/*********************************************************/
	/* Cr�ation des tableaux cosinus, cos_teta et sin_teta.  */
	/* pour l'audio.                                         */
	x->cos_teta = (float*)getbytes( (short)((T_COS+2*x->N)*sizeof(float)) );
	x->sin_teta = x->cos_teta+x->N;
	
	//Pr�calculs des cos et sin des haut-parleurs.
	for( hp=0; hp<x->N; hp++){
		x->cos_teta[hp] = (float)cos( x->teta[hp] );
		x->sin_teta[hp] = (float)sin( x->teta[hp] );
	 }
	
	//Remplissage du tableau cosinus,
	x->cosin = x->sin_teta+x->N;
	/*Pour avoir besoin de cos( phi ), on cherche:
	 cos(phi) = 
	 cosin[ (int)( phi*T_COS/360 ))&(((int)T_COS-1) ] */
	for( i=0; i<T_COS; i++) x->cosin[i] = (float)cos( i*2*Pi/T_COS );
	
	/*********************************************************/
	//initialisation de x, X, Y, W et Pn par la m�thode recoit x.
	if(x->base) ambipan_tilde_recoit_x( x, Xdefaut);
	else        ambipan_tilde_recoit_x( x, Rdefaut);     
	
	/*********************************************************/
	/*Cr�ation des nouvelles entr�es. ************************/
	dsp_setup((t_pxobject *)x, 3);
	
	/*Cr�ation des sorties************************************/
	for(i=0; i < x->N; i++) outlet_new((t_object *)x, "signal");
	
	return (void *)x;
}
void irextract_sweep (t_irextract *x, t_symbol *sym, long argc, t_atom *argv)
{			
	double f1 = 20;
	double f2 = 22050;
	double length = 30000;
	double fade_in = 50;
	double fade_out = 10;
	double out_length = 0;
	double sample_rate;
	
	double amp_curve[33];
	
	t_atom_long num_channels = 1;
	
	t_symbol *rec_buffer = 0;
	
	// Load parameters

	if (argc > 0)
	{
		rec_buffer = atom_getsym(argv++);
		sample_rate = buffer_sample_rate(rec_buffer);
		f2 = sample_rate / 2.;
	}
	if (argc > 1)
		f1 = atom_getfloat(argv++);
	if (argc > 2)
		f2 = atom_getfloat(argv++);
	if (argc > 3)
		length = atom_getfloat(argv++);
	if (argc > 4)
		fade_in = atom_getfloat(argv++);
	if (argc > 5)
		fade_out = atom_getfloat(argv++);
	if (argc > 6)
		num_channels = atom_getlong(argv++);
	if (argc > 7)
		out_length = atom_getfloat(argv++);
	
	// Check parameters
		
	if (!rec_buffer)
	{
		object_error((t_object *)x, "no buffer given");
		return;
	}
	
	f1 = irextract_param_check(x, "low frequency", f1, 0.0001, sample_rate / 2);
	f2 = irextract_param_check(x, "high frequency", f2, f2, sample_rate / 2);
	length = irextract_param_check(x, "length", length, 0., HUGE_VAL);
	fade_in = irextract_param_check(x, "fade in time", fade_in, 0., length / 2);
	fade_out = irextract_param_check(x, "fade out time", fade_out, 0., length / 2);
	num_channels = (t_atom_long) irextract_param_check(x, "number of channels", (double) num_channels, 1, HIRT_MAX_MEASURE_CHANS);
	x->out_length = irextract_param_check(x, "output length", out_length, 0., HUGE_VAL) / 1000.;
	
	// Check length of sweep and memory allocation
	
	fill_amp_curve_specifier(amp_curve, x->amp_curve_specifier, x->amp_curve_num_specifiers);
	
	if (ess_params(&x->sweep_params, f1, f2, fade_in / 1000., fade_out / 1000., length / 1000., sample_rate, db_to_a(x->amp), amp_curve))
	{
		// Process
		
		x->measure_mode = SWEEP;
		irextract_process(x, rec_buffer, num_channels, sample_rate);
	}
	else 
		object_error((t_object *) x, "zero length sweep - requested length value is too small");		
}
Beispiel #24
0
void omax_outputState(t_object *x)
{
	t_symbol *classname = object_classname(x);
	if(!classname){
		return;
	}
	t_hashtab *ht = omax_class_getHashtab(classname->s_name);
	if(!ht){
		return;
	}
	long nkeys = 0;
	t_symbol **keys = NULL;
	hashtab_getkeys(ht, &nkeys, &keys);

	t_osc_bndl_u *bndl_u = osc_bundle_u_alloc();
	int i;
	for(i = 0; i < nkeys; i++){
		if(osc_error_validateAddress(keys[i]->s_name)){
			continue;
		}

		t_omax_method *m = NULL;
		hashtab_lookup(ht, keys[i], (t_object **)(&m));
		if(!m){
			continue;
		}
		if(m->type == OMAX_PARAMETER){
			t_object *attr = object_attr_get(x, m->sym);
			long argc = 0;
			t_atom *argv = NULL;
			//m->m.m_fun(ob, attr, &argc, &argv);
			char getter[128];
			sprintf(getter, "get%s", m->sym->s_name);
			long get;
			method f = object_attr_method(x, gensym(getter), (void **)(&attr), &get);
			if(f){
				f(x, attr, &argc, &argv);
				if(argv){
					char address[128];
					sprintf(address, "/%s", m->sym->s_name);
					t_symbol *addresssym = gensym(address);

					t_osc_msg_u *msg_u = NULL;
					t_osc_err e = omax_util_maxAtomsToOSCMsg_u(&msg_u, addresssym, argc, argv);
					if(e){
						object_error((t_object *)x, "%s", osc_error_string(e));
						if(bndl_u){
							osc_bundle_u_free(bndl_u);
						}
						return;
					}
					osc_bundle_u_addMsg(bndl_u, msg_u);

					if(argv){
						sysmem_freeptr(argv);
					}
				}
			}
		}
	}
	//long len = 0;
	//char *buf = NULL;
	t_osc_bndl_s *bs = osc_bundle_u_serialize(bndl_u);
	void *outlet = omax_object_getInfoOutlet(x);
	if(outlet && bs){
		omax_util_outletOSC(outlet, osc_bundle_s_getLen(bs), osc_bundle_s_getPtr(bs));
		osc_bundle_s_deepFree(bs);
	}
	if(bndl_u){
		osc_bundle_u_free(bndl_u);
 	}
}
void irextract_noise (t_irextract *x, t_symbol *sym, long argc, t_atom *argv)
{
	double length = 10000;
	double fade_in = 10;
	double fade_out = 10;
	double amp_comp = 1.;
	double out_length = 0;
	double max_pink, max_brown;
	double sample_rate;
	
	t_atom_long num_channels = 1;

	t_symbol *rec_buffer = 0;
	
	t_noise_mode noise_mode = NOISE_MODE_WHITE;
	
	if (sym == gensym("brown"))
		noise_mode = NOISE_MODE_BROWN;
	if (sym == gensym("pink"))
		noise_mode = NOISE_MODE_PINK;
		
	// Load parameters
	
	if (argc > 0)
	{
		rec_buffer = atom_getsym(argv++);
		sample_rate = buffer_sample_rate(rec_buffer);
	}
	if (argc > 1)
		length = atom_getfloat(argv++);
	if (argc > 2)
		fade_in = atom_getfloat(argv++);
	if (argc > 3)
		fade_out = atom_getfloat(argv++);
	if (argc > 4)
		num_channels = atom_getlong(argv++);
	if (argc > 5)
		out_length = atom_getfloat(argv++);
	
	// Check parameters
	
	if (!rec_buffer)
	{
		object_error((t_object *)x, "no buffer given");
		return;
	}
	
	length = irextract_param_check(x, "length", length, 0., HUGE_VAL);
	fade_in = irextract_param_check(x, "fade in time", fade_in, 0., length / 2);
	fade_out = irextract_param_check(x, "fade out time", fade_out, 0., length / 2);
	num_channels = (t_atom_long) irextract_param_check(x, "number of channels", (double) num_channels, 1, HIRT_MAX_MEASURE_CHANS);
	x->out_length = irextract_param_check(x, "output length", out_length, 0., HUGE_VAL) / 1000.;

	// Process

	x->measure_mode = NOISE;
	coloured_noise_params(&x->noise_params, noise_mode, fade_in / 1000., fade_out / 1000., length / 1000., sample_rate, db_to_a(x->amp) / amp_comp);
	
	if (noise_mode != NOISE_MODE_WHITE)
	{
		coloured_noise_measure(&x->noise_params, (int) (length * sample_rate * 1000.), &max_pink, &max_brown);
		coloured_noise_reset(&x->noise_params);
	}
	if (noise_mode == NOISE_MODE_BROWN)
		amp_comp = max_brown;
	if (noise_mode == NOISE_MODE_PINK)
		amp_comp = max_pink;

	irextract_process(x, rec_buffer, num_channels, sample_rate);
}
t_jit_err jit_realsense_grab_matrix_calc(t_jit_realsense_grab *x, void *inputs, void *outputs)
{
	t_jit_err err = JIT_ERR_NONE;
	long out_savelock;
	t_jit_matrix_info out_minfo;
	char *out_bp;
	long i, xx, yy, dimcount, planecount, dim[JIT_MATRIX_MAX_DIMCOUNT];
	//t_jit_noise_vecdata	vecdata;
	void *out_matrix;

	PXCSenseManager *sm = x->sm;

	// note: if there is no frame available, should probably send out previous frame (to do)
	if (sm->AcquireFrame(true) < PXC_STATUS_NO_ERROR)
	{
		object_error((t_object *)x, "camera not available");
		return JIT_ERR_GENERIC;
	}

	// retrieve the sample
	PXCCapture::Sample *sample = sm->QuerySample();
	PXCImage::ImageInfo info = sample->depth->QueryInfo();
	PXCImage::ImageData data;
	out_matrix = jit_object_method(outputs, _jit_sym_getindex, 0);

//	post("w %d h %d format %s", info.width, info.height, PXCImage::PixelFormatToString(info.format));

	//get zeroith outlet
	if (x && out_matrix) 
	{
		// lock output
		out_savelock = (long)jit_object_method(out_matrix, _jit_sym_lock, 1);

		// fill out matrix info structs for input and output
		jit_object_method(out_matrix, _jit_sym_getinfo, &out_minfo);
		
		// get pointer to matrix
		jit_object_method(out_matrix, _jit_sym_getdata, &out_bp);

		if (!out_bp){ err = JIT_ERR_INVALID_OUTPUT; goto out; }

		if (!(sample->depth->AcquireAccess(PXCImage::ACCESS_READ, PXCImage::PIXEL_FORMAT_DEPTH, &data) >= PXC_STATUS_NO_ERROR))
		{
			object_error((t_object *)x, "aquire error");
			goto out;
		}

		//get dimensions/planecount
		dimcount = out_minfo.dimcount;
		planecount = out_minfo.planecount;

		if (dimcount != 2){ err = JIT_ERR_MISMATCH_DIM; goto out; }
		
		//post("dim %d x %d planes %d stride %ld", out_minfo.dim[0], out_minfo.dim[1], planecount, out_minfo.dimstride);

		for (i = 0; i < dimcount; i++) {
			dim[i] = out_minfo.dim[i];
		}

		short *dpixels = (short *)data.planes[0];
		int dpitch = data.pitches[0] / sizeof(short);
		for (yy = 0; yy < dim[1]; yy++)
		{
			for (xx = 0; xx < dim[0]; xx++)
			{
				*out_bp++ = (char)dpixels[yy * dpitch + xx];
			}
		}


		//jit_parallel_ndim_simplecalc1((method)jit_realsense_grab_calculate_ndim, x, dimcount, dim, planecount, &out_minfo, out_bp, 0 /* flags1 */);
	}
	else 
		err = JIT_ERR_INVALID_PTR;

out:
	sample->depth->ReleaseAccess(&data);
	sm->ReleaseFrame();

	jit_object_method(out_matrix, _jit_sym_lock, out_savelock);
	return err;
}
Beispiel #27
0
// This assumes we are single threaded, i.e. that we can never be interrupted by perform routine
void resonators_list(t_resonators *x, t_symbol *s, short argc, t_atom *argv)
{
	int i;
	int nres;
	double srbar = x->sampleinterval;
	dresdesc *dp = x->dbase;
	
	if (argc%3!=0) {
		object_error((t_object *)x, "multiple of 3 floats required (frequency amplitude decayRate)");
		return;
	}
			
	for(i=0; (i*3)<argc; ++i)
    {
		if (i >= MAXRESONANCES)
        {
			object_error((t_object *)x, "list has more than %ld resonances; dropping extras", MAXRESONANCES);
			break;
		}
        else
        {
			// Here are the filter design equations		
			double f = atom_getfloatarg(i*3,argc,argv);
			double g = 	atom_getfloatarg(i*3+1,argc,argv);
			double rate = atom_getfloatarg(i*3+2,argc,argv);
			double r;
			r =  exp(-rate*srbar);
			if((f<=0.0) || (f>=(0.995*x->samplerate*0.5)) || (r<=0.0) || (r>1.0))
			{
					//				post("Warning parameters out of range");
					dp[i].b1 = dp[i].b1 = 0.0;
					dp[i].a1prime = 0.0;
            }
			else
            {
					double ts;
					f *= 2.0*3.14159265358979323*srbar;
					ts = g;
					ts *= sin(f);
					dp[i].a1 = ts *  (1.0-r);   //this is one of the relavent L norms
					dp[i].b2 =  -r*r;
                    dp[i].b1 = r*cos(f)*2.0;
                        //this is the other norm that establishes the impulse response of the right amplitude (scaled
                        // so that it can be summed into the state variable outside the perform routine (for efficiency)
                        // This was chosen to correspond with IRCAM Resan representation

					dp[i].a1prime = ts/dp[i].b2;					            }
		}
	}
	/* Now we know how many "good" resonances (freq > 0) were in the list */
	nres = i;

	for(i=0;i<nres;++i)
	{
			if(i>=x->nres) 	/* If there are now more resonances than there were: */ 
            {
					// Set old a1 to zero so that the input to the new resonators will ramp up over the first signal vector.
			
					dp[i].o_a1 = 0.0;
					dp[i].o_b1 = dp[i].b1;
					dp[i].o_b2 = dp[i].b2;
					// Clear out state variables for these totally new resonances

					dp[i].out1 = dp[i].out2 = 0.0f;
			}
	}
	x->nres = nres;	
	//		post("nres %d x->nres %d", nres, x->nres);
}