Exemplo n.º 1
0
        public int Read(AudioBuffer buff, int maxLength)
        {
            buff.Prepare(this, maxLength);

            byte[] bytes     = buff.Bytes;
            int    byteCount = (int)buff.ByteLength;
            int    pos       = 0;

            while (pos < byteCount)
            {
                int len = _IO.Read(bytes, pos, byteCount - pos);
                if (len <= 0)
                {
                    if ((pos % PCM.BlockAlign) != 0 || _sampleLen >= 0)
                    {
                        throw new Exception("Incomplete file read.");
                    }
                    buff.Length = pos / PCM.BlockAlign;
                    _samplePos += buff.Length;
                    _sampleLen  = _samplePos;
                    return(buff.Length);
                }
                pos += len;
            }
            _samplePos += buff.Length;
            return(buff.Length);
        }
Exemplo n.º 2
0
 public int Write(AudioBuffer buff)
 {
     if (_writeBuffer.Size < _writeBuffer.Length + buff.Length)
     {
         AudioBuffer realloced = new AudioBuffer(PCM, _writeBuffer.Size + buff.Size);
         realloced.Prepare(_writeBuffer, 0, _writeBuffer.Length);
         _writeBuffer = realloced;
     }
     if (_writeBuffer.Length == 0)
     {
         _writeBuffer.Prepare(buff, 0, buff.Length);
     }
     else
     {
         _writeBuffer.Load(_writeBuffer.Length, buff, 0, buff.Length);
         _writeBuffer.Length += buff.Length;
     }
     lock (this)
     {
         if (!_haveData)
         {
             AudioBuffer temp = _writeBuffer;
             _writeBuffer        = _readBuffer;
             _writeBuffer.Length = 0;
             _readBuffer         = temp;
             _haveData           = true;
             Monitor.Pulse(this);
         }
     }
     return(_writeBuffer.Length);
 }
Exemplo n.º 3
0
		public void SOXResamplerConstructorTest()
		{
			AudioPCMConfig inputPCM = new AudioPCMConfig(32, 1, 44100);
			AudioPCMConfig outputPCM = new AudioPCMConfig(32, 1, 48000);
			SOXResamplerConfig cfg;
			cfg.Quality = SOXResamplerQuality.Very;
			cfg.Phase = 50;
			cfg.AllowAliasing = false;
			cfg.Bandwidth = 0;
			SOXResampler resampler = new SOXResampler(inputPCM, outputPCM, cfg);
			AudioBuffer src = new AudioBuffer(inputPCM, 400 * inputPCM.SampleRate / 1000);
			AudioBuffer dst = new AudioBuffer(outputPCM, src.Size * 3);
			int offs = 0;
			double delta = 0;
			for (int i = 0; i < 100; i++)
			{
				src.Prepare(-1);
				for (int j = 0; j < src.Size; j++)
					src.Float[j, 0] = (float)Math.Sin((i * src.Size + j) * Math.PI / 44100);
				src.Length = src.Size;
				resampler.Flow(src, dst);
				for (int j = 0; j < dst.Length; j++)
					delta += dst.Float[j, 0] - Math.Sin((offs + j) * Math.PI / 48000);
				offs += dst.Length;
			}
			Assert.IsTrue(Math.Abs(delta) < 0.00001, "Error too large");
		}
Exemplo n.º 4
0
		public void BytesTest()
		{
			AudioBuffer target = new AudioBuffer(AudioPCMConfig.RedBook, 1);
			target.Prepare(testSamples, testSamples.GetLength(0));
			CollectionAssert.AreEqual(testBytes, target.Bytes, "CUETools.Codecs.AudioBuffer.Bytes was not set correctly.");
			target.Prepare(testSamples2, testSamples2.GetLength(0));
			CollectionAssert.AreEqual(testBytes2, target.Bytes, "CUETools.Codecs.AudioBuffer.Bytes was not set correctly.");
		}
Exemplo n.º 5
0
		public static void MyClassInitialize(TestContext testContext)
		{
			toc = new CDImageLayout(1, 1, 1, string.Format("0 {0}", (finalSampleCount / 588).ToString()));
			ar = new AccurateRipVerify(toc, null);
			ar2 = new AccurateRipVerify(toc, null);
			ar3 = new AccurateRipVerify(toc, null);

			new Random(2423).NextBytes(wav);
			new Random(2423).NextBytes(wav2);
			Random rnd = new Random(987);
			for (int i = 0; i < stride / 4; i++ )
				wav2[(int)(rnd.NextDouble() * (wav2.Length - 1))] = (byte)(rnd.NextDouble() * 255);

			AudioBuffer buff = new AudioBuffer(AudioPCMConfig.RedBook, 0);
			CDRepairEncode encode = new CDRepairEncode(ar, stride, npar, false, true);
			buff.Prepare(wav, finalSampleCount);
			ar.Init(toc);
			ar.Write(buff);
			ar.Close(); 
			parity = encode.Parity;
			crc = encode.CRC;

			decode = new CDRepairEncode(ar2, stride, npar, true, false);
			buff.Prepare(wav2, finalSampleCount);
			ar2.Init(toc);
			ar2.Write(buff);
			ar2.Close(); 

			int actualOffset;
			bool hasErrors;
			decode.FindOffset(npar, parity, 0, crc, out actualOffset, out hasErrors);
			fix = decode.VerifyParity(parity, actualOffset);

			decode2 = new CDRepairEncode(ar3, stride, npar, true, false);
			ar3.Init(toc);
			buff.Prepare(new byte[offset * 4], offset);
			ar3.Write(buff);
			buff.Prepare(wav2, finalSampleCount - offset);
			ar3.Write(buff);
			ar3.Close();
			decode2.FindOffset(npar, parity, 0, crc, out actualOffset, out hasErrors);
			fix2 = decode2.VerifyParity(parity, actualOffset);
		}
Exemplo n.º 6
0
        public int Read(AudioBuffer buff, int maxLength)
        {
            Go();

            bool needToCopy = false;

            if (_bufferPos != 0)
            {
                needToCopy = true;
            }
            else
            {
                lock (this)
                {
                    while (!_haveData && _ex == null)
                    {
                        Monitor.Wait(this);
                    }
                    if (_ex != null)
                    {
                        throw _ex;
                    }
                    if (_bufferPos == 0 && (maxLength < 0 || _readBuffer.Length <= maxLength))
                    {
                        buff.Swap(_readBuffer);
                        _haveData = false;
                        Monitor.Pulse(this);
                    }
                    else
                    {
                        needToCopy = true;
                    }
                }
            }
            if (needToCopy)
            {
                buff.Prepare(_readBuffer, _bufferPos, maxLength);
                _bufferPos += buff.Length;
                if (_bufferPos == _readBuffer.Length)
                {
                    _bufferPos = 0;
                    lock (this)
                    {
                        _haveData = false;
                        Monitor.Pulse(this);
                    }
                }
            }
            _samplePos += buff.Length;
            return(buff.Length);
        }
Exemplo n.º 7
0
 public void Write(AudioBuffer buff)
 {
     if (buff.Length == 0)
     {
         return;
     }
     buff.Prepare(this);
     if (!_headersWritten)
     {
         WriteHeaders();
     }
     _IO.Write(buff.Bytes, 0, buff.ByteLength);
     _sampleLen += buff.Length;
 }
Exemplo n.º 8
0
        public int Read(AudioBuffer result, int maxLength)
        {
            if (maxLength > (BufferSize - mixoffs) || maxLength < 0)
                maxLength = (BufferSize - mixoffs);

            result.Prepare(maxLength);

            if (mixbuff == null)
                mixbuff = LockFilledBuffer();

            float sumVolume = 0.0f;
            for (int iSource = 0; iSource < mixbuff.source.Length; iSource++)
                if (mixbuff.filled[iSource])
                    sumVolume += mixbuff.volume[iSource];
            for (int iSource = 0; iSource < mixbuff.source.Length; iSource++)
                volume[iSource] = mixbuff.filled[iSource] ? mixbuff.volume[iSource] / Math.Max(1.0f, sumVolume) : 0.0f;
            for (int iSmp = 0; iSmp < result.Length; iSmp++)
            {
                for (int iChan = 0; iChan < result.PCM.ChannelCount; iChan++)
                {
                    float sample = 0.0f;
                    for (int iSource = 0; iSource < mixbuff.source.Length; iSource++)
                        sample += mixbuff.source[iSource].Float[mixoffs + iSmp, iChan] * volume[iSource];
                    result.Float[iSmp, iChan] = sample;
                }
            }
            mixoffs += result.Length;
            if (mixoffs == BufferSize)
            {
                UnlockFilledBuffer(mixbuff);
                mixbuff = null;
                mixoffs = 0;
            }
            samplePos += result.Length;

            if (AudioRead != null)
            {
                audioReadArgs.source = this;
                audioReadArgs.buffer = result;
                AudioRead(this, audioReadArgs);
            }

            return result.Length;
        }
Exemplo n.º 9
0
		public void Flow(AudioBuffer input, AudioBuffer output)
		{
			if (input.PCM.SampleRate != inputPCM.SampleRate || output.PCM.SampleRate != outputPCM.SampleRate ||
				input.PCM.ChannelCount != inputPCM.ChannelCount || output.PCM.ChannelCount != outputPCM.ChannelCount)
				throw new NotSupportedException();
			if (rateUp2 == null)
			{
				output.Prepare(-1);
				int odone = output.Size;
				for (int channel = 0; channel < inputPCM.ChannelCount; channel++)
				{
					rate[channel].input(input.Float, channel, input.Length);
					rate[channel].process();
					rate[channel].output(output.Float, channel, ref odone);
				}
				output.Length = odone;
			}
			else
				throw new NotSupportedException();
		}
Exemplo n.º 10
0
        public int Read(AudioBuffer buffer, int maxLength)
        {
            buffer.Prepare(this, maxLength);
            int samplesCopied = 0;
            int bytesCopied = 0;

            Action copyBuffer = () =>
            {
                if (this.audioBuffer.Length > this.audioBufferOffset)
                {
                    int samplesToCopy = Math.Min(maxLength, this.audioBuffer.Length - this.audioBufferOffset);
                    int bytesToCopy = samplesToCopy * this.pcm.BlockAlign;

                    Array.Copy(this.audioBuffer.Bytes, this.audioBufferOffset * this.pcm.BlockAlign, buffer.Bytes, bytesCopied, bytesToCopy);

                    this.audioBufferOffset += samplesToCopy;
                    maxLength -= samplesToCopy;
                    samplesCopied += samplesToCopy;
                    bytesCopied += bytesToCopy;
                }
            };
            copyBuffer();

            while (maxLength > 0)
            {
                if (FLAC__stream_decoder_get_state(this.handle) == FlacDecoderState.EndOfStream)
                {
                    break;
                }
                if (!FLAC__stream_decoder_process_single(this.handle))
                {
                    throw new FlacException("Error processing frame.");
                }
                copyBuffer();
            }

            return samplesCopied;
        }
Exemplo n.º 11
0
		public unsafe int Read(AudioBuffer buff, int maxLength)
		{
			if (_toc == null)
				throw new ReadCDException("Read: invalid TOC");
			buff.Prepare(this, maxLength);
			if (Position >= Length)
				return 0;
			if (_sampleOffset >= Length)
			{
				for (int i = 0; i < buff.ByteLength; i++)
					buff.Bytes[i] = 0;
				_sampleOffset += buff.Length;
				return buff.Length; // == Remaining
			}
			if (_sampleOffset < 0)
			{
				buff.Length = Math.Min(buff.Length, -_sampleOffset);
				for (int i = 0; i < buff.ByteLength; i++)
					buff.Bytes[i] = 0;
				_sampleOffset += buff.Length;
				return buff.Length;
			}
			PrefetchSector(/*(int)_toc[_toc.FirstAudio][0].Start +*/ (_sampleOffset / 588));
			buff.Length = Math.Min(buff.Length, (int)Length - _sampleOffset);
			buff.Length = Math.Min(buff.Length, _currentEnd * 588 - _sampleOffset);
			if ((_sampleOffset - _currentStart * 588) == 0 && (maxLength < 0 || (_currentEnd - _currentStart) * 588 <= buff.Length))
			{
				buff.Swap(currentData);
				_currentStart = -1;
				_currentEnd = -1;
			} 
			else
				fixed (byte* dest = buff.Bytes, src = &currentData.Bytes[(_sampleOffset - _currentStart * 588) * 4])
					AudioSamples.MemCpy(dest, src, buff.ByteLength);
			_sampleOffset += buff.Length;
			return buff.Length;
		}
Exemplo n.º 12
0
        public void Write(AudioBuffer buff)
        {
            if (!inited)
            {
                

                if (!m_settings.IsValid())
                    throw new Exception("unsupported encoder settings");
                inited = true;
                int header_size = flake_encode_init();
                _IO.Write(header, 0, header_size);
                if (_IO.CanSeek)
                    first_frame_offset = _IO.Position;
            }

            buff.Prepare(this);

            int pos = 0;
            while (pos < buff.Length)
            {
                int block = Math.Min(buff.Length - pos, m_blockSize - samplesInBuffer);

                copy_samples(buff.Samples, pos, block);

                pos += block;

                while (samplesInBuffer >= m_blockSize)
                    output_frame();
            }

            if (md5 != null)
                md5.Append(buff.Bytes.AsBuffer(0, buff.ByteLength));
        }
Exemplo n.º 13
0
        public void Write(AudioBuffer buffer)
        {
            if (this.closed)
            {
                throw new InvalidOperationException("Writer already closed.");
            }

            buffer.Prepare(this);

            this.EnsureInitialized();

            this.EnsureOutputBufferSize(buffer.Length * 5 / 4 + 7200);

            byte[] bytes = buffer.Bytes;

            int result;
            unsafe
            {
                fixed (byte* bytesPtr = bytes)
                {
                    fixed (byte* outputBufferPtr = this.outputBuffer)
                    {
                        result = lame_encode_buffer_interleaved(handle, (IntPtr)bytesPtr, buffer.Length, (IntPtr)outputBufferPtr, outputBuffer.Length);
                    }
                }
            }

            if (result < 0)
            {
                switch (result)
                {
                    case -1:
                        throw new LameException("Output buffer is too small");
                    case -2:
                        throw new LameException("malloc problem");
                    case -3:
                        throw new LameException("lame_init_params was not called");
                    case -4:
                        throw new LameException("Psycho acoustic problems");
                    default:
                        throw new LameException("Unknown error");
                }
            }

            if (result > 0)
            {
                this.outputStream.Write(this.outputBuffer, 0, result);
            }
        }
Exemplo n.º 14
0
		public int Read(AudioBuffer buff, int maxLength)
		{
			InitTables();

			buff.Prepare(this, maxLength);

			int offset = 0;
			int sampleCount = buff.Length;

			while (_samplesInBuffer < sampleCount)
			{
				if (_samplesInBuffer > 0)
				{
					deinterlace(buff.Samples, offset, _samplesInBuffer);
					sampleCount -= _samplesInBuffer;
					offset += _samplesInBuffer;
					_samplesInBuffer = 0;
					_samplesBufferOffset = 0;
				}

				int sampleDuration;
				int sampleSize;
				if (_iSample >= _sample_byte_size.Length)
				{
					buff.Length = offset;
					return offset;
				}
				get_sample_info(_iSample, out sampleDuration, out sampleSize);
				_IO.Read(_framesBuffer, 0, sampleSize);
				decodeFrame(sampleSize);
				if (sampleDuration != _samplesInBuffer)
					throw new Exception("sample count mismatch");
				_samplesInBuffer -= _samplesBufferOffset;
				_sampleOffset += _samplesInBuffer;
				_iSample++;
			}

			deinterlace(buff.Samples, offset, sampleCount);
			_samplesInBuffer -= sampleCount;
			_samplesBufferOffset += sampleCount;
			if (_samplesInBuffer == 0)
				_samplesBufferOffset = 0;
			return offset + sampleCount;
		}
		public int Read(AudioBuffer buff, int maxLength)
		{
			buff.Prepare(this, maxLength);

			int buffOffs = 0;
			while (buffOffs < buff.ByteLength)
			{
				if (tempOffs == temp.Length)
				{
					rnd.NextBytes(temp);
					tempOffs = 0;
				}
				int chunk = Math.Min(buff.ByteLength - buffOffs, temp.Length - tempOffs);
				Array.Copy(temp, tempOffs, buff.Bytes, buffOffs, chunk);
				buffOffs += chunk;
				tempOffs += chunk;
			}

			while (this.nextError < this.errors.Length && this.errors[this.nextError] < _sampleOffset + buff.Length)
			{
				for (int i = 0; i < PCM.BlockAlign; i++)
					buff.Bytes[(this.errors[this.nextError] - _sampleOffset) * PCM.BlockAlign + i] ^= (byte)this.rnd2.Next(1, 255);
				this.nextError++;
			}

			_sampleOffset += buff.Length;
			return buff.Length;
		}
Exemplo n.º 16
0
        public void Write(AudioBuffer buffer)
        {
            if (this.closed)
            {
                throw new InvalidOperationException("Writer already closed.");
            }

            buffer.Prepare(this);

            this.EnsureInitialized();

            if (!FLAC__stream_encoder_process_interleaved(this.handle, buffer.Samples, buffer.Length))
            {
                throw new FlacException("Error processing data");
            }
        }
Exemplo n.º 17
0
        public int Read(AudioBuffer buff, int maxLength)
        {
            Go();

            bool needToCopy = false;
            if (_bufferPos != 0)
                needToCopy = true;
            else
                lock (this)
                {
                    while (!_haveData && _ex == null)
                        Monitor.Wait(this);
                    if (_ex != null)
                        throw _ex;
                    if (_bufferPos == 0 && (maxLength < 0 || _readBuffer.Length <= maxLength))
                    {
                        buff.Swap(_readBuffer);
                        _haveData = false;
                        Monitor.Pulse(this);
                    }
                    else
                        needToCopy = true;
                }
            if (needToCopy)
            {
                buff.Prepare(_readBuffer, _bufferPos, maxLength);
                _bufferPos += buff.Length;
                if (_bufferPos == _readBuffer.Length)
                {
                    _bufferPos = 0;
                    lock (this)
                    {
                        _haveData = false;
                        Monitor.Pulse(this);
                    }
                }
            }
            _samplePos += buff.Length;
            return buff.Length;
        }
Exemplo n.º 18
0
		public void Write(AudioBuffer buff)
		{
			if (!inited)
			{
				if (!_pathGiven && sample_count <= 0)
					throw new NotSupportedException("input and output are both pipes");
				if (_IO == null)
					_IO = new FileStream(_path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
				if (_IO != null && !_IO.CanSeek)
					throw new NotSupportedException("stream doesn't support seeking");
				encode_init();
				inited = true;
			}

			buff.Prepare(this);

			int pos = 0;
			int len = buff.Length;
			while (len > 0)
			{
				int block = Math.Min(len, eparams.block_size - samplesInBuffer);

				copy_samples(buff.Samples, pos, block);

				len -= block;
				pos += block;

				while (samplesInBuffer >= eparams.block_size)
					output_frame(eparams.block_size);
			}
		}
Exemplo n.º 19
0
		public unsafe void Write(AudioBuffer buff)
		{
			InitTasks();
			buff.Prepare(this);
			int pos = 0;
			while (pos < buff.Length)
			{
				int block = Math.Min(buff.Length - pos, eparams.block_size * framesPerTask - samplesInBuffer);

				fixed (byte* buf = buff.Bytes)
					AudioSamples.MemCpy(((byte*)task1.clSamplesBytesPtr) + samplesInBuffer * _pcm.BlockAlign, buf + pos * _pcm.BlockAlign, block * _pcm.BlockAlign);
				
				samplesInBuffer += block;
				pos += block;

				int nFrames = samplesInBuffer / eparams.block_size;
				if (nFrames >= framesPerTask)
					do_output_frames(nFrames);
			}
			if (md5 != null)
				md5.TransformBlock(buff.Bytes, 0, buff.ByteLength, null, 0);
		}
Exemplo n.º 20
0
        public int Read(AudioBuffer buff, int maxLength)
        {
            buff.Prepare(this, maxLength);

            int[,] samples = buff.Samples;
            for (int i = 0; i < buff.Length; i++)
                for (int j = 0; j < PCM.ChannelCount; j++)
                    samples[i, j] = _sampleVal;

            _sampleOffset += buff.Length;
            return buff.Length;
        }
Exemplo n.º 21
0
		public unsafe void Write(AudioBuffer sampleBuffer)
		{
			sampleBuffer.Prepare(this);

			int pos = 0;
			fixed (uint* t = Crc32.table)
			fixed (ushort* pte = encodeTable)
			fixed (byte* pSampleBuff = &sampleBuffer.Bytes[0], bpar = parity)
				while (pos < sampleBuffer.Length)
				{
					// Process no more than there is in the buffer, no more than there is in this track, and no more than up to a sector boundary.
					int copyCount = Math.Min(Math.Min(sampleBuffer.Length - pos, (int)_samplesRemTrack), 588 - (int)_sampleCount % 588);
					uint* samples = ((uint*)pSampleBuff) + pos;
                    int currentSample = (int)_sampleCount - 588 * (int)this.TOC.Pregap;
                    int currentPart = currentSample < 0 ? 0 : (currentSample * 2) % stride;
					//ushort* synptr = synptr1 + npar * currentPart;
                    ushort* wr = ((ushort*)bpar) + maxNpar * currentPart;

                    for (int i = Math.Max(0, - currentSample * 2); i < Math.Min(leadin.Length - currentSample * 2, copyCount * 2); i++)
                        leadin[currentSample * 2 + i] = ((ushort*)samples)[i];

					for (int i = Math.Max(0, (int)(_finalSampleCount - _sampleCount) * 2 - leadout.Length); i < copyCount * 2; i++)
					{
						int remaining = (int)(_finalSampleCount - _sampleCount) * 2 - i - 1;
						leadout[remaining] = ((ushort*)samples)[i];
					}

					int offset = _samplesDoneTrack < maxOffset ? _samplesDoneTrack
						: _samplesRemTrack <= maxOffset ? 2 * maxOffset - _samplesRemTrack
						: _samplesDoneTrack >= 445 * 588 && _samplesDoneTrack <= 455 * 588 ? 2 * maxOffset + 1 + _samplesDoneTrack - 445 * 588
						: -1;

					CalculateCRCs(t, wr, pte, samples, copyCount, offset);

					// duplicate prefix to suffix
					if (_samplesDoneTrack < maxOffset && _samplesRemTrack <= maxOffset)
					{
						Array.Copy(_CRC32, _currentTrack * 3 * maxOffset + _samplesDoneTrack,
							_CRC32, _currentTrack * 3 * maxOffset + 2 * maxOffset - _samplesRemTrack,
							copyCount);
						Array.Copy(_CRCWN, _currentTrack * 3 * maxOffset + _samplesDoneTrack,
							_CRCWN, _currentTrack * 3 * maxOffset + 2 * maxOffset - _samplesRemTrack,
							copyCount);
						Array.Copy(_CRCNL, _currentTrack * 3 * maxOffset + _samplesDoneTrack,
							_CRCNL, _currentTrack * 3 * maxOffset + 2 * maxOffset - _samplesRemTrack,
							copyCount);
					}
					// duplicate prefix to pregap
					if (_sampleCount < maxOffset && _currentTrack == 1)
					{
						Array.Copy(_CRC32, _currentTrack * 3 * maxOffset + _samplesDoneTrack,
							_CRC32, _sampleCount,
							copyCount);
						Array.Copy(_CRCWN, _currentTrack * 3 * maxOffset + _samplesDoneTrack,
							_CRCWN, _sampleCount,
							copyCount);
						Array.Copy(_CRCNL, _currentTrack * 3 * maxOffset + _samplesDoneTrack,
							_CRCNL, _sampleCount,
							copyCount);
					}

					pos += copyCount;
					_samplesRemTrack -= copyCount;
					_samplesDoneTrack += copyCount;
					_sampleCount += copyCount;

					while (_samplesRemTrack <= 0)
					{
						if (++_currentTrack > _toc.AudioTracks)
							return;
						_samplesRemTrack = (int)_toc[_currentTrack + _toc.FirstAudio - 1].Length * 588;
						_samplesDoneTrack = 0;
					}
				}
		}
Exemplo n.º 22
0
		new public unsafe void Write(AudioBuffer sampleBuffer)
		{
			if (!verify && !encode)
				return;

			sampleBuffer.Prepare(this);

			if ((sampleBuffer.ByteLength & 1) != 0 || sampleCount + sampleBuffer.Length > finalSampleCount)
				throw new Exception("sampleCount > finalSampleCount");

			fixed (byte* bytes = sampleBuffer.Bytes)
			{
				int offs = 0;
				while (offs < sampleBuffer.Length)
				{
					int currentPart = (sampleCount * 2) % stride;
					int currentStride = (sampleCount * 2) / stride;
					// Process no more than there is in the buffer, and no more than up to a stride boundary.
					int copyCount = Math.Min((sampleBuffer.Length - offs) * 2, stride - currentPart);
					ushort* data = ((ushort*)bytes) + offs * 2;

					if (currentStride < 2)
						for (int pos = 0; pos < copyCount; pos++)
							leadin[sampleCount * 2 + pos] = data[pos];

					if (currentStride >= stridecount)
						for (int pos = 0; pos < copyCount; pos++)
						{
							int remaining = (finalSampleCount - sampleCount) * 2 - pos - 1;
							if (remaining < stride + laststride)
								leadout[remaining] = data[pos];
						}

					if (currentStride >= 1 && currentStride <= stridecount)
					{
						if (npar == 16)
							ProcessStride16(currentStride, currentPart, copyCount, data);
						else if (npar != 8)
							ProcessStride(currentStride, currentPart, copyCount, data);
					}

					sampleCount += copyCount >> 1;
					offs += copyCount >> 1;
				}
			}
		}
Exemplo n.º 23
0
        public int Read(AudioBuffer buff, int maxLength)
        {
            buff.Prepare(this, maxLength);

            byte[] bytes = buff.Bytes;
            int byteCount = (int)buff.ByteLength;
            int pos = 0;

            while (pos < byteCount)
            {
                int len = _IO.Read(bytes, pos, byteCount - pos);
                if (len <= 0)
                {
                    if ((pos % PCM.BlockAlign) != 0 || _sampleLen >= 0)
                        throw new Exception("Incomplete file read.");
                    buff.Length = pos / PCM.BlockAlign;
                    _samplePos += buff.Length;
                    _sampleLen = _samplePos;
                    return buff.Length;
                }
                pos += len;
            }
            _samplePos += buff.Length;
            return buff.Length;
        }
Exemplo n.º 24
0
		new public unsafe void Write(AudioBuffer sampleBuffer)
		{
			sampleBuffer.Prepare(this);

			if ((sampleBuffer.ByteLength & 1) != 0)
				throw new Exception("never happens");

			int firstPos = Math.Max(0, stride - sampleCount * 2 - ActualOffset * 2);
			int lastPos = Math.Min(sampleBuffer.ByteLength >> 1, (finalSampleCount - sampleCount) * 2 - laststride - ActualOffset * 2);

			SortErrors();

			fixed (byte* bytes = sampleBuffer.Bytes)
			fixed (uint* t = Crc32.table)
			{
				ushort* data = (ushort*)bytes;
				for (int pos = firstPos; pos < lastPos; pos++)
				{
					if (sampleCount * 2 + pos == erroffsorted[nexterroff] && nexterroff < erroffsorted.Length)
						data[pos] ^= forneysorted[nexterroff++];
					
					ushort dd = data[pos];
					crc = (crc >> 8) ^ t[(byte)(crc ^ dd)];
					crc = (crc >> 8) ^ t[(byte)(crc ^ (dd >> 8))];
				}
			}
			sampleCount += sampleBuffer.Length;
		}
Exemplo n.º 25
0
        public void Write(AudioBuffer buffer)
        {
            if (this.closed)
            {
                throw new InvalidOperationException("Writer already closed.");
            }

            buffer.Prepare(this);

            if (buffer.PCM.BitsPerSample != 16)
            {
                if (buffer.PCM.BitsPerSample == 24)
                {
                    AudioBuffer newBuffer = new AudioBuffer(new AudioPCMConfig(16, buffer.PCM.ChannelCount, buffer.PCM.SampleRate), buffer.Size);
                    newBuffer.Length = buffer.Length;

                    int length0 = buffer.Samples.GetLength(0);
                    int length1 = buffer.Samples.GetLength(1);
                    for (int i = 0; i < length0; ++i)
                    {
                        for (int j = 0; j < length1; ++j)
                        {
                            newBuffer.Samples[i, j] = buffer.Samples[i, j] >> 8;
                        }
                    }
                    buffer = newBuffer;
                }
                else
                {
                    throw new NotSupportedException("Unsupported bit depth");
                }
            }

            this.EnsureInitialized();

            this.EnsureOutputBufferSize(buffer.Length * 5 / 4 + 7200);

            byte[] bytes = buffer.Bytes;

            int result;
            unsafe
            {
                fixed (byte* bytesPtr = bytes)
                {
                    fixed (byte* outputBufferPtr = this.outputBuffer)
                    {
                        result = lame_encode_buffer_interleaved(handle, (IntPtr)bytesPtr, buffer.Length, (IntPtr)outputBufferPtr, outputBuffer.Length);
                    }
                }
            }

            if (result < 0)
            {
                switch (result)
                {
                    case -1:
                        throw new LameException("Output buffer is too small");
                    case -2:
                        throw new LameException("malloc problem");
                    case -3:
                        throw new LameException("lame_init_params was not called");
                    case -4:
                        throw new LameException("Psycho acoustic problems");
                    default:
                        throw new LameException("Unknown error");
                }
            }

            if (result > 0)
            {
                this.outputStream.Write(this.outputBuffer, 0, result);
            }
        }
Exemplo n.º 26
0
		public void Write(AudioBuffer buff)
		{
			if (!inited)
			{
				if (_IO == null)
					_IO = new FileStream(_path, FileMode.Create, FileAccess.Write, FileShare.Read);
				int header_size = flake_encode_init();
				_IO.Write(header, 0, header_size);
				if (_IO.CanSeek)
					first_frame_offset = _IO.Position;
				inited = true;
			}

			buff.Prepare(this);

			int pos = 0;
			while (pos < buff.Length)
			{
				int block = Math.Min(buff.Length - pos, eparams.block_size - samplesInBuffer);

				copy_samples(buff.Samples, pos, block);

				pos += block;

				while (samplesInBuffer >= eparams.block_size)
					output_frame();
			}

			if (md5 != null)
				md5.TransformBlock(buff.Bytes, 0, buff.ByteLength, null, 0);
		}
Exemplo n.º 27
0
        public void Write(AudioBuffer buffer)
        {
            if (this.closed)
            {
                throw new InvalidOperationException("Writer already closed.");
            }

            buffer.Prepare(this);

            this.EnsureInitialized();

            this.networkStream.Write((int)NetworkMessageType.DataMessage);
            this.networkStream.Write(buffer.ByteLength);
            this.networkStream.Write(buffer.Bytes, 0, buffer.ByteLength);
        }
Exemplo n.º 28
0
 public void Write(AudioBuffer buff)
 {
     if (buff.Length == 0)
         return;
     buff.Prepare(this);
     if (!_headersWritten)
         WriteHeaders();
     _IO.Write(buff.Bytes, 0, buff.ByteLength);
     _sampleLen += buff.Length;
 }
Exemplo n.º 29
0
		public void CDRepairFixWithOffsetTest()
		{
			Assert.IsTrue(fix2.HasErrors);
			Assert.IsTrue(fix2.CanRecover);
			Assert.AreEqual(-offset, fix2.ActualOffset, "wrong offset");

			AudioBuffer buff = new AudioBuffer(AudioPCMConfig.RedBook, 0);
			buff.Prepare(new byte[offset * 4], offset);
			fix2.Write(buff);
			buff.Prepare(wav2, finalSampleCount - offset);
			fix2.Write(buff);
			fix2.Close();

			Assert.AreEqual<uint>(crc, fix2.CRC);
		}
Exemplo n.º 30
0
 public int Write(AudioBuffer buff)
 {
     if (_writeBuffer.Size < _writeBuffer.Length + buff.Length)
     {
         AudioBuffer realloced = new AudioBuffer(pcm, _writeBuffer.Size + buff.Size);
         realloced.Prepare(_writeBuffer, 0, _writeBuffer.Length);
         _writeBuffer = realloced;
     }
     if (_writeBuffer.Length == 0)
         _writeBuffer.Prepare(buff, 0, buff.Length);
     else
     {
         _writeBuffer.Load(_writeBuffer.Length, buff, 0, buff.Length);
         _writeBuffer.Length += buff.Length;
     }
     lock (this)
     {
         if (!_haveData)
         {
             AudioBuffer temp = _writeBuffer;
             _writeBuffer = _readBuffer;
             _writeBuffer.Length = 0;
             _readBuffer = temp;
             _haveData = true;
             Monitor.Pulse(this);
         }
     }
     return _writeBuffer.Length;
 }
Exemplo n.º 31
0
 public int Read(AudioBuffer buff, int maxLength)
 {
     buff.Prepare(this, maxLength);
     while (_samplePos >= nextPos)
     {
         currentSource++;
         if (currentSource >= cueSheet._sources.Count)
         {
             buff.Length = 0;
             return 0;
         }
         if (currentAudio != null)
             currentAudio.Close();
         currentAudio = cueSheet.GetAudioSource(currentSource, false);
         int offset = (int)(_samplePos - nextPos);
         if (offset != 0)
             currentAudio.Position += offset;
         nextPos += cueSheet._sources[currentSource].Length;
     }
     int count = (int)(nextPos - _samplePos);
     if (maxLength >= 0)
         count = Math.Min(count, maxLength);
     count = currentAudio.Read(buff, count);
     _samplePos += count;
     return count;
 }