Exemplo n.º 1
0
Arr* WindowFilter(Arr *a, Arr* b,int w){
  int i=0,j=0,k=0;
  double rms0=0.0,rms1=0.0,rmsm1=0.0;
  double weight=((double) (w+1))/(w+2);
 
  w+=1;
  if(timer_on){
    timer_clear(w);
    timer_start(w);
  }
  if(a->len<b->len) Resample(a,b->len);
  if(a->len>b->len) Resample(b,a->len);
  for(i=fielddim;i<a->len-fielddim;i+=fielddim){
    rms0=(a->val[i]-b->val[i])*(a->val[i]-b->val[i])
  +(a->val[i+1]-b->val[i+1])*(a->val[i+1]-b->val[i+1])
  +(a->val[i+2]-b->val[i+2])*(a->val[i+2]-b->val[i+2])
  +(a->val[i+3]-b->val[i+3])*(a->val[i+3]-b->val[i+3]);
    j=i+fielddim;
    rms1=(a->val[j]-b->val[j])*(a->val[j]-b->val[j])
      +(a->val[j+1]-b->val[j+1])*(a->val[j+1]-b->val[j+1])
      +(a->val[j+2]-b->val[j+2])*(a->val[j+2]-b->val[j+2])
      +(a->val[j+3]-b->val[j+3])*(a->val[j+3]-b->val[j+3]);
    j=i-fielddim;
    rmsm1=(a->val[j]-b->val[j])*(a->val[j]-b->val[j])
   +(a->val[j+1]-b->val[j+1])*(a->val[j+1]-b->val[j+1])
   +(a->val[j+2]-b->val[j+2])*(a->val[j+2]-b->val[j+2])
   +(a->val[j+3]-b->val[j+3])*(a->val[j+3]-b->val[j+3]);
    k=0;
    if(rms1<rms0){
      k=1;
      rms0=rms1;
    }
    if(rmsm1<rms0) k=-1;
    if(k==0){
      j=i+fielddim;
      a->val[i]=weight*b->val[i];
      a->val[i+1]=weight*b->val[i+1];
      a->val[i+2]=weight*b->val[i+2];
      a->val[i+3]=weight*b->val[i+3];  
    }else if(k==1){
      j=i+fielddim;
      a->val[i]=weight*b->val[j];
      a->val[i+1]=weight*b->val[j+1];
      a->val[i+2]=weight*b->val[j+2];
      a->val[i+3]=weight*b->val[j+3];  
    }else { /*if(k==-1)*/
      j=i-fielddim;
      a->val[i]=weight*b->val[j];
      a->val[i+1]=weight*b->val[j+1];
      a->val[i+2]=weight*b->val[j+2];
      a->val[i+3]=weight*b->val[j+3];  
    }     
  }
  if(timer_on){
    timer_stop(w);
    fprintf(stderr,"** WindowFilter time in node %d = %f\n",(w-1),timer_read(w));
  }
  return a;
}
Exemplo n.º 2
0
void IPlugConvoEngine::Reset()
{
	TRACE; IMutexLock lock(this);

	// Detect a change in sample rate.
	if (GetSampleRate() != mSampleRate)
	{
		mSampleRate = GetSampleRate();

		const int irLength = sizeof(mIR) / sizeof(mIR[0]);
		const double irSampleRate = 44100.;
		mImpulse.SetNumChannels(1);

		#if defined(_USE_WDL_RESAMPLER)
			mResampler.SetMode(false, 0, true); // Sinc, default size
			mResampler.SetFeedMode(true); // Input driven
		#elif defined(_USE_R8BRAIN)
			if (mResampler) delete mResampler;
			mResampler = new CDSPResampler16IR(irSampleRate, mSampleRate, mBlockLength);
		#endif

		// Resample the impulse response.
		int len = mImpulse.SetLength(ResampleLength(irLength, irSampleRate, mSampleRate));
		if (len) Resample(mIR, irLength, irSampleRate, mImpulse.impulses[0].Get(), len, mSampleRate);

		// Tie the impulse response to the convolution engine.
		mEngine.SetImpulse(&mImpulse);
	}
}
Exemplo n.º 3
0
StrokeInternal::StrokeVertexIterator Stroke::strokeVerticesBegin(float t)
{
  if ((t != 0) && (t < _sampling))
    Resample(t);
  return StrokeInternal::StrokeVertexIterator(
      this->_Vertices.begin(), this->_Vertices.begin(), this->_Vertices.end());
}
Exemplo n.º 4
0
Stroke::vertex_container::reverse_iterator Stroke::vertices_last(float sampling)
{
  // Resample if necessary
  if (sampling < _sampling)
    Resample(sampling);
  return _Vertices.rbegin();
}
Exemplo n.º 5
0
Stroke::vertex_iterator Stroke::vertices_begin(float sampling)
{
  // Resample if necessary
  if ((sampling != 0) && (sampling < _sampling))
    Resample(sampling);
  return vertex_iterator(_Vertices.begin(), _Vertices.begin(), _Vertices.end());
  // return _Vertices.begin();
}
Exemplo n.º 6
0
CScreen3D::CScreen3D (const double xl, const double xr, const double yt, const double yb, const double z0, const int w, const int h)
{
	xleft = __min (xl, xr);
	xright = __max (xl, xr);
	ytop = __max (yt, yb);
	ybottom = __min (yt, yb);
	z = z0;
	width = w == 0? 1 : w;
	height = h == 0? 1 : h;
	Resample ();
}
Exemplo n.º 7
0
void SmallImage::Resample(unsigned int newWidth, unsigned int newHeight, bool bKeepAspect) {
  if (newWidth == m_size.x && newHeight == m_size.y)  return; // that was easy :-)
  
  if (bKeepAspect) AdjustToAspect(newWidth, newHeight);

  boost::uint8_t* pData = new boost::uint8_t [m_iComponentCount*newWidth*newHeight];  
  Resample(pData, newWidth, newHeight);
  delete [] m_pData;
  m_pData = pData;
  m_size = UINTVECTOR2(newWidth, newHeight);
}
    Template::Template(std::string name, PointVector points) : Name(name), references(0)
    {
        for (size_t i = 0; i < points.size(); ++i)
        {
            Points.push_back(PointPtr(new Point(points[i]->X,points[i]->Y)));
        }

        Resample(Points, NumPoints);
        RotateToZero(Points);
        ScaleToSquare(Points, SquareSize);
        TranslateToOrigin(Points);
    }
Exemplo n.º 9
0
void MR_ResBitmapBuilder::ComputeIntermediateImages(MR_UInt8 * pBuffer)
{

	// First copy the original image

	if(mSubBitmapCount != 0) {
		int lBitmapSize;
		int lCounter;

		lBitmapSize = mSubBitmapList[0].mXRes * mSubBitmapList[0].mYRes;

		// Put 0 in all transparent bit
		int lNbTransparent = 0;
		int lNbBadColors = 0;

		for(lCounter = 0; lCounter < lBitmapSize; lCounter++) {
			if(pBuffer[lCounter] < MR_RESERVED_COLORS_BEGINNING) {
				if(pBuffer[lCounter] != 0) {
					pBuffer[lCounter] = 0;
					lNbBadColors++;
				}
				lNbTransparent++;
			}
		}

		if(lNbTransparent != 0) {
			if(lNbBadColors > 0) {
				printf("WARNING: This image have invalid colors\n");
			}
			printf("INFO: This image have transparent pixels\n");
		}
		// First copy the original image
		memcpy(mSubBitmapList[0].mBuffer, pBuffer, lBitmapSize);

		// Resample the sub bitmaps
		for(lCounter = 1; lCounter < mSubBitmapCount; lCounter++) {
			printf("INFO: Resampling...\n");
			Resample(&mSubBitmapList[0], &mSubBitmapList[lCounter]);
		}

		// Init the plain color
		BOOL lDummyBool;

		printf("INFO: Computing plain color\n");

		mPlainColor = GetBestColor(mSubBitmapList[0].mBuffer, mSubBitmapList[0].mYRes, mSubBitmapList[0].mXRes, mSubBitmapList[0].mYRes, lDummyBool);
	}
	else {
		printf("WARNING: Bitmap too small, using single color\n");

		mPlainColor = *pBuffer;
	}
}
Exemplo n.º 10
0
void AudioProcessor::Consume(const int16_t *input, int length)
{
	assert(length >= 0);
	assert(length % m_num_channels == 0);
	length /= m_num_channels;
	while (length > 0) {
		int consumed = Load(input, length); 
		input += consumed * m_num_channels;
		length -= consumed;
		if (m_buffer.size() == m_buffer_offset) {
			Resample();
			if (m_buffer.size() == m_buffer_offset) {
				DEBUG("chromaprint::AudioProcessor::Consume() -- Resampling failed?");
				return;
			}
		}
	}
}
    ResultPtr Recognize(PointVector& points, TemplateVector& templates)
	{
		Resample(points, NumPoints);
		RotateToZero(points);
		ScaleToSquare(points, SquareSize);
		TranslateToOrigin(points);

		double b = DBL_MAX;
		int index = 0;
		for (size_t i = 0; i < templates.size(); ++i)
		{
			double d = DistanceAtBestAngle(points, templates[i], -AngleRange, +AngleRange, AnglePrecision);
			if (d < b)
			{
				b = d;
				index = i;
			}
		}
		double score = 1.0 - (b / HalfDiagonal);
		return ResultPtr(new Result(templates[index]->Name, score));
	};
Exemplo n.º 12
0
SDL_Surface* SDL_Resize(SDL_Surface *src, int new_w, int new_h, bool free, int filter)
{
    SDL_Surface * dst;
    bool is_alpha = has_alpha(src);    

    if (src->w == new_w && src->h == new_h)
    {
        //No change in size.
        return src;
    }

    Uint32 rmask = 0x000000ff,
        gmask = 0x0000ff00,
        bmask = 0x00ff0000,
        amask = 0xff000000;
    #if SDL_BYTEORDER == SDL_BIG_ENDIAN
        rmask = 0xff000000;
        gmask = 0x00ff0000;
        bmask = 0x0000ff00;
        amask = 0x000000ff;
    #endif

    dst = SDL_CreateRGBSurface(0, new_w, new_h, 32, rmask, gmask, bmask, amask);
    SDL_Surface * temp = SDL_ConvertSurface(src,dst->format,0);

    Resample(temp,dst,filter);
	
	SDL_FreeSurface(temp);
	temp = SDL_ConvertSurface(dst,src->format,0);
	SDL_FreeSurface(dst);
    if (is_alpha)
	{
		SDL_SetAlpha(temp, SDL_SRCALPHA, 0);
	}

	if (free)
		SDL_FreeSurface(src);
    return temp;
}
HRESULT CPatternMatch::PatternMatch(BYTE *pImage, int nImgRows, int nImgCols, double fImgScanSize,
								 BYTE *pPattern, int nPtnRows, int nPtnCols, double fPtnScanSize,
								 UINT nDataType,
								 double *px, double *py, double *pCoef)
{
	*px=nImgCols/2;
	*py=nImgRows/2;
	//�ز�����ģ��
	BYTE* pNewPattern=NULL;
	int nNewPtnRows,nNewPtnCols;
	Resample(pPattern,nPtnRows,nPtnCols,nDataType,fPtnScanSize,fImgScanSize,&pNewPattern,&nNewPtnRows,&nNewPtnCols);

	//�������
	int nX0,nY0,nHeight,nWidth;
	//ƥ����
	double X,Y,Coef;
	BOOL bMatched=FALSE;
	int nImgPydRowsPre=0,nImgPydColsPre=0;
	
	//
	int nLevel = 0;
	for(int pl=PYRAMIDLAYER;pl>=1;pl--)
	{
		nLevel = (int)pow(2,pl-1);
		BYTE* pImgPyd=NULL;
		int nImgPydRows=0,nImgPydCols=0;
		Pyramid(pImage,
				nImgRows,nImgCols,
				nDataType,
				nLevel,
				&pImgPyd,&nImgPydRows,&nImgPydCols);
		
		BYTE* pPtnPyd=NULL;
		int nPtnPydRows=0,nPtnPydCols=0;
		Pyramid(pNewPattern,
				nNewPtnRows,nNewPtnCols,
				nDataType,
				nLevel,
				&pPtnPyd,&nPtnPydRows,&nPtnPydCols);

		if(bMatched==FALSE)
		{
			nX0=nPtnPydCols/2;
			nY0=nPtnPydRows/2;
			nHeight=nImgPydRows-nPtnPydRows/2;
			nWidth=nImgPydCols-nPtnPydCols/2;
		}
		else
		{
			nX0=(int)(X*(double)nImgPydCols/(double)nImgPydColsPre+0.5)-10;
			nY0=(int)(Y*(double)nImgPydRows/(double)nImgPydRowsPre+0.5)-10;
			nHeight=21;
			nWidth=21;
		}

		bMatched=FALSE;
		if(Match(pImgPyd,nImgPydRows,nImgPydCols,
			pPtnPyd,nPtnPydRows,nPtnPydCols,
			nDataType,
			nX0,nY0,nHeight,nWidth,
			&X,&Y,&Coef,
			pl==1?TRUE:FALSE)==TRUE)
		{
			bMatched=TRUE;

			nImgPydRowsPre=nImgPydRows;
			nImgPydColsPre=nImgPydCols;
		}

		delete [] pImgPyd; pImgPyd=NULL;
		delete [] pPtnPyd; pPtnPyd=NULL;

		//��������ϲ�������ϲ���ƥ�䵽ͬ��㣬�򷵻�֮����ֹ��������²�ƥ���˷�ʱ��
		if(bMatched==FALSE)
		{
			break;
		}
	}

	delete [] pNewPattern; pNewPattern=NULL;

	*px=X;
	*py=Y;
	*pCoef=Coef;

	return bMatched==TRUE?S_OK:S_FALSE;
}
Exemplo n.º 14
0
int
main(int argc, char **argv)
{
	FILE *infile, *outfile;
	short *inbuf, *outbuf;
	int inbufsize, outbufsize;
	int argnext, incount, outcount, starttime;
	int nread, ninput, noutput, nwanted, nsaved;
	float calctime, audiotime;
	void *inst;	/* resampler instance */

	/* command-line switches */
	argnext = ParseArgs(argc, argv);
	if (argc - argnext != 2)
		Usage(argv[0]);

	/* open files */
	if ((infile = fopen(argv[argnext++], "rb")) == NULL)
		ERROR("Cannot open infile");
	if ((outfile = fopen(argv[argnext++], "wb")) == NULL)
		ERROR("Cannot open outfile");

	/* create resampler */
	inst = InitResampler(inrate, outrate, chans, quality);
	if (!inst)
		ERROR("InitResampler failed");

	/* determine buffer sizes */
	if (!outmode) {
		/* constant-input */
		inbufsize = nchunk;
		outbufsize = GetMaxOutput(nchunk, inst);
	} else {
		/* constant-output */
		inbufsize = GetMinInput(nchunk, inst);
		outbufsize = nchunk + GetMaxOutput(chans, inst);
	}

	/* allocate buffers */
	inbuf = (short *) malloc(inbufsize * sizeof(short));
	outbuf = (short *) malloc(outbufsize * sizeof(short));
	if (!inbuf || !outbuf)
		ERROR("malloc failed");

	printf("\nConverting %d %s to %d %s (quality=%d %s=%d)\n",
		inrate, chans==2 ? "STEREO" : "MONO",
		outrate, chans==2 ? "STEREO" : "MONO",
		quality, outmode ? "outchunk" : "inchunk", nchunk);

	incount = 0;
	outcount = 0;
	starttime = clock();

	if (outmode) {

/*
 * Process the file, in constant output chunks.
 */
		nsaved = 0;
		for (;;) {

			/* determine the amount of input needed */
			nwanted = MAX(nchunk - nsaved, 0);
			ninput = GetMinInput(nwanted, inst);
			ASSERT(ninput <= inbufsize);

			/* read variable input */
			nread = fread(inbuf, sizeof(short), ninput, infile);
			incount += nread;

			if (nread < ninput)
				break;	/* not enough input */

			/* resample, appending to saved output */
			noutput = Resample(inbuf, nread, outbuf + nsaved, inst);
			outcount += noutput;

			ASSERT(noutput >= nwanted);
			ASSERT((nsaved + noutput) >= nchunk);
			ASSERT((nsaved + noutput) <= outbufsize);
			ASSERT(noutput <= GetMaxOutput(ninput, inst));

			/* write constant output */
			fwrite(outbuf, sizeof(short), nchunk, outfile);

			/* save extra output */
			nsaved += noutput - nchunk;
			ASSERT(nsaved >= 0);
			memcpy(outbuf, outbuf + nchunk, nsaved * sizeof(short));
		}

		/* resample the remaining input */
		noutput = Resample(inbuf, nread, outbuf + nsaved, inst);
		outcount += noutput;

		/* write the remaining output */
		fwrite(outbuf, sizeof(short), nsaved + noutput, outfile);

	} else {

/*
 * Process the file, in constant input chunks.
 */
		for (;;) {

			/* read constant input */
			nread = fread(inbuf, sizeof(short), nchunk, infile);
			incount += nread;

			if (!nread)
				break;	/* done */

			/* resample */
			noutput = Resample(inbuf, nread, outbuf, inst);
			outcount += noutput;
			
			/* write variable output */
			fwrite(outbuf, sizeof(short), noutput, outfile);
		}
	}

	/* print timing info */
	calctime = (clock() - starttime) / (float)CLOCKS_PER_SEC;
	audiotime = outcount / ((float)outrate * chans);
	printf("Processed %0.2fs of audio in %0.2fs ", audiotime, calctime);
	printf("[%0.2f%% realtime]\n", calctime * 100.0f / audiotime);

	FreeResampler(inst);

	free(inbuf);
	free(outbuf);
	fclose(infile);
	fclose(outfile);

	return 0;
}
Exemplo n.º 15
0
SmallImage* SmallImage::GeneratePreviewImage(unsigned int newWidth, unsigned int newHeight, bool bKeepAspect) {
  if (bKeepAspect) AdjustToAspect(newWidth, newHeight);
  SmallImage* preview = new SmallImage(newWidth, newHeight, m_iComponentCount);
  Resample(preview->m_pData, newWidth, newHeight);
  return preview;
}
Exemplo n.º 16
0
void PatchDeformPW::fnResample()
{
	Resample();
}
Exemplo n.º 17
0
void ParticleBelief::Update(int action, OBS_TYPE obs) {
	history_.Add(action, obs);

	vector<State*> updated;
	double total_weight = 0;
	double reward;
	OBS_TYPE o;
	// Update particles
	for (int i = 0; i <particles_.size(); i++) {
		State* particle = particles_[i];
		bool terminal = model_->Step(*particle, Random::RANDOM.NextDouble(),
			action, reward, o);
		double prob = model_->ObsProb(obs, *particle, action);

		if (!terminal && prob) { // Terminal state is not required to be explicitly represented and may not have any observation
			particle->weight *= prob;
			total_weight += particle->weight;
			updated.push_back(particle);
		} else {
			model_->Free(particle);
		}
	}

	logd << "[ParticleBelief::Update] " << updated.size()
		<< " particles survived among " << particles_.size() << endl;
	particles_ = updated;

	// Resample if the particle set is empty
	if (particles_.size() == 0) {
		logw << "Particle set is empty!" << endl;
		if (prior_ != NULL) {
			logw
				<< "Resampling by drawing random particles from prior which are consistent with history"
				<< endl;
			particles_ = Resample(num_particles_, *prior_, history_);
		} else {
			logw
				<< "Resampling by searching initial particles which are consistent with history"
				<< endl;
			particles_ = Resample(num_particles_, initial_particles_, model_,
				history_);
		}

		if (particles_.size() == 0 && state_indexer_ != NULL) {
			logw
				<< "Resampling by searching states consistent with last (action, observation) pair"
				<< endl;
			particles_ = Resample(num_particles_, model_, state_indexer_,
				action, obs);
		}

		if (particles_.size() == 0) {
			logw << "Resampling failed - Using initial particles" << endl;
			for (int i = 0; i < initial_particles_.size(); i ++)
				particles_.push_back(model_->Copy(initial_particles_[i]));
		}
		
		//Update total weight so that effective number of particles are computed correctly 
		total_weight = 0;
                for (int i = 0; i < particles_.size(); i++) {
		    State* particle = particles_[i];
                    total_weight = total_weight + particle->weight;
                }
	}

	
	double weight_square_sum = 0;
	for (int i = 0; i < particles_.size(); i++) {
		State* particle = particles_[i];
		particle->weight /= total_weight;
		weight_square_sum += particle->weight * particle->weight;
	}

	// Resample if the effective number of particles is "small"
	double num_effective_particles = 1.0 / weight_square_sum;
	if (num_effective_particles < num_particles_ / 2.0) {
		vector<State*> new_belief = Belief::Sample(num_particles_, particles_,
			model_);
		for (int i = 0; i < particles_.size(); i++)
			model_->Free(particles_[i]);

		particles_ = new_belief;
	}
}
Exemplo n.º 18
0
// Volume 0-I2X (1)
int CAudioChannel::Start (short nSound, int nSoundClass, fix nVolume, int nPan, int bLooping, 
								  int nLoopStart, int nLoopEnd, int nSoundObj, int nSpeed, 
								  const char *pszWAV, CFixVector* vPos)
{
	CSoundSample*	soundP = NULL;
	int			bPersistent = (nSoundObj > -1) || bLooping || (nVolume > I2X (1));

if (!(pszWAV && *pszWAV && gameOpts->sound.bUseSDLMixer)) {
	if (nSound < 0)
		return -1;
	if (!gameData.pig.sound.nSoundFiles [gameStates.sound.bD1Sound])
		return -1;
	soundP = gameData.pig.sound.sounds [gameStates.sound.bD1Sound] + nSound % gameData.pig.sound.nSoundFiles [gameStates.sound.bD1Sound];
	if (!(soundP->data [soundP->bCustom].Buffer () && soundP->nLength [soundP->bCustom]))
		return -1;
	}
if (m_info.bPlaying) {
	m_info.bPlaying = 0;
	if (m_info.nSoundObj > -1)
		audio.EndSoundObject (m_info.nSoundObj);
	if (soundQueue.Channel () == audio.FreeChannel ())
		soundQueue.End ();
	}
#if USE_OPENAL
if (m_info.source == 0xFFFFFFFF) {
	CFloatVector	fPos;

	DigiALError ();
	alGenSources (1, &m_info.source);
	if (DigiALError ())
		return -1;
	alSourcei (m_info.source, AL_BUFFER, soundP->buffer);
	if (DigiALError ())
		return -1;
	alSourcef (m_info.source, AL_GAIN, ((nVolume < I2X (1)) ? X2F (nVolume) : 1) * 2 * X2F (m_info.nVolume));
	alSourcei (m_info.source, AL_LOOPING, (ALuint) ((nSoundObj > -1) || bLooping || (nVolume > I2X (1))));
	fPos.Assign (vPos ? *vPos : OBJECTS [LOCALPLAYER.nObject].nPosition.vPos);
	alSourcefv (m_info.source, AL_POSITION, reinterpret_cast<ALfloat*> (fPos));
	alSource3f (m_info.source, AL_VELOCITY, 0, 0, 0);
	alSource3f (m_info.source, AL_DIRECTION, 0, 0, 0);
	if (DigiALError ())
		return -1;
	alSourcePlay (m_info.source);
	if (DigiALError ())
		return -1;
	}
#endif
#if USE_SDL_MIXER
if (gameOpts->sound.bUseSDLMixer) {
	if (m_info.mixChunkP) {
		Mix_HaltChannel (m_info.nChannel);
		if (m_info.bBuiltIn)
			m_info.bBuiltIn = 0;
		else
			Mix_FreeChunk (m_info.mixChunkP);
		m_info.mixChunkP = NULL;
		}
	}
#endif
if (m_info.bResampled) {
	m_info.sample.Destroy ();
	m_info.bResampled = 0;
	}
#if USE_SDL_MIXER
if (gameOpts->sound.bUseSDLMixer) {
	//resample to two channels
	m_info.nChannel = audio.FreeChannel ();
	if (pszWAV && *pszWAV) {
		if (!(m_info.mixChunkP = LoadAddonSound (pszWAV, &m_info.bBuiltIn)))
			return -1;
		}
	else {
		int l;
		if (soundP->bHires) {
			l = soundP->nLength [soundP->bCustom];
			m_info.sample.SetBuffer (soundP->data [soundP->bCustom].Buffer (), 1, l);
			m_info.mixChunkP = Mix_QuickLoad_WAV (reinterpret_cast<Uint8*> (m_info.sample.Buffer ()));
			}
		else {
			if (gameOpts->sound.bHires [0])
				return -1;	//cannot mix hires and standard sounds
			l = Resample (soundP, gameStates.sound.bD1Sound && (gameOpts->sound.digiSampleRate != SAMPLE_RATE_11K), songManager.MP3 ());
			if (l <= 0)
				return -1;
			if (nSpeed < I2X (1))
				l = Speedup (soundP, nSpeed);
#if MAKE_WAV
			m_info.mixChunkP = Mix_QuickLoad_WAV (reinterpret_cast<Uint8*> (m_info.sample.Buffer ()));
#else
			m_info.mixChunkP = Mix_QuickLoad_RAW (reinterpret_cast<Uint8*> (m_info.sample.Buffer ()), l);
#endif
			}
		}
	Mix_VolPan (m_info.nChannel, nVolume, nPan);
	Mix_PlayChannel (m_info.nChannel, m_info.mixChunkP, bLooping ? -1 : nLoopEnd - nLoopStart);
	}
else 
#else
if (pszWAV && *pszWAV)
	return -1;
#endif
 {
	if (gameStates.sound.bD1Sound && (gameOpts->sound.digiSampleRate != SAMPLE_RATE_11K)) {
		int l = Resample (soundP, 0, 0);
		if (l <= 0)
			return -1;
		m_info.nLength = l;
		}
	else {
		m_info.sample.SetBuffer (soundP->data [soundP->bCustom].Buffer (), 1, m_info.nLength = soundP->nLength [soundP->bCustom]);
		}
	if (nSpeed < I2X (1))
		Speedup (soundP, nSpeed);
	}
m_info.nVolume = FixMul (audio.Volume (), nVolume);
m_info.nPan = nPan;
m_info.nPosition = 0;
m_info.nSoundObj = nSoundObj;
m_info.nSoundClass = nSoundClass;
m_info.bLooped = bLooping;
#if USE_OPENAL
m_info.loops = bLooping ? -1 : nLoopEnd - nLoopStart + 1;
#endif
m_info.nSound = nSound;
m_info.bPersistent = 0;
m_info.bPlaying = 1;
m_info.bPersistent = bPersistent;
return audio.FreeChannel ();
}
Exemplo n.º 19
0
////////////////////////////////////////////////////
// 功能: 写入空数据,补齐缓冲区指针
// 输入: 
// 输出:
// 返回: 
// 说明: 
////////////////////////////////////////////////////
int DacWriteEnd(HANDLE hdac, int terminate)
{
	PDAC_DEVICE dac;
	PRESAMPLE presample;
	short *dst;
	volatile BYTE *flag;
	int offset;

	// 获取设备对象
	dac = (PDAC_DEVICE)hdac;
	if(dac == NULL)
		return -1;
	if( terminate )
		return 0;

	// 获取写缓冲区指针
	presample = &dac->Resample;

	offset = presample->WriteOffset;
	if( dac->Samprate != DAC_SAMPLE_RATIO )
	{
		AUDIO_FILTER Filter;
		int size;
		int wsize, rsize;
		int error_delay;
		short *src;
		Filter.iBuf  = NULL;
		Filter.iSize = 0;
		Filter.oBuf  = dac->pSamplerate;
		Filter.oSize = (4*FILTER_PCMBUF_SIZE*DAC_SAMPLE_RATIO)/dac->Samprate+512;
		size = Resample(dac->hSample,&Filter);
		kdebug(mod_audio, PRINT_INFO, "last resample size:%d\n", size);
		src = dac->pSamplerate;

		while(size)
		{
			wsize = (DAC_PCMBUF_SIZE - offset);
			rsize = size;
			dst = presample->Buf[presample->WriteBuf] + offset / sizeof(short);
			flag = &presample->BufFlag[presample->WriteBuf];

			error_delay = 0;
			while((*flag != DAC_BUF_WRITE) )
			{
				sTimerSleep(10, NULL);
				error_delay++;
				if( error_delay >= 1000 )
				{
					kdebug(mod_audio, PRINT_ERROR, "have't action for dma 10S\n");
					GetDmaInfo();
					SetMuteMode(0);
					if( error_delay > 1005 )
						return 0;
				}
			}

			DacPcmQueue(dst, src, &wsize, &rsize, dac->Channel);

			size -= rsize;
			src += rsize / sizeof(short);
			offset += wsize;

			if(offset == DAC_PCMBUF_SIZE)
			{
				// 设置变量
				kMutexWait(hDacMutex);
				if(++presample->WriteBuf == MAX_PCMBUFS)
					presample->WriteBuf = 0;
				*flag = DAC_BUF_READ;
				kMutexRelease(hDacMutex);
				offset = 0;
			}
			presample->WriteOffset = offset;
		}
	}

	if(offset != 0)
	{
		dst = presample->Buf[presample->WriteBuf] + offset / sizeof(short);
		flag = &presample->BufFlag[presample->WriteBuf];
		// 清除缓冲区内容	
		kmemset(dst, 0x00, DAC_PCMBUF_SIZE-offset);

		// 设置变量
		kMutexWait(hDacMutex);
		if(++presample->WriteBuf == MAX_PCMBUFS)
			presample->WriteBuf = 0;
		*flag = DAC_BUF_READ;
		presample->WriteOffset = 0;
		kMutexRelease(hDacMutex);
	}

	// 用于声音合成时的强制同步, 表示这个声音的缓冲数量不会再增加了.
	dac->fThreadStart = 2;

	// 等待缓冲区中的PCM输出完毕
	DacWaitWriteEnd(presample);
	
	return DAC_PCMBUF_SIZE-offset;
}
Exemplo n.º 20
0
/*virtual*/ void CMainWnd::WindowMessage(int nMsg, int nParam /*=0*/)
{
//	BIOS::LCD::Printf( 0, 0, RGB565(ff0000), RGB565(ffffff), "%d", BIOS::ADC::GetState() );
	if ( nMsg == WmTick )
	{
		if ( m_bSleeping )
			return;

		m_Mouse.Hide();
		if ( m_Mouse.Clicked() )
			OnMouseClick();

		// timers update
		CWnd::WindowMessage( nMsg, nParam );
		bool bEnableSdk = Settings.Runtime.m_bUartSdk ? true : false;

#ifdef ENABLE_MONITOR
		// When the user is in UART monitor screen, do not intercept UART traffic
		if ( MainWnd.m_wndToolBar.GetCurrentLayout() == &MainWnd.m_wndUserCWndUserMonitor )
			bEnableSdk = false;
#endif

#ifdef ENABLE_MODULE_GPIOTEST
		if ( MainWnd.m_wndToolBar.GetCurrentLayout() == &MainWnd.m_wndUserCWndGpioTest )
			bEnableSdk = false;
#endif

		if ( bEnableSdk )
			SdkUartProc();

		if ( (Settings.Trig.Sync != CSettings::Trigger::_None) && BIOS::ADC::Enabled() && BIOS::ADC::Ready() )
		{
			// ADC::Ready means that the write pointer is at the end of buffer, we can restart sampler
			BIOS::ADC::Copy( BIOS::ADC::GetCount() );
			BIOS::ADC::Restart();
			Resample();

			// trig stuff
			m_lLastAcquired = BIOS::SYS::GetTick();
			if ( BIOS::ADC::Enabled() && Settings.Trig.Sync == CSettings::Trigger::_Single )
			{
				BIOS::ADC::Enable( false );
				Settings.Trig.State = CSettings::Trigger::_Stop;
				if ( m_wndMenuInput.m_itmTrig.IsVisible() )
					m_wndMenuInput.m_itmTrig.Invalidate();
			}

			// broadcast message for windows that process waveform data
			WindowMessage( CWnd::WmBroadcast, ToWord('d', 'g') );
		}
		m_Mouse.Show();
		return;
	}

	if ( nMsg == WmKey )
	{
		if ( m_bSleeping )
		{
			SetTimer( 200 );
			m_bSleeping = false;
			BIOS::SYS::Standby( FALSE );

			CCoreOscilloscope::ConfigureAdc();
			CCoreGenerator::Update();
			m_wndMessage.Hide();
			Invalidate();

			for ( int i = 0; i < Settings.Runtime.m_nBacklight; i++)
			{
				BIOS::SYS::SetBacklight( i );
				BIOS::SYS::DelayMs(10);
			}

			m_nLastKey = BIOS::SYS::GetTick();
			CCoreSettings::Update();	// display backlight
			return;
		}

		m_nLastKey = BIOS::SYS::GetTick();

		if ( nParam & ( BIOS::KEY::KeyFunction | BIOS::KEY::KeyFunction2 | BIOS::KEY::KeyS2 | BIOS::KEY::KeyS1 ) )
		{
			m_Mouse.Hide();
			if ( nParam == BIOS::KEY::KeyFunction )
				CMainWnd::CallShortcut(Settings.Runtime.m_nShortcutCircle);

			if ( nParam == BIOS::KEY::KeyFunction2 )
				CMainWnd::CallShortcut(Settings.Runtime.m_nShortcutTriangle);

			if ( nParam == BIOS::KEY::KeyS2 )
				CMainWnd::CallShortcut(Settings.Runtime.m_nShortcutS2);

			if ( nParam == BIOS::KEY::KeyS1 )
				CMainWnd::CallShortcut(Settings.Runtime.m_nShortcutS1);
			m_Mouse.Show();
			return;
		}
	}

	m_Mouse.Hide();
	CWnd::WindowMessage( nMsg, nParam );
	m_Mouse.Show();
}
Exemplo n.º 21
0
void AudioProcessor::Flush()
{
	if (m_buffer_offset) {
		Resample();
	}
}
Exemplo n.º 22
0
////////////////////////////////////////////////////
// 功能: 
// 输入: 
// 输出:
// 返回: 
// 说明: 
////////////////////////////////////////////////////
int DacWrite(HANDLE hdac, short *src, int len)
{
	PDAC_DEVICE dac;
	AUDIO_FILTER Filter;
	PRESAMPLE presample;
	short *dst,*pcm_src;
	volatile BYTE *flag;
	int wsize, rsize,error_delay;
	int offset,fltr_in;
	int len_bak,pcm_in,wsola_in,start_flag;
	DWORD nWsolaSize;

	// 获取设备对象
	dac = (PDAC_DEVICE)hdac;
	if(dac == NULL)
		return -1;

	presample = &dac->Resample;
	start_flag = dac->fThreadStart;

	len_bak = len;
	dst = NULL;
	offset = 0;
	wsize = 0;
	rsize = 0;
	pcm_src = src;

#if defined(DAC_SAVE_PCM)
	kmemcpy(&dac_source_buf[dac_source_offset],(BYTE*)src,len);
	dac_source_offset += len;
	if( dac_source_offset >= 2 * 1024 * 1024 )
		dac_source_offset = 0;
#endif

	while(len)
	{
		if( dac->WsolaBuf && dac->hWsola )
		{	//调节语速
			wsola_in = (len > FILTER_PCMBUF_SIZE) ? FILTER_PCMBUF_SIZE : len;
			Filter.iBuf = src;
			Filter.iSize = wsola_in;
			Filter.oBuf = dac->WsolaBuf;
			Filter.oSize = WAOLA_PCM_BUF_SIZE;
			WsolaConvert(dac->hWsola,&Filter);
			nWsolaSize = Filter.oSize;

			pcm_in = 0;
			if( nWsolaSize )
			{
				if( dac->Samprate != DAC_SAMPLE_RATIO )
				{
					// 重采样处理
					Filter.iBuf  = dac->WsolaBuf;
					Filter.iSize = nWsolaSize;
					Filter.oBuf  = dac->pSamplerate;
					Filter.oSize = (4*FILTER_PCMBUF_SIZE*DAC_SAMPLE_RATIO)/dac->Samprate+512;	//((DAC_SAMPLE_RATIO * fltr_in) / dac->Samprate) & 0xfffe;	//
					pcm_in = Resample(dac->hSample,&Filter);
					pcm_src = dac->pSamplerate;
				}
				else
				{
					pcm_in  = nWsolaSize;
					pcm_src = dac->WsolaBuf;
				}
			}

			len -= wsola_in;
			src += wsola_in/sizeof(short);
		}
		else if( dac->Samprate != DAC_SAMPLE_RATIO)
		{
			// 重采样处理
			fltr_in = (len > FILTER_PCMBUF_SIZE) ? FILTER_PCMBUF_SIZE : len;
			Filter.iBuf  = src;
			Filter.iSize = fltr_in;
			Filter.oBuf  = dac->pSamplerate;
			Filter.oSize = (4*FILTER_PCMBUF_SIZE*DAC_SAMPLE_RATIO)/dac->Samprate+512;	//((DAC_SAMPLE_RATIO * fltr_in) / dac->Samprate) & 0xfffe;	//
			pcm_in = Resample(dac->hSample,&Filter);
			pcm_src = dac->pSamplerate;
			len -= fltr_in;
			src += fltr_in/sizeof(short);
		}
		else
		{
			pcm_src = src;
			pcm_in = len;
			len = 0;
		}

		// 把经过Filter后的数据写入PCM缓冲区
		offset = presample->WriteOffset;
		while(pcm_in)
		{
			// 获取写缓冲区指针
			dst = presample->Buf[presample->WriteBuf] + offset / sizeof(short);
			flag = &presample->BufFlag[presample->WriteBuf];

			// 获取可写字节数据
			if(offset != 0)
				wsize = (DAC_PCMBUF_SIZE - offset);
			else
				wsize = DAC_PCMBUF_SIZE;
			rsize = pcm_in;

			// 等待当前缓冲区可写
			error_delay = 0;
			while((*flag != DAC_BUF_WRITE) )
			{
				sTimerSleep(10, NULL);
				error_delay++;
				if( error_delay >= 1000 )
				{
					kdebug(mod_audio, PRINT_ERROR, "have't action for dma 10S\n");
					GetDmaInfo();
					SetMuteMode(0);
					if( error_delay > 1005 )
						return 0;
				}
			}

			// 写入数据到BUF
			DacPcmQueue(dst, pcm_src, &wsize, &rsize, dac->Channel);

			// 准备循环条件
			pcm_in -= rsize;
			pcm_src += rsize/sizeof(short);
			offset += wsize;
			if(offset == DAC_PCMBUF_SIZE)
			{
				kMutexWait(hDacMutex);
				offset = 0;
				if(++presample->WriteBuf == MAX_PCMBUFS)
					presample->WriteBuf = 0;
				dac->fThreadStart = 1;
				*flag = DAC_BUF_READ;
				kMutexRelease(hDacMutex);
			}
			presample->WriteOffset = offset;
		}	
	}


	if( start_flag == 0 && dac->fThreadStart == 1 )
	{
		//kprintf("dac write sleep\n");
		sTimerSleep(20, NULL);
	}
	return len_bak;
}