static void my_audio_callback(void *userdata, unsigned char *stream, int len) { if (!l_PluginInit) return; int newsamplerate = OutputFreq * 100 / speed_factor; int oldsamplerate = GameFreq; if (buffer_pos > (len * oldsamplerate) / newsamplerate) { int input_used; if (VolumeControlType == VOLUME_TYPE_SDL) { input_used = resample(buffer, buffer_pos, oldsamplerate, mixBuffer, len, newsamplerate); SDL_MixAudio(stream, mixBuffer, len, VolSDL); } else { input_used = resample(buffer, buffer_pos, oldsamplerate, stream, len, newsamplerate); } memmove(buffer, &buffer[input_used], buffer_pos - input_used); buffer_pos -= input_used; } else { underrun_count++; DebugMessage(M64MSG_VERBOSE, "Audio buffer underrun (%i).",underrun_count); memset(stream , 0, len); buffer_pos = 0; } }
void my_audio_callback(void *userdata, Uint8 *stream, int len) { int newsamplerate = OutputFreq * 100 / speed_factor; int oldsamplerate = GameFreq; if (buffer_pos > (len * oldsamplerate) / newsamplerate) { int input_used; if (VolumeControlType == VOLUME_TYPE_SDL) { input_used = resample(buffer, buffer_pos, oldsamplerate, mixBuffer, len, newsamplerate); SDL_MixAudio(stream, mixBuffer, len, VolSDL); } else { input_used = resample(buffer, buffer_pos, oldsamplerate, stream, len, newsamplerate); } memmove(buffer, &buffer[input_used], buffer_pos - input_used); buffer_pos -= input_used; } else { #ifdef DEBUG underrun_count++; fprintf(stderr, "[JttL's SDL Audio plugin] Debug: Audio buffer underrun (%i).\n",underrun_count); #endif memset(stream , 0, len); buffer_pos = 0; } }
static void streaming_up_down_test(const SRCParams ¶ms) { // Source noise Samples noise(noise_size); RNG(seed).fill_samples(noise, noise_size); // Upsampled buffer Samples buf1(size_t(double(noise_size + 1) * params.fd / params.fs) + 1); // Downsampled buffer Samples buf2(noise_size + 100); StreamingSRC src; BOOST_REQUIRE(src.open(params)); size_t buf1_data = resample(src, noise, noise_size, buf1, buf1.size()); BOOST_REQUIRE(src.open(SRCParams(params.fd, params.fs, params.a, params.q))); size_t buf2_data = resample(src, buf1, buf1_data, buf2, buf2.size()); BOOST_CHECK(abs(int(buf2_data) - int(noise_size)) <= 1); // Resample introduces not more than -A dB of noise. // 2 resamples introduces twice more noise, -A + 6dB sample_t diff = diff_resampled(params, noise, buf2, MIN(noise_size, buf2_data)); BOOST_MESSAGE("Transform: " << params.fs << "Hz <-> " << params.fd << "Hz Diff: " << value2db(diff) << " dB"); BOOST_CHECK_LE(value2db(diff), -params.a + 7); }
HRESULT TaudioFilterResampleLavc::process(TfilterQueue::iterator it, TsampleFormat &fmt, void *samples, size_t numsamples, const TfilterSettingsAudio *cfg0) { const TresampleSettings *cfg = (const TresampleSettings*)cfg0; if (is(fmt, cfg)) { if (!cfg->equal(old) || oldfreq != fmt.freq || oldnchannels != fmt.nchannels || oldsf != fmt.sf) { old = *cfg; oldfreq = fmt.freq; oldnchannels = fmt.nchannels; oldsf = fmt.sf; done(); buffIn.clear(); buffOut.clear(); bool libsamplerateok = false; int mode = limit(cfg->mode, (int)TresampleSettings::RESAMPLE_LAVC_NORMAL, (int)TresampleSettings::RESAMPLE_LAVC_HIGHEST); TsampleFormat fmtOut = fmt; getOutputFmt(fmtOut, cfg); if (fmtOut.sf == TsampleFormat::SF_PCM16) for (unsigned int i = 0; i < fmt.nchannels; i++) switch (mode) { case TresampleSettings::RESAMPLE_LAVC_NORMAL : ctxsInt[i] = new TreSampleContext<int16_t>(1, cfg->freq, fmt.freq, 16 , 10, 0, 1.0, 15); break; case TresampleSettings::RESAMPLE_LAVC_HIGH : ctxsInt[i] = new TreSampleContext<int16_t>(1, cfg->freq, fmt.freq, 16 , 10, 1, 1.0, 22); break; case TresampleSettings::RESAMPLE_LAVC_HIGHEST: ctxsInt[i] = new TreSampleContext<int16_t>(1, cfg->freq, fmt.freq, int(16 * 2.2), 10, 1, 1.0, 22); break; } else for (unsigned int i = 0; i < fmt.nchannels; i++) switch (mode) { case TresampleSettings::RESAMPLE_LAVC_NORMAL : ctxsFloat[i] = new TreSampleContext<float>(1, cfg->freq, fmt.freq, 16 , 10, 0, 1.0, 0); break; case TresampleSettings::RESAMPLE_LAVC_HIGH : ctxsFloat[i] = new TreSampleContext<float>(1, cfg->freq, fmt.freq, 16 , 10, 1, 1.0, 0); break; case TresampleSettings::RESAMPLE_LAVC_HIGHEST: ctxsFloat[i] = new TreSampleContext<float>(1, cfg->freq, fmt.freq, int(16 * 2.2), 10, 1, 1.0, 0); break; } } if (ctxsInt[0]) { resample(fmt, (int16_t*&)samples, numsamples, cfg, ctxsInt); } else { resample(fmt, (float*&)samples, numsamples, cfg, ctxsFloat); } } return parent->deliverSamples(++it, fmt, samples, numsamples); }
int TrackerTLDImpl::Pexpert::additionalExamples(std::vector<Mat_<uchar> >& examplesForModel, std::vector<Mat_<uchar> >& examplesForEnsemble) { examplesForModel.clear(); examplesForEnsemble.clear(); examplesForModel.reserve(100); examplesForEnsemble.reserve(100); std::vector<Rect2d> closest, scanGrid; Mat scaledImg, blurredImg; double scale = scaleAndBlur(img_, cvRound(log(1.0 * resultBox_.width / (initSize_.width)) / log(SCALE_STEP)), scaledImg, blurredImg, GaussBlurKernelSize, SCALE_STEP); TLDDetector::generateScanGrid(img_.rows, img_.cols, initSize_, scanGrid); getClosestN(scanGrid, Rect2d(resultBox_.x / scale, resultBox_.y / scale, resultBox_.width / scale, resultBox_.height / scale), 10, closest); for( int i = 0; i < (int)closest.size(); i++ ) { for( int j = 0; j < 10; j++ ) { Point2f center; Size2f size; Mat_<uchar> standardPatch(STANDARD_PATCH_SIZE, STANDARD_PATCH_SIZE), blurredPatch(initSize_); center.x = (float)(closest[i].x + closest[i].width * (0.5 + rng.uniform(-0.01, 0.01))); center.y = (float)(closest[i].y + closest[i].height * (0.5 + rng.uniform(-0.01, 0.01))); size.width = (float)(closest[i].width * rng.uniform((double)0.99, (double)1.01)); size.height = (float)(closest[i].height * rng.uniform((double)0.99, (double)1.01)); float angle = (float)rng.uniform(-5.0, 5.0); for( int y = 0; y < standardPatch.rows; y++ ) { for( int x = 0; x < standardPatch.cols; x++ ) { standardPatch(x, y) += (uchar)rng.gaussian(5.0); } } #ifdef BLUR_AS_VADIM GaussianBlur(standardPatch, blurredPatch, GaussBlurKernelSize, 0.0); resize(blurredPatch, blurredPatch, initSize_); #else resample(blurredImg, RotatedRect(center, size, angle), blurredPatch); #endif resample(scaledImg, RotatedRect(center, size, angle), standardPatch); examplesForModel.push_back(standardPatch); examplesForEnsemble.push_back(blurredPatch); } } return 0; }
/************************************************* ********************FOR GUI*********************** *************************************************/ QVector<QVector<double>> sleep_apnea::sleep_apnea_plots(QVector<unsigned int> tab_R_peaks) { //getting data QVector<QVector<double>>tab_RR,tab_RR_new,tab_res; QVector<QVector<double>>h_amp(2); QVector<QVector<double>>h_freq(2); QVector<QVector<double>> apnea_plots(3); tab_RR=RR_intervals(tab_R_peaks); tab_RR_new=averange_filter(tab_RR); tab_res=resample(tab_RR_new); HP_LP_filter(tab_res); hilbert(tab_res,h_amp,h_freq); freq_amp_filter(h_freq,h_amp); median_filter(h_freq,h_amp); //resizing output apnea_plots[0].resize(h_amp[0].size()); apnea_plots[1].resize(h_amp[1].size()); apnea_plots[2].resize(h_freq[1].size()); //writing output int i; for(i=0;i<apnea_plots[0].size();i++)apnea_plots[0][i]=h_amp[0][i]; for(i=0;i<apnea_plots[1].size();i++)apnea_plots[1][i]=h_amp[1][i]; for(i=0;i<apnea_plots[2].size();i++)apnea_plots[2][i]=h_freq[1][i]; return apnea_plots; }
std::vector<moving_objects3_particle_t> algorithm_particle_filter(std::vector<moving_objects3_particle_t> particle_set_t_1, carmen_velodyne_projected_on_ground_message velodyne_projected_on_ground, double delta_time) { std::vector<moving_objects3_particle_t> particle_set_t; double total_weight = 0.0; std::vector<moving_objects3_particle_t>::iterator it = particle_set_t_1.begin(); std::vector<moving_objects3_particle_t>::iterator end = particle_set_t_1.end(); for (; it != end; ++it) { moving_objects3_particle_t particle_t; // Motion Model particle_t = sample_motion_model((*it), delta_time); // Measurement Model -> RANSAC // cost = measurement_model(particle_t, velodyne_projected_on_ground); // Weighing particles particle_t.weight = get_particle_weight(particle_t, velodyne_projected_on_ground); total_weight += particle_t.weight; particle_set_t.push_back(particle_t); } // normalize particles weight normalize_weights(particle_set_t, total_weight); // resample particle_set_t = resample(particle_set_t); return particle_set_t; }
unsigned int AmAudio::resampleOutput(unsigned char* buffer, unsigned int s, int input_sample_rate, int output_sample_rate) { if ((input_sample_rate == output_sample_rate) && !output_resampling_state.get()) { return s; } if (!output_resampling_state.get()) { #ifdef USE_INTERNAL_RESAMPLER if (AmConfig::ResamplingImplementationType == AmAudio::INTERNAL_RESAMPLER) { DBG("using internal resampler for output"); output_resampling_state.reset(new AmInternalResamplerState()); } else #endif #ifdef USE_LIBSAMPLERATE if (AmConfig::ResamplingImplementationType == AmAudio::LIBSAMPLERATE) { output_resampling_state.reset(new AmLibSamplerateResamplingState()); } else #endif { return s; } } return resample(*output_resampling_state, buffer, s, input_sample_rate, output_sample_rate); }
void ParticleFilter::observation_density_reweight(cv::Mat& input) { // Reweight every particle in model by its observation density for(int i = 0; i < N; i++) { particle_model[i].prevWeight = particle_model[i].weight; particle_model[i].weight *= likelihood(input, particle_model[i]); } // Normalize weights double sum = 0.0; for(int i = 0; i < N; i++) sum += particle_model[i].weight; double normFactor = 1.0/sum; if(sum == 0.0) normFactor = 0.0; for(int i = 0; i < N; i++) particle_model[i].weight *= normFactor; // Compute Neff (effective particle number) sum = 0.0; for(int i = 0; i < N; i++) sum += pow(particle_model[i].weight, 2); neff = 1.0/sum; if(sum == 0) neff = 0.0; ROS_INFO("Neff = %f", neff); if(neff < N * 0.04) { is_dead_ = true; } else if(neff < N * 0.75) { resample(); observation_density_reweight(input); } }
void GenericAudioMixer::pushBuffer(const uint8_t* const data, size_t size, IMetadata& metadata) { AudioBufferMetadata & inMeta = static_cast<AudioBufferMetadata&>(metadata); if(inMeta.size() >= 5) { const auto inSource = inMeta.getData<kAudioMetadataSource>() ; auto lSource = inSource.lock(); if(lSource) { auto hash = std::hash<std::shared_ptr<ISource> > ()(lSource); auto ret = resample(data, size, inMeta); if(ret->size() > 0) { // push buffer uint8_t *p; size_t rsize = ret->read(&p, ret->size()); m_inBuffer[hash]->put(p, rsize); } else { // use data provided m_inBuffer[hash]->put(const_cast<uint8_t*>(data), size); } } } }
//----------------------------------------------------------------------------- void MainWindow::keyPressEvent(QKeyEvent* e) { if ((e->key() == Qt::Key_W) || (e->key()==Qt::Key_Up)) m_frontDown=true; else if ((e->key() == Qt::Key_S) || (e->key()==Qt::Key_Down)) m_backDown=true; else if ((e->key() == Qt::Key_A) || (e->key()==Qt::Key_Left)) m_leftDown=true; else if ((e->key() == Qt::Key_D) || (e->key()==Qt::Key_Right)) m_rightDown=true; else if (e->key() == Qt::Key_R) { initStates(); } else if (e->key() == Qt::Key_1) resample(); else if (e->key() == Qt::Key_2) drift(); else if (e->key() == Qt::Key_3) diffuse(); else if (e->key() == Qt::Key_4) measure(); else if (e->key() == Qt::Key_Tab) changeRunMode(); else e->ignore(); }
int audioedit_delete_selection(struct view *v) { int rc = -1; long first, last; char undo_label[200]; get_region_of_interest(&first, &last, v); sprintf(undo_label, "Delete audio data from %ld to %ld.", first, last); if (start_save_undo(undo_label, v) < 0) return -1; rc = save_undo_data_remove(first, last, 1); close_undo(); if (rc == 1) /* canceled */ return -1; begin_operation("Deleting audio data") ; rc = soundfile_remove_samples(first, last - first + 1, 1); end_operation(); if (rc == 0) { adjust_view(v); v->selection_region = FALSE; resample(first, prefs.n_samples-1); } return rc; }
void t_audio_rx::post_media_peer_rx_3way(unsigned char *media, int len, unsigned short peer_sample_rate) { mtx_3way.lock(); if (!is_3way) { // This is not a 3-way call. This is not necessarily an // error condition. The 3rd party may be in the process of // leaving the conference. // Simply discard the posted media mtx_3way.unlock(); return; } if (peer_sample_rate != audio_encoder->get_sample_rate()) { // Resample media from peer to sample rate of this receiver int output_len = (len / 2) * audio_encoder->get_sample_rate() / peer_sample_rate; short *output_buf = new short[output_len]; MEMMAN_NEW_ARRAY(output_buf); int resample_len = resample((short *)media, len / 2, peer_sample_rate, output_buf, output_len, audio_encoder->get_sample_rate()); media_3way_peer_rx->add((unsigned char *)output_buf, resample_len * 2); MEMMAN_DELETE_ARRAY(output_buf); delete [] output_buf; } else { media_3way_peer_rx->add(media, len); } mtx_3way.unlock(); }
void t_audio_tx::post_media_peer_tx_3way(unsigned char *media, int len, unsigned short peer_sample_rate) { mtx_3way.lock(); if (!is_3way || !is_3way_mixer) { mtx_3way.unlock(); return; } if (peer_sample_rate != sc_sample_rate) { // Resample media from peer to sample rate of this transmitter int output_len = (len / 2) * sc_sample_rate / peer_sample_rate; short *output_buf = new short[output_len]; MEMMAN_NEW_ARRAY(output_buf); int resample_len = resample((short *)media, len / 2, peer_sample_rate, output_buf, output_len, sc_sample_rate); media_3way_peer_tx->add((unsigned char *)output_buf, resample_len * 2); MEMMAN_DELETE_ARRAY(output_buf); delete [] output_buf; } else { media_3way_peer_tx->add(media, len); } mtx_3way.unlock(); }
//------------------------------------------------------------------------------ //! Append anim2 at the end of anim1 (no blending whatsoever). //! If rates differ, the rate of anim1 is used for the final animation. RCP<SkeletalAnimation> Puppeteer::concatenate( SkeletalAnimation* anim1, SkeletalAnimation* anim2 ) { DBG_BLOCK( os_pup, "Puppeteer::concatenate(" << anim1 << ", " << anim2 << ")" ); anim1->makeRelative(); anim2->makeRelative(); RCP<SkeletalAnimation> anim = anim1->clone(); if( anim2->numPoses() > 0 ) { RCP<SkeletalAnimation> animToAppend; if( anim1->rate() == anim2->rate() ) { animToAppend = anim2; } else { animToAppend = resample( anim2, anim1->rate() ); } // Remove the first animation's last frame (a copy of frame 0). uint np1 = anim->numPoses() - 1; anim->removePose( np1 ); // Add the second animation's poses. uint np2 = animToAppend->numPoses(); anim->reservePoses( np1 + np2 ); for( uint p = 0; p < np2; ++p ) { anim->addPose( animToAppend->pose(p)->clone().ptr() ); } } return anim; }
void ParticleFilterLocalizer::update(const Measurements& measurements) { Particle* particle; float maxProbability = -1; for (unsigned int i = 0; i < particles.size(); i++) { particle = particles[i]; Util::confineField(particle->x, particle->y); particle->probability = getMeasurementProbability(particle, measurements); if (maxProbability == -1 || particle->probability > maxProbability) { maxProbability = particle->probability; } } if (maxProbability == 0) { return; } for (unsigned int i = 0; i < particles.size(); i++) { particles[i]->probability /= maxProbability; } resample(); }
void PosEst::estimate(Scene *scene_, Model *model_, MatrixXf boundBox, float gridSize, int cnt) { if(DEBUG_ALGORITHM) cout<<cnt<<endl; model = model_; scene = scene_; double lastT = pcl::getTime(); resample(var_trans, var_rot); if(DEBUG_ALGORITHM) cout<<"resample time : "<<pcl::getTime()-lastT<<endl; lastT = pcl::getTime(); weight(boundBox, gridSize); if(DEBUG_ALGORITHM) cout<<"weight time : "<<pcl::getTime()-lastT<<endl; // if (!(m_finalParticle.x==m_finalParticle.x && m_finalParticle.y==m_finalParticle.y && m_finalParticle.z == m_finalParticle.z && // m_finalParticle.roll == m_finalParticle.roll && m_finalParticle.pitch == m_finalParticle.pitch && m_finalParticle.yaw == m_finalParticle.yaw)) // m_finalParticle = m_lastFinalParticle; // Eigen::Affine3f finaltrans = finalParticle.toEigenMatrix(); if(DEBUG_ALGORITHM) cout<<"finaltrans is : " <<finalParticle<<endl; // CloudPtr out (new Cloud); // transformPointCloud(*m_modelOrig, *out, finaltrans); // return out; // convert finalparticle to pos_updated pos_updated = finalParticle; }
Path2D GeometricRecognizer::normalizePath(Path2D points) { /* Recognition algorithm from http://faculty.washington.edu/wobbrock/pubs/uist-07.1.pdf Step 1: Resample the Point Path Step 2: Rotate Once Based on the "Indicative Angle" Step 3: Scale and Translate Step 4: Find the Optimal Angle for the Best Score */ // TODO: Switch to $N algorithm so can handle 1D shapes //--- Make everyone have the same number of points (anchor points) points = resample(points); //--- Pretend that all gestures began moving from right hand side //--- (degree 0). Makes matching two items easier if they're //--- rotated the same if (getRotationInvariance()) points = rotateToZero(points); //--- Pretend all shapes are the same size. //--- Note that since this is a square, our new shape probably //--- won't be the same aspect ratio points = scaleToSquare(points); //--- Move the shape until its center is at 0,0 so that everyone //--- is in the same coordinate system points = translateToOrigin(points); return points; }
static void low_variance_sampler(carmen_fused_odometry_particle *xt, carmen_fused_odometry_parameters *fused_odometry_parameters) { /* int m; double sum_weights = 0.0; double sum_sqr_weight = 0.0; //double Neff; for (m = 0; m < num_particles; m++) sum_weights += xt[m].weight; // @@@ Alberto: O peso das particulas nao esta de acordo com a probabilidade; por isso tem que normalizar. for (m = 0; m < num_particles; m++) sum_sqr_weight += (xt[m].weight / sum_weights) * (xt[m].weight / sum_weights); Neff = 1.0 / sum_sqr_weight; //printf("Neff = %lf\n", Neff); if (Neff < (num_particles * 0.90)) // Selective resampling: see Grisetti, Stachniss and Burgard { // Nao estamos utilizando selective resample por causa de nao estarmos computando o peso das paticulas precisamente */ if (fabs(ut.v) > fused_odometry_parameters->minimum_speed_for_correction) { resample(xt); } }
static void cf_new_track(input_stream_t *source) { static int skipnext = 0; static input_stream_t lasttrack; int filesecs; if (lasttrack.samplerate && lasttrack.samplerate != source->samplerate) { if (resample(lasttrack.samplerate, source->samplerate) < 0) skipnext = 1; } memcpy(&lasttrack, source, sizeof(lasttrack)); /* turn off crossfading for tracks less than twice the length of the fade */ if (skipnext) { skipnext = 0; return; } if (source->filesize && source->bitrate) { filesecs = source->filesize / (source->bitrate * 128); if (filesecs < 10 || filesecs <= Fadelen * 2) { ices_log_debug("crossfade: not fading short track of %d secs", filesecs); skipnext = 1; return; } } NewTrack = FadeSamples; }
Anchors resample(const GeometryCoordinates &line, const float offset, const float spacing, const float angleWindowSize, const float maxAngle, const float labelLength, const bool continuedLine, const bool placeAtMiddle) { const float halfLabelLength = labelLength / 2.0f; float lineLength = 0; for (auto it = line.begin(), end = line.end() - 1; it != end; it++) { lineLength += util::dist<float>(*(it), *(it + 1)); } float distance = 0; float markedDistance = offset - spacing; Anchors anchors; assert(spacing > 0.0); int i = 0; for (auto it = line.begin(), end = line.end() - 1; it != end; it++, i++) { const GeometryCoordinate &a = *(it); const GeometryCoordinate &b = *(it + 1); const float segmentDist = util::dist<float>(a, b); const float angle = util::angle_to(b, a); while (markedDistance + spacing < distance + segmentDist) { markedDistance += spacing; float t = (markedDistance - distance) / segmentDist, x = util::interpolate(float(a.x), float(b.x), t), y = util::interpolate(float(a.y), float(b.y), t); // Check that the point is within the tile boundaries and that // the label would fit before the beginning and end of the line // if placed at this point. if (x >= 0 && x < util::EXTENT && y >= 0 && y < util::EXTENT && markedDistance - halfLabelLength >= 0.0f && markedDistance + halfLabelLength <= lineLength) { Anchor anchor(::round(x), ::round(y), angle, 0.5f, i); if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { anchors.push_back(anchor); } } } distance += segmentDist; } if (!placeAtMiddle && anchors.empty() && !continuedLine) { // The first attempt at finding anchors at which labels can be placed failed. // Try again, but this time just try placing one anchor at the middle of the line. // This has the most effect for short lines in overscaled tiles, since the // initial offset used in overscaled tiles is calculated to align labels with positions in // parent tiles instead of placing the label as close to the beginning as possible. anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, continuedLine, true); } return anchors; }
/** * @brief Isotropically 3D resample data to new grid size * * @param M Incoming data * @param f Resampling factor for all 3 dimensions * @param im Interpolation method (LINEAR|BSPLINE) * * @return Resampled data */ template<class T> static Matrix<T> resample (const Matrix<T>& M, const double& f, const InterpMethod& im) { Matrix<double> mf (3,1); mf = f; return resample(M, mf, im); }
void ParticleFilter::correct() { normalize(); resample(); //Op is the first particle //qsort( mParticles, mParams.NUMBER_OF_PARTICLES, sizeof( Particle ), particle_cmp); }
void resample_spam_entries_by_row(double *entries, int *pnb_ent,int *rpoint,int*pnb_rows){ int r=0; int nb_ent_row=0; for(r=0;r<*pnb_rows;r++){ nb_ent_row = rpoint[r+1]-rpoint[r]; //printf("nb_ent_row %i\n",nb_ent_row); resample(&entries[rpoint[r]-1],&nb_ent_row); } }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* B=imResample(A,scale) or B=imResample(A,h,w); */ double input1=0, input2=0; int *ns, ms[3], nCh, nDims, i, r; double *A, *B, *T; void *A1, *B1; mxClassID id; /* Error checking on arguments */ if( nrhs<2 || nrhs>3) mexErrMsgTxt("Two or three inputs expected."); if( nlhs>1 ) mexErrMsgTxt("One output expected."); nDims=mxGetNumberOfDimensions(prhs[0]); id=mxGetClassID(prhs[0]); if( (nDims!=2 && nDims!=3) || (id!=mxDOUBLE_CLASS && id!=mxUINT8_CLASS) ) mexErrMsgTxt("A should be 2D or 3D double or uint8 array."); input1=mxGetScalar(prhs[1]); if(nrhs>=3) input2=mxGetScalar(prhs[2]); /* create output array */ ns = (int*) mxGetDimensions(prhs[0]); nCh=(nDims==2) ? 1 : ns[2]; ms[2]=nCh; if( nrhs==2 ) { ms[0]=(int) (ns[0]*input1+.5); ms[1]=(int) (ns[1]*input1+.5); } else { ms[0]=(int) input1; ms[1]=(int) input2; } plhs[0] = mxCreateNumericArray(3, ms, id, mxREAL); /* convert to double if id!=mxDOUBLE_CLASS */ A1=mxGetData(prhs[0]); B1=mxGetData(plhs[0]); if( id==mxDOUBLE_CLASS ) { A=(double*) A1; B=(double*) B1; } else { A = (double*) mxMalloc( ns[0]*ns[1]*nCh*sizeof(double) ); B = (double*) mxCalloc( ms[0]*ms[1]*nCh, sizeof(double) ); } if(id==mxUINT8_CLASS) for(i=0; i<ns[0]*ns[1]*nCh; i++) A[i]=(double) ((uchar*)A1)[i]; /* Perform rescaling */ r=ns[0]/ms[0]; if(ms[0]*r==ns[0] && ms[1]*r==ns[1] ) { resampleInt(A,B,ns[0],ns[1],nCh,r); } else { T = (double*) mxCalloc(ms[0]*ns[1]*nCh, sizeof(double) ); resample( A, T, 0, ns[0], ms[0], ns[1], nCh ); resample( T, B, 1, ns[1], ms[1], ms[0], nCh ); mxFree(T); } /* convert from double if id!=mxDOUBLE_CLASS */ if(id==mxUINT8_CLASS) for(i=0; i<ms[0]*ms[1]*nCh; i++) ((uchar*)B1)[i]=(uchar) (B[i]+.5); if( id!=mxDOUBLE_CLASS ) { mxFree(A); mxFree(B); } }
void truncate_wavfile(struct view *v, int save_undo) { int rc; long first, last; long end_pos = soundfile_count_samples(); char undo_label[200]; get_region_of_interest(&first, &last, v); if (save_undo) { /* split undo-data to undo separately in case of failure */ sprintf(undo_label, "Delete audio data from %ld to %ld.", last+1, end_pos); if (start_save_undo(undo_label, v) < 0) return; rc = save_undo_data_remove(last+1, end_pos, 1); close_undo(); if (rc == 1) /* canceled */ return; } begin_operation("Deleting audio data") ; rc = soundfile_remove_samples(last+1, end_pos, 1); end_operation(); if (rc != 0) { /* failure; FIX: needs cleanup of undo and more */ return; } if (save_undo) { /* second part of undo */ sprintf(undo_label, "Delete audio data from 0 to %ld.", first-1); if (start_save_undo(undo_label, v) < 0) return; rc = save_undo_data_remove(0, first-1, 1); close_undo(); /* cancel ignored */ } begin_operation("Deleting audio data") ; rc = soundfile_remove_samples(0, first-1, 1); end_operation(); if (rc != 0) { /* failure; FIX: needs cleanup of undo and more */ return; } adjust_view(v); v->first_sample = 0; v->last_sample = v->n_samples - 1; v->selection_region = FALSE; resample(0, prefs.n_samples-1); }
vibratingString::vibratingString( float _pitch, float _pick, float _pickup, float * _impulse, int _len, sample_rate_t _sample_rate, int _oversample, float _randomize, float _string_loss, float _detune, bool _state ) : m_oversample( 2 * _oversample / (int)( _sample_rate / Engine::mixer()->baseSampleRate() ) ), m_randomize( _randomize ), m_stringLoss( 1.0f - _string_loss ), m_state( 0.1f ) { m_outsamp = new sample_t[m_oversample]; int string_length; string_length = static_cast<int>( m_oversample * _sample_rate / _pitch ) + 1; string_length += static_cast<int>( string_length * -_detune ); int pick = static_cast<int>( ceil( string_length * _pick ) ); if( not _state ) { m_impulse = new float[string_length]; resample( _impulse, _len, string_length ); } else { m_impulse = new float[_len]; for( int i = 0; i < _len; i++ ) { m_impulse[i] = _impulse[i]; } } m_toBridge = vibratingString::initDelayLine( string_length, pick ); m_fromBridge = vibratingString::initDelayLine( string_length, pick ); vibratingString::setDelayLine( m_toBridge, pick, m_impulse, _len, 0.5f, _state ); vibratingString::setDelayLine( m_fromBridge, pick, m_impulse, _len, 0.5f, _state); m_choice = static_cast<int>( m_oversample * static_cast<float>( rand() ) / RAND_MAX ); m_pickupLoc = static_cast<int>( _pickup * string_length ); }
bool COGGPlayer::readOGGStreamAndResample( OggVorbis_File &oggStream, Uint8 *buffer, const size_t output_size, const size_t input_size, const SDL_AudioSpec &OGGAudioSpec ) { Uint8 buf[input_size]; bool eof = readOGGStream( oggStream, reinterpret_cast<char*>(buf), input_size, OGGAudioSpec ); resample( buffer, buf, output_size, input_size, OGGAudioSpec.format, OGGAudioSpec.channels); return eof; }
template<class T> bool check_resample () { Matrix<T> img = phantom3D<T> (32); resample (img,.5,BSPLINE); return true; }
// the MCL algoritmh void MonteCarloLocalization::run() { // update the LaserScan and the GridMap if necessary and returns the laser TimeStamp sync = measurement->update(); // get the available commands bool moved = motion->update(sync); if(moved) { // reset the total weight Xt.total_weight = 0.0; // reset the SampleSet index sampleIndex = 0; // starts the new threads std::vector<std::thread> pool(pool_size); // spawn each thread for (int k = 0; k < pool_size; k++) { pool[k] = std::thread(&MonteCarloLocalization::sample, this); } // join each thread for (int k = 0; k < pool_size; k++) { pool[k].join(); } // normalize Xt.normalizeWeights(); // RESAMPLING if (resample_rate < resample_counter) { // resampling resample(); // reset the resample_counter resample_counter = 0; } else { // increments the resample_counter resample_counter++; } } // unlock the mutex mcl_mutex.unlock(); }