content: /*
    Copyright (c) 2014, Alberto Gramaglia
  
    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.
  
  */
  
  
  package com.audioneex.audio;
  
  /**
      This naive ring buffer is used by one producer (the audio source)
      and one consumer (the audio processor) that work on continuous
      audio streams, so there is no need for thread synchronization
      facilities.
  */
  
  
  public class BufferQueue
  {
      private AudioBuffer[] mBuffer      = null;
      private long          mConsumed    = 0;
      private long          mProduced    = 0;
      private boolean       mConsumeDone = false;
  
      BufferQueue(){
      	
      }
  
      BufferQueue(int size, AudioFormat format){
          mBuffer = AudioFactory.CreateAudioBuffers(format, size);      
      }
  
      BufferQueue(int size, AudioBuffer buf){
          mBuffer = AudioFactory.CreateAudioBuffers(buf.Format(), size,
                                                    buf.Capacity(),
                                                    buf.SampleRate(),
                                                    buf.Channels(),
                                                    buf.Size());       
      }
  
      public int Size() { return mBuffer.length; }
      public boolean  IsFull() { return Available() == mBuffer.length; }
      public boolean  IsEmpty() { return Available() == 0; }
      public boolean  IsNull() { return mBuffer == null; }
      public long Available() { return (mProduced - mConsumed); }
      
      public AudioBuffer GetHead() { 
      	return (IsFull() ? null : mBuffer[(int) (mProduced % mBuffer.length)]);
      }
      
      public AudioBuffer Push(){
          if(IsFull()) return null;
          AudioBuffer ret = mBuffer[(int) (mProduced % mBuffer.length)];
          mProduced++;
          return ret;    	
      }
  
      public AudioBuffer Pull()
      {
          AudioBuffer b = null;
  
          if(mConsumeDone)
             mConsumed++;
  
          if(!IsEmpty()) {
              b = mBuffer[(int) (mConsumed % mBuffer.length)];
              mConsumeDone = true;
          } else {
              mConsumeDone = false;
          }
  
          return b;    	
      }
  
      public void Reset(){
      	mConsumed = 0;
      	mProduced = 0;
      	mConsumeDone = false;
      	if(mBuffer!=null)
      	   for(int i=0; i<mBuffer.length; i++)
      		   mBuffer[i].Resize(0);
      }
  
  }
  
  