public SilenceGenerator(AudioPCMConfig pcm, long sampleCount, int sampleVal) { this._sampleVal = sampleVal; this._sampleOffset = 0; this._sampleCount = sampleCount; this.pcm = pcm; }
public LAMEEncoder(string path, Stream IO, AudioPCMConfig pcm) { if (pcm.BitsPerSample != 16)// && pcm.BitsPerSample != 32) throw new ArgumentOutOfRangeException("format", "Only 16 & 32 bits samples supported"); _pcm = pcm; _path = path; _IO = IO; }
public LAMEEncoderVBR(string path, AudioPCMConfig pcm) : base(path, null, pcm) { }
public FlakeReader(AudioPCMConfig _pcm) { pcm = _pcm; crc8 = new Crc8(); crc16 = new Crc16(); samplesBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; residualBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; frame = new FlacFrame(PCM.ChannelCount); framereader = new BitReader(); }
public LameWriterVBR(string path, AudioPCMConfig pcm) : base(path, pcm) { }
public LAMEEncoder(string path, AudioPCMConfig pcm) : this(path, null, pcm) { }
public AudioDecoder(DecoderSettings settings, string path, Stream IO) { m_settings = settings; m_path = path; isValid(path); bool pfIsProtected; WMUtils.WMIsContentProtected(path, out pfIsProtected); if (pfIsProtected) { throw new Exception("DRM present"); } WMUtils.WMCreateSyncReader(IntPtr.Zero, Rights.None, out m_syncReader); if (path == null) { m_IO = IO != null ? IO : new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x10000); m_streamWrapper = new StreamWrapper(m_IO); m_syncReader.OpenStream(m_streamWrapper); } else { m_syncReader.Open(path); } var pProfile = (m_syncReader as IWMProfile); int dwStreamCount; pProfile.GetStreamCount(out dwStreamCount); for (int dwIndex = 0; dwIndex < dwStreamCount; dwIndex++) { IWMStreamConfig pConfig = null; pProfile.GetStream(dwIndex, out pConfig); try { Guid guid; pConfig.GetStreamType(out guid); if (MediaType.Audio != guid) { continue; } short wStreamNum; pConfig.GetStreamNumber(out wStreamNum); int dwBitrate = -1; pConfig.GetBitrate(out dwBitrate); var pIWMMediaProps = pConfig as IWMMediaProps; int cbType = 0; pIWMMediaProps.GetMediaType(null, ref cbType); var pMediaType = new AMMediaType(); pMediaType.formatSize = cbType; pIWMMediaProps.GetMediaType(pMediaType, ref cbType); if (pMediaType.formatType != FormatType.WaveEx) { continue; } if (pMediaType.subType != MediaSubType.WMAudio_Lossless) { continue; } m_wStreamNum = wStreamNum; pcm = WaveFormatExtensible.FromMediaType(pMediaType).GetConfig(); break; } finally { Marshal.ReleaseComObject(pConfig); } } if (m_wStreamNum == -1) { throw new Exception("No WMA lossless streams found"); } m_syncReader.SetReadStreamSamples(m_wStreamNum, false); bool pfCompressed; m_syncReader.GetReadStreamSamples(m_wStreamNum, out pfCompressed); if (pfCompressed) { throw new Exception("doesn't decompress"); } m_syncReader.GetOutputNumberForStream(m_wStreamNum, out m_dwAudioOutputNum); IWMOutputMediaProps pProps; m_syncReader.GetOutputProps(m_dwAudioOutputNum, out pProps); try { StringBuilder sName = null; AMMediaType pMediaType = null; int cbType = 0; cbType = 0; pMediaType = null; pProps.GetMediaType(pMediaType, ref cbType); // Get the name of the output we'll be using sName = null; short iName = 0; pProps.GetConnectionName(sName, ref iName); sName = new StringBuilder(iName); pProps.GetConnectionName(sName, ref iName); if (pcm.ChannelCount > 2) { m_syncReader.SetOutputSetting(m_dwAudioOutputNum, Constants.g_wszEnableDiscreteOutput, AttrDataType.BOOL, new byte[] { 1, 0, 0, 0 }, 4); m_syncReader.SetOutputSetting(m_dwAudioOutputNum, Constants.g_wszSpeakerConfig, AttrDataType.DWORD, new byte[] { 0, 0, 0, 0 }, 4); } pMediaType = new AMMediaType(); pMediaType.formatSize = cbType - Marshal.SizeOf(typeof(AMMediaType)); // // Get the value for MediaType // pProps.GetMediaType(pMediaType, ref cbType); try { if (MediaType.Audio != pMediaType.majorType) { throw new Exception("not Audio"); } if (FormatType.WaveEx != pMediaType.formatType) { throw new Exception("not WaveEx"); } var wfe = new WaveFormatExtensible(pcm); Marshal.FreeCoTaskMem(pMediaType.formatPtr); pMediaType.formatPtr = IntPtr.Zero; pMediaType.formatSize = 0; pMediaType.formatPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(wfe)); pMediaType.formatSize = Marshal.SizeOf(wfe); Marshal.StructureToPtr(wfe, pMediaType.formatPtr, false); pProps.SetMediaType(pMediaType); m_syncReader.SetOutputProps(m_dwAudioOutputNum, pProps); } finally { WMUtils.FreeWMMediaType(pMediaType); } } finally { Marshal.ReleaseComObject(pProps); } //try //{ // AttrDataType wmtType; // short cbLength = 0; // short wAnyStream = 0; // var pHeaderInfo = m_syncReader as IWMHeaderInfo; // pHeaderInfo.GetAttributeByName(ref wAnyStream, Constants.g_wszWMDuration, out wmtType, null, ref cbLength); // var pbValue = new byte[cbLength]; // pHeaderInfo.GetAttributeByName(ref wAnyStream, Constants.g_wszWMDuration, out wmtType, pbValue, ref cbLength); // var m_cnsFileDuration = BitConverter.ToInt64(pbValue, 0); // _sampleCount = m_cnsFileDuration * m_pWfx.nSamplesPerSec / 10000000; // // NOT ACCURATE ENOUGH (~1ms precision observed) //} //catch (COMException) //{ //} //try //{ // var pHeaderInfo = m_syncReader as IWMHeaderInfo2; // int nCodec; // pHeaderInfo.GetCodecInfoCount(out nCodec); // for (int wIndex = 0; wIndex < nCodec; wIndex++) // { // CodecInfoType enumCodecType; // short cchName = 0; // short cchDescription = 0; // short cbCodecInfo = 0; // pHeaderInfo.GetCodecInfo(wIndex, ref cchName, null, // ref cchDescription, null, out enumCodecType, // ref cbCodecInfo, null); // var pwszName = new StringBuilder(cchName); // var pwszDescription = new StringBuilder(cchDescription); // var pbCodecInfo = new byte[cbCodecInfo]; // pHeaderInfo.GetCodecInfo(wIndex, ref cchName, pwszName, // ref cchDescription, pwszDescription, out enumCodecType, // ref cbCodecInfo, pbCodecInfo); // if (enumCodecType == CodecInfoType.Audio) // { // // pbCodecInfo = {99,1} ??/ // } // } //} //catch (COMException) //{ //} //int cbMax; //m_syncReader.GetMaxOutputSampleSize(m_dwAudioOutputNum, out cbMax); }
public BE_CONFIG(AudioPCMConfig format) : this(format, 0, 5) { }
public WAVWriterSettings(AudioPCMConfig pcm) : base(pcm) { }
public RemoteWriterBase(IPAddress remoteAddress, Stream output, AudioPCMConfig pcm) { this.remoteEndpoint = new IPEndPoint(remoteAddress, EncodingServer.Port); this.outputStream = output; this.pcm = pcm; }
private void WriteHeaders() { const uint fccRIFF = 0x46464952; const uint fccWAVE = 0x45564157; const uint fccFormat = 0x20746D66; const uint fccData = 0x61746164; bool wavex = (Settings.PCM.BitsPerSample != 16 && Settings.PCM.BitsPerSample != 24) || Settings.PCM.ChannelMask != AudioPCMConfig.GetDefaultChannelMask(Settings.PCM.ChannelCount); hdrLen += 36 + (wavex ? 24 : 0) + 8; uint dataLen = (uint)(_finalSampleCount * Settings.PCM.BlockAlign); uint dataLenPadded = dataLen + (dataLen & 1); _bw.Write(fccRIFF); if (_finalSampleCount <= 0) { _bw.Write((uint)0xffffffff); } else { _bw.Write((uint)(dataLenPadded + hdrLen - 8)); } _bw.Write(fccWAVE); _bw.Write(fccFormat); if (wavex) { _bw.Write((uint)40); _bw.Write((ushort)0xfffe); // WAVEX follows } else { _bw.Write((uint)16); _bw.Write((ushort)1); // PCM } _bw.Write((ushort)Settings.PCM.ChannelCount); _bw.Write((uint)Settings.PCM.SampleRate); _bw.Write((uint)(Settings.PCM.SampleRate * Settings.PCM.BlockAlign)); _bw.Write((ushort)Settings.PCM.BlockAlign); _bw.Write((ushort)((Settings.PCM.BitsPerSample + 7) / 8 * 8)); if (wavex) { _bw.Write((ushort)22); // length of WAVEX structure _bw.Write((ushort)Settings.PCM.BitsPerSample); _bw.Write((uint)Settings.PCM.ChannelMask); _bw.Write((ushort)1); // PCM Guid _bw.Write((ushort)0); _bw.Write((ushort)0); _bw.Write((ushort)0x10); _bw.Write((byte)0x80); _bw.Write((byte)0x00); _bw.Write((byte)0x00); _bw.Write((byte)0xaa); _bw.Write((byte)0x00); _bw.Write((byte)0x38); _bw.Write((byte)0x9b); _bw.Write((byte)0x71); } if (_chunks != null) { for (int i = 0; i < _chunks.Count; i++) { _bw.Write(_chunkFCCs[i]); _bw.Write((uint)_chunks[i].Length); _bw.Write(_chunks[i]); if ((_chunks[i].Length & 1) != 0) { _bw.Write((byte)0); } } } _bw.Write(fccData); if (_finalSampleCount <= 0) { _bw.Write((uint)0xffffffff); } else { _bw.Write(dataLen); } _headersWritten = true; }
public AudioDecoder(DecoderSettings settings, string path, Stream IO) { m_settings = settings; _path = path; m_stream = (IO != null) ? IO : new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: var myPath = new Uri(typeof(AudioDecoder).Assembly.CodeBase).LocalPath; var current = System.IO.Path.GetDirectoryName(myPath); var probe = Environment.Is64BitProcess ? "x64" : "win32"; while (current != null) { var ffmpegDirectory = System.IO.Path.Combine(current, probe); if (Directory.Exists(ffmpegDirectory)) { System.Diagnostics.Trace.WriteLine($"FFmpeg binaries found in: {ffmpegDirectory}"); RegisterLibrariesSearchPath(ffmpegDirectory); break; } current = Directory.GetParent(current)?.FullName; } break; //case PlatformID.Unix: //case PlatformID.MacOSX: // var libraryPath = Environment.GetEnvironmentVariable(LD_LIBRARY_PATH); // RegisterLibrariesSearchPath(libraryPath); // break; } pkt = ffmpeg.av_packet_alloc(); if (pkt == null) { throw new Exception("Unable to initialize the decoder"); } decoded_frame = ffmpeg.av_frame_alloc(); if (decoded_frame == null) { throw new Exception("Could not allocate audio frame"); } //ffmpeg.avcodec_register_all(); ffmpeg.av_register_all(); #if DEBUG ffmpeg.av_log_set_level(ffmpeg.AV_LOG_DEBUG); av_log_set_callback_callback logCallback = (p0, level, format, vl) => { if (level > ffmpeg.av_log_get_level()) { return; } var lineSize = 1024; var lineBuffer = stackalloc byte[lineSize]; var printPrefix = 1; ffmpeg.av_log_format_line(p0, level, format, vl, lineBuffer, lineSize, &printPrefix); var line = Marshal.PtrToStringAnsi((IntPtr)lineBuffer); System.Diagnostics.Trace.Write(line); }; ffmpeg.av_log_set_callback(logCallback); #endif m_read_packet_callback = readPacketCallback; m_seek_callback = seekCallback; int ret; AVFormatContext *new_fmt_ctx = ffmpeg.avformat_alloc_context(); if (new_fmt_ctx == null) { throw new Exception("ffmpeg.avformat_alloc_context() failed"); } ulong avio_ctx_buffer_size = 65536; void *avio_ctx_buffer = ffmpeg.av_malloc(avio_ctx_buffer_size); AVIOContext *avio_ctx = ffmpeg.avio_alloc_context((byte *)avio_ctx_buffer, (int)avio_ctx_buffer_size, 0, null, m_read_packet_callback, null, m_seek_callback); if (avio_ctx == null) { ffmpeg.avformat_free_context(new_fmt_ctx); throw new Exception("Cannot find stream information"); } new_fmt_ctx->pb = avio_ctx; AVInputFormat *fmt = ffmpeg.av_find_input_format(m_settings.Format); if (fmt == null) { ffmpeg.avformat_free_context(new_fmt_ctx); throw new Exception($"Cannot find input format ${m_settings.Format}"); } if ((ret = ffmpeg.avformat_open_input(&new_fmt_ctx, null, fmt, null)) < 0) { ffmpeg.avformat_free_context(new_fmt_ctx); ret.ThrowExceptionIfError(); } if ((ret = ffmpeg.avformat_find_stream_info(new_fmt_ctx, null)) < 0) { ffmpeg.avformat_close_input(&new_fmt_ctx); ret.ThrowExceptionIfError(); } #if FINDBESTSTREAM /* select the audio stream */ ret = ffmpeg.av_find_best_stream(new_fmt_ctx, AVMediaType.AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0); if (ret < 0) { ffmpeg.avformat_close_input(&new_fmt_ctx); ret.ThrowExceptionIfError(); } #endif int matching_stream = -1; int matching_streams = 0; for (int i = 0; i < (int)new_fmt_ctx->nb_streams; i++) { AVStream *stream_i = new_fmt_ctx->streams[i]; if (stream_i->codecpar->codec_type == AVMediaType.AVMEDIA_TYPE_AUDIO && (settings.StreamId == 0 || settings.StreamId == stream_i->id)) { matching_stream = i; matching_streams++; } } if (matching_streams == 0) { ffmpeg.avformat_close_input(&new_fmt_ctx); throw new Exception("No matching streams"); } if (matching_streams != 1) { ffmpeg.avformat_close_input(&new_fmt_ctx); throw new Exception("More than one stream matches"); } stream = new_fmt_ctx->streams[matching_stream]; // Duration is unreliable for most codecs. //if (stream->duration > 0) // _sampleCount = stream->duration; //else _sampleCount = -1; int bps = stream->codecpar->bits_per_raw_sample != 0 ? stream->codecpar->bits_per_raw_sample : stream->codecpar->bits_per_coded_sample; int channels = stream->codecpar->channels; int sample_rate = stream->codecpar->sample_rate; ulong channel_layout = stream->codecpar->channel_layout; pcm = new AudioPCMConfig(bps, channels, sample_rate, (AudioPCMConfig.SpeakerConfig)channel_layout); fmt_ctx = new_fmt_ctx; codec = ffmpeg.avcodec_find_decoder(stream->codecpar->codec_id); if (codec == null) { throw new Exception("Codec not found"); } c = ffmpeg.avcodec_alloc_context3(codec); if (c == null) { throw new Exception("Could not allocate audio codec context"); } // ffmpeg.av_opt_set_int(c, "refcounted_frames", 1, 0); ffmpeg.avcodec_parameters_to_context(c, stream->codecpar); c->request_sample_fmt = AVSampleFormat.AV_SAMPLE_FMT_S32; /* open it */ if (ffmpeg.avcodec_open2(c, null, null) < 0) { throw new Exception("Could not open codec"); } m_decoded_frame_offset = 0; m_decoded_frame_size = 0; _sampleOffset = 0; }
public RemoteMp3VbrWriter(IPAddress remoteAddress, Stream output, AudioPCMConfig pcm) : base(remoteAddress, output, pcm) { this.CheckPCMConfig(pcm); }
public RemoteMp3VbrWriter(IPAddress remoteAddress, string outputPath, AudioPCMConfig pcm) : base(remoteAddress, outputPath, pcm) { this.CheckPCMConfig(pcm); }
public BE_CONFIG(AudioPCMConfig format, uint MpeBitRate, uint quality) { this.dwConfig = BE_CONFIG_LAME; this.format = new Format(format, MpeBitRate, quality); }
public ushort nQuality; // Quality Setting, HIGH BYTE should be NOT LOW byte, otherwise quality=5 // FUTURE USE, SET TO 0, align structure to 331 bytes //[ MarshalAs( UnmanagedType.ByValArray, SizeConst=255-4*4-2 )] //public byte[] btReserved;//[255-4*sizeof(DWORD) - sizeof( WORD )]; public LHV1(AudioPCMConfig format, uint MpeBitRate, uint quality) { dwStructVersion = 1; dwStructSize = (uint)Marshal.SizeOf(typeof(BE_CONFIG)); switch (format.SampleRate) { case 16000: case 22050: case 24000: dwMpegVersion = MPEG2; break; case 32000: case 44100: case 48000: dwMpegVersion = MPEG1; break; default: throw new ArgumentOutOfRangeException("format", "Unsupported sample rate"); } dwSampleRate = (uint)format.SampleRate; // INPUT FREQUENCY dwReSampleRate = 0; // DON'T RESAMPLE switch (format.ChannelCount) { case 1: nMode = MpegMode.MONO; break; case 2: nMode = MpegMode.STEREO; break; default: throw new ArgumentOutOfRangeException("format", "Invalid number of channels"); } switch (MpeBitRate) { case 0: case 32: case 40: case 48: case 56: case 64: case 80: case 96: case 112: case 128: case 160: //Allowed bit rates in MPEG1 and MPEG2 break; case 192: case 224: case 256: case 320: //Allowed only in MPEG1 if (dwMpegVersion != MPEG1) { throw new ArgumentOutOfRangeException("MpsBitRate", "Bit rate not compatible with input format"); } break; case 8: case 16: case 24: case 144: //Allowed only in MPEG2 if (dwMpegVersion != MPEG2) { throw new ArgumentOutOfRangeException("MpsBitRate", "Bit rate not compatible with input format"); } break; default: throw new ArgumentOutOfRangeException("MpsBitRate", "Unsupported bit rate"); } dwBitrate = MpeBitRate; // MINIMUM BIT RATE nPreset = LAME_QUALITY_PRESET.LQP_NORMAL_QUALITY; // QUALITY PRESET SETTING dwPsyModel = 0; // USE DEFAULT PSYCHOACOUSTIC MODEL dwEmphasis = 0; // NO EMPHASIS TURNED ON bOriginal = 1; // SET ORIGINAL FLAG bWriteVBRHeader = 0; bNoRes = 0; // No Bit resorvoir bCopyright = 0; bCRC = 0; bEnableVBR = 0; bPrivate = 0; bStrictIso = 0; dwMaxBitrate = 0; dwVbrAbr_bps = 0; nQuality = (ushort)(quality | ((~quality) << 8)); nVbrMethod = VBRMETHOD.VBR_METHOD_NONE; nVBRQuality = 0; }
static void Main(string[] args) { Console.SetOut(Console.Error); Console.WriteLine("LossyWAV {0}, Copyright (C) 2007,2008 Nick Currie, Copyleft.", LossyWAVWriter.version_string); Console.WriteLine("C# port Copyright (C) 2008 Grigory Chudov."); Console.WriteLine("This is free software under the GNU GPLv3+ license; There is NO WARRANTY, to"); Console.WriteLine("the extent permitted by law. <http://www.gnu.org/licenses/> for details."); if (args.Length < 1 || (args[0].StartsWith("-") && args[0] != "-")) { Usage(); return; } string sourceFile = args[0]; string stdinName = null; double quality = 5.0; bool createCorrection = false; bool toStdout = false; int outputBPS = 0; for (int arg = 1; arg < args.Length; arg++) { bool ok = true; if (args[arg] == "-I" || args[arg] == "--insane") { quality = 10; } else if (args[arg] == "-E" || args[arg] == "--extreme") { quality = 7.5; } else if (args[arg] == "-S" || args[arg] == "--standard") { quality = 5.0; } else if (args[arg] == "-P" || args[arg] == "--portable") { quality = 2.5; } else if (args[arg] == "-C" || args[arg] == "--correction") { createCorrection = true; } else if (args[arg] == "--16") { outputBPS = 16; } else if ((args[arg] == "-N" || args[arg] == "--stdinname") && ++arg < args.Length) { stdinName = args[arg]; } else if ((args[arg] == "-q" || args[arg] == "--quality") && ++arg < args.Length) { ok = double.TryParse(args[arg], out quality); } else if (args[arg] == "--stdout") { toStdout = true; } else { ok = false; } if (!ok) { Usage(); return; } } DateTime start = DateTime.Now; TimeSpan lastPrint = TimeSpan.FromMilliseconds(0); #if !DEBUG try #endif { Codecs.WAV.AudioDecoder audioSource = new Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings() { IgnoreChunkSizes = (sourceFile == "-") }, sourceFile, (sourceFile == "-" ? Console.OpenStandardInput() : null)); if (sourceFile == "-" && stdinName != null) { sourceFile = stdinName; } AudioPCMConfig pcm = outputBPS == 0 ? audioSource.PCM : new AudioPCMConfig(outputBPS, audioSource.PCM.ChannelCount, audioSource.PCM.SampleRate, audioSource.PCM.ChannelMask); Codecs.WAV.AudioEncoder audioDest = new Codecs.WAV.AudioEncoder(new Codecs.WAV.EncoderSettings(pcm), Path.ChangeExtension(sourceFile, ".lossy.wav"), toStdout ? Console.OpenStandardOutput() : null); Codecs.WAV.AudioEncoder lwcdfDest = createCorrection ? new Codecs.WAV.AudioEncoder(new Codecs.WAV.EncoderSettings(audioSource.PCM), Path.ChangeExtension(sourceFile, ".lwcdf.wav")) : null; LossyWAVWriter lossyWAV = new LossyWAVWriter(audioDest, lwcdfDest, quality, new Codecs.WAV.EncoderSettings(audioSource.PCM)); AudioBuffer buff = new AudioBuffer(audioSource, 0x10000); Console.WriteLine("Filename : {0}", sourceFile); Console.WriteLine("File Info : {0}kHz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample, TimeSpan.FromSeconds(audioSource.Length * 1.0 / audioSource.PCM.SampleRate)); lossyWAV.FinalSampleCount = audioSource.Length; while (audioSource.Read(buff, -1) != 0) { lossyWAV.Write(buff); TimeSpan elapsed = DateTime.Now - start; if ((elapsed - lastPrint).TotalMilliseconds > 60) { Console.Error.Write("\rProgress : {0:00}%; {1:0.0000} bits; {2:0.00}x; {3}/{4}", 100.0 * audioSource.Position / audioSource.Length, 1.0 * lossyWAV.OverallBitsRemoved / audioSource.PCM.ChannelCount / lossyWAV.BlocksProcessed, lossyWAV.SamplesProcessed / elapsed.TotalSeconds / audioSource.PCM.SampleRate, elapsed, TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / lossyWAV.SamplesProcessed * audioSource.Length) ); lastPrint = elapsed; } } TimeSpan totalElapsed = DateTime.Now - start; Console.Error.Write("\r \r"); Console.WriteLine("Results : {0:0.0000} bits; {1:0.00}x; {2}", (1.0 * lossyWAV.OverallBitsRemoved) / audioSource.PCM.ChannelCount / lossyWAV.BlocksProcessed, lossyWAV.SamplesProcessed / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate, totalElapsed ); audioSource.Close(); lossyWAV.Close(); } #if !DEBUG catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error: {0}", ex.Message); //Console.WriteLine("{0}", ex.StackTrace); } #endif }
public BE_CONFIG(AudioPCMConfig format, uint MpeBitRate, uint quality) { this.dwConfig = BE_CONFIG_LAME; this.format = new Format(format, MpeBitRate, quality); }
private void ParseHeaders() { const long maxFileSize = 0x7FFFFFFEL; const uint fccRIFF = 0x46464952; const uint fccWAVE = 0x45564157; const uint fccFormat = 0x20746D66; const uint fccData = 0x61746164; uint lenRIFF; bool foundFormat, foundData; if (_br.ReadUInt32() != fccRIFF) { throw new Exception("Not a valid RIFF file."); } lenRIFF = _br.ReadUInt32(); if (_br.ReadUInt32() != fccWAVE) { throw new Exception("Not a valid WAVE file."); } _largeFile = false; foundFormat = false; foundData = false; long pos = 12; do { uint ckID, ckSize, ckSizePadded; long ckEnd; ckID = _br.ReadUInt32(); ckSize = _br.ReadUInt32(); ckSizePadded = (ckSize + 1U) & ~1U; pos += 8; ckEnd = pos + (long)ckSizePadded; if (ckID == fccFormat) { foundFormat = true; uint fmtTag = _br.ReadUInt16(); int _channelCount = _br.ReadInt16(); int _sampleRate = _br.ReadInt32(); _br.ReadInt32(); // bytes per second int _blockAlign = _br.ReadInt16(); int _bitsPerSample = _br.ReadInt16(); int _channelMask = 0; pos += 16; if (fmtTag == 0xFFFEU && ckSize >= 34) // WAVE_FORMAT_EXTENSIBLE { _br.ReadInt16(); // CbSize _br.ReadInt16(); // ValidBitsPerSample _channelMask = _br.ReadInt32(); fmtTag = _br.ReadUInt16(); pos += 10; } if (fmtTag != 1) // WAVE_FORMAT_PCM { throw new Exception("WAVE format tag not WAVE_FORMAT_PCM."); } pcm = new AudioPCMConfig(_bitsPerSample, _channelCount, _sampleRate, (AudioPCMConfig.SpeakerConfig)_channelMask); if (pcm.BlockAlign != _blockAlign) { throw new Exception("WAVE has strange BlockAlign"); } } else if (ckID == fccData) { foundData = true; _dataOffset = pos; if (!_IO.CanSeek || _IO.Length <= maxFileSize) { if (ckSize == 0 || ckSize >= 0x7fffffff) { _dataLen = -1; } else { _dataLen = (long)ckSize; } } else { _largeFile = true; _dataLen = _IO.Length - pos; } } if ((foundFormat & foundData) || _largeFile) { break; } if (_IO.CanSeek) { _IO.Seek(ckEnd, SeekOrigin.Begin); } else { _br.ReadBytes((int)(ckEnd - pos)); } pos = ckEnd; } while (true); if ((foundFormat & foundData) == false || pcm == null) { throw new Exception("Format or data chunk not found."); } if (pcm.ChannelCount <= 0) { throw new Exception("Channel count is invalid."); } if (pcm.SampleRate <= 0) { throw new Exception("Sample rate is invalid."); } if ((pcm.BitsPerSample <= 0) || (pcm.BitsPerSample > 32)) { throw new Exception("Bits per sample is invalid."); } if (pos != _dataOffset) { Position = 0; } }
public static IAudioDest GetAudioDest(AudioEncoderType audioEncoderType, string path, AudioPCMConfig pcm, long finalSampleCount, int padding, string extension, CUEConfig config) { IAudioDest dest; if (audioEncoderType == AudioEncoderType.NoAudio || extension == ".dummy") { return new Codecs.NULL.AudioEncoder(path, new Codecs.WAV.EncoderSettings(pcm)) { FinalSampleCount = finalSampleCount } } ; CUEToolsFormat fmt; if (!extension.StartsWith(".") || !config.formats.TryGetValue(extension.Substring(1), out fmt)) { throw new Exception("Unsupported audio type: " + path); } AudioEncoderSettingsViewModel encoder = audioEncoderType == AudioEncoderType.Lossless ? fmt.encoderLossless : audioEncoderType == AudioEncoderType.Lossy ? fmt.encoderLossy : null; if (encoder == null) { throw new Exception("Unsupported audio type: " + path); } var settings = encoder.Settings.Clone(); settings.PCM = pcm; settings.Padding = padding; object o; try { o = Activator.CreateInstance(settings.EncoderType, settings, path, null); } catch (System.Reflection.TargetInvocationException ex) { throw ex.InnerException; } if (o == null || !(o is IAudioDest)) { throw new Exception("Unsupported audio type: " + path + ": " + settings.EncoderType.FullName); } dest = o as IAudioDest; dest.FinalSampleCount = finalSampleCount; return(dest); } }
public EncoderSettings(AudioPCMConfig pcm) { this.Init(pcm); }
public RemoteFlacWriter(IPAddress remoteAddress, string outputPath, AudioPCMConfig pcm) : base(remoteAddress, outputPath, pcm) { }
public RemoteFlacWriter(IPAddress remoteAddress, Stream output, AudioPCMConfig pcm) : base(remoteAddress, output, pcm) { }
public LameWriterVBR(string path, Stream IO, AudioPCMConfig pcm) : base(IO, pcm) { }
unsafe void decode_metadata() { byte x; int i, id; //bool first = true; byte[] FLAC__STREAM_SYNC_STRING = new byte[] { (byte)'f', (byte)'L', (byte)'a', (byte)'C' }; byte[] ID3V2_TAG_ = new byte[] { (byte)'I', (byte)'D', (byte)'3' }; for (i = id = 0; i < 4;) { if (_IO.Read(_framesBuffer, 0, 1) == 0) { throw new Exception("FLAC stream not found"); } x = _framesBuffer[0]; if (x == FLAC__STREAM_SYNC_STRING[i]) { //first = true; i++; id = 0; continue; } if (id < 3 && x == ID3V2_TAG_[id]) { id++; i = 0; if (id == 3) { if (!skip_bytes(3)) { throw new Exception("FLAC stream not found"); } int skip = 0; for (int j = 0; j < 4; j++) { if (0 == _IO.Read(_framesBuffer, 0, 1)) { throw new Exception("FLAC stream not found"); } skip <<= 7; skip |= ((int)_framesBuffer[0] & 0x7f); } if (!skip_bytes(skip)) { throw new Exception("FLAC stream not found"); } } continue; } id = 0; if (x == 0xff) /* MAGIC NUMBER for the first 8 frame sync bits */ { do { if (_IO.Read(_framesBuffer, 0, 1) == 0) { throw new Exception("FLAC stream not found"); } x = _framesBuffer[0]; } while (x == 0xff); if (x >> 2 == 0x3e) /* MAGIC NUMBER for the last 6 sync bits */ { //_IO.Position -= 2; // state = frame throw new Exception("headerless file unsupported"); } } throw new Exception("FLAC stream not found"); } do { fill_frames_buffer(); fixed(byte *buf = _framesBuffer) { BitReader bitreader = new BitReader(buf, _framesBufferOffset, _framesBufferLength - _framesBufferOffset); bool is_last = bitreader.readbit() != 0; MetadataType type = (MetadataType)bitreader.readbits(7); int len = (int)bitreader.readbits(24); if (type == MetadataType.StreamInfo) { const int FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */ min_block_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN); max_block_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN); min_frame_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN); max_frame_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN); int sample_rate = (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN); int channels = 1 + (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN); int bits_per_sample = 1 + (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN); pcm = new AudioPCMConfig(bits_per_sample, channels, sample_rate); _sampleCount = (long)bitreader.readbits64(FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN); bitreader.skipbits(FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN); } else if (type == MetadataType.Seektable) { int num_entries = len / 18; seek_table = new SeekPoint[num_entries]; for (int e = 0; e < num_entries; e++) { seek_table[e].number = bitreader.read_long(); seek_table[e].offset = bitreader.read_long(); seek_table[e].framesize = (int)bitreader.read_ushort(); } } if (_framesBufferLength < 4 + len) { _IO.Position += 4 + len - _framesBufferLength; _framesBufferLength = 0; } else { _framesBufferLength -= 4 + len; _framesBufferOffset += 4 + len; } if (is_last) { break; } } } while (true); first_frame_offset = _IO.Position - _framesBufferLength; }
unsafe void decode_metadata() { byte x; int i, id; bool first = true; byte[] FLAC__STREAM_SYNC_STRING = new byte[] { (byte)'f', (byte)'L', (byte)'a', (byte)'C' }; byte[] ID3V2_TAG_ = new byte[] { (byte)'I', (byte)'D', (byte)'3' }; for (i = id = 0; i < 4; ) { if (_IO.Read(_framesBuffer, 0, 1) == 0) throw new Exception("FLAC stream not found"); x = _framesBuffer[0]; if (x == FLAC__STREAM_SYNC_STRING[i]) { first = true; i++; id = 0; continue; } if (id < 3 && x == ID3V2_TAG_[id]) { id++; i = 0; if (id == 3) { if (!skip_bytes(3)) throw new Exception("FLAC stream not found"); int skip = 0; for (int j = 0; j < 4; j++) { if (0 == _IO.Read(_framesBuffer, 0, 1)) throw new Exception("FLAC stream not found"); skip <<= 7; skip |= ((int)_framesBuffer[0] & 0x7f); } if (!skip_bytes(skip)) throw new Exception("FLAC stream not found"); } continue; } id = 0; if (x == 0xff) /* MAGIC NUMBER for the first 8 frame sync bits */ { do { if (_IO.Read(_framesBuffer, 0, 1) == 0) throw new Exception("FLAC stream not found"); x = _framesBuffer[0]; } while (x == 0xff); if (x >> 2 == 0x3e) /* MAGIC NUMBER for the last 6 sync bits */ { //_IO.Position -= 2; // state = frame throw new Exception("headerless file unsupported"); } } throw new Exception("FLAC stream not found"); } do { fill_frames_buffer(); fixed (byte* buf = _framesBuffer) { BitReader bitreader = new BitReader(buf, _framesBufferOffset, _framesBufferLength - _framesBufferOffset); bool is_last = bitreader.readbit() != 0; MetadataType type = (MetadataType)bitreader.readbits(7); int len = (int)bitreader.readbits(24); if (type == MetadataType.StreamInfo) { const int FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */ min_block_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN); max_block_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN); min_frame_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN); max_frame_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN); int sample_rate = (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN); int channels = 1 + (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN); int bits_per_sample = 1 + (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN); pcm = new AudioPCMConfig(bits_per_sample, channels, sample_rate); _sampleCount = (long)bitreader.readbits64(FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN); bitreader.skipbits(FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN); } else if (type == MetadataType.Seektable) { int num_entries = len / 18; seek_table = new SeekPoint[num_entries]; for (int e = 0; e < num_entries; e++) { seek_table[e].number = (long)bitreader.readbits64(Flake.FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN); seek_table[e].offset = (long)bitreader.readbits64(Flake.FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN); seek_table[e].framesize = (int)bitreader.readbits24(Flake.FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN); } } if (_framesBufferLength < 4 + len) { _IO.Position += 4 + len - _framesBufferLength; _framesBufferLength = 0; } else { _framesBufferLength -= 4 + len; _framesBufferOffset += 4 + len; } if (is_last) break; } } while (true); first_frame_offset = _IO.Position - _framesBufferLength; }
public CLParityWriter(string path, AudioPCMConfig pcm) : this(path, null, pcm) { }
public LAMEEncoderVBR(string path, Stream IO, AudioPCMConfig pcm) : base(path, IO, pcm) { }
public IcecastWriter(AudioPCMConfig pcm, IcecastSettingsData settings) { this.m_settings = new AudioEncoderSettings(pcm); this.settings = settings; }
public LossyWAVWriter(IAudioDest audioDest, IAudioDest lwcdfDest, double quality, AudioPCMConfig pcm) { _audioDest = audioDest; _lwcdfDest = lwcdfDest; _pcm = pcm; if (_audioDest != null && _audioDest.PCM.BitsPerSample > _pcm.BitsPerSample) throw new Exception("audio parameters mismatch"); if (_lwcdfDest != null && _lwcdfDest.PCM.BitsPerSample != _pcm.BitsPerSample) throw new Exception("audio parameters mismatch"); int quality_integer = (int)Math.Floor(quality); fft_analysis_string = new string[4] { "0100010", "0110010", "0111010", "0111110" }; bool[] quality_auto_fft32_on = { false, false, false, true, true, true, true, true, true, true, true }; double[] quality_noise_threshold_shifts = { 20, 16, 9, 6, 3, 0, -2.4, -4.8, -7.2, -9.6, -12 }; double[] quality_signal_to_noise_ratio = { -18, -22, -23.5, -23.5, -23.5, -25, -28, -31, -34, -37, -40 }; double[] quality_dynamic_minimum_bits_to_keep = { 2.5, 2.75, 3.00, 3.25, 3.50, 3.75, 4.0, 4.25, 4.5, 4.75, 5.00 }; double[] quality_maximum_clips_per_channel = { 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0 }; this_analysis_number = 2; impulse = quality_auto_fft32_on[quality_integer]; linkchannels = false; noise_threshold_shift = Math.Round(interpolate_param(quality_noise_threshold_shifts, quality) * 1000) / 1000; snr_value = Math.Round(interpolate_param(quality_signal_to_noise_ratio, quality) * 1000) / 1000; dynamic_minimum_bits_to_keep = Math.Round(interpolate_param(quality_dynamic_minimum_bits_to_keep, quality) * 1000) / 1000; maximum_clips_per_channel = (int)Math.Round(interpolate_param(quality_maximum_clips_per_channel, quality)); scaling_factor = 1.0; shaping_factor = Math.Min(1, quality / 10); shaping_is_on = shaping_factor > 0; _audioBuffer = new AudioBuffer(_pcm, 256); }
public Format(AudioPCMConfig format, uint MpeBitRate, uint quality) { lhv1 = new LHV1(format, MpeBitRate, quality); }
public BE_CONFIG(AudioPCMConfig format) : this(format, 0, 5) { }
public ushort nQuality; // Quality Setting, HIGH BYTE should be NOT LOW byte, otherwhise quality=5 // FUTURE USE, SET TO 0, align strucutre to 331 bytes //[ MarshalAs( UnmanagedType.ByValArray, SizeConst=255-4*4-2 )] //public byte[] btReserved;//[255-4*sizeof(DWORD) - sizeof( WORD )]; public LHV1(AudioPCMConfig format, uint MpeBitRate, uint quality) { dwStructVersion = 1; dwStructSize = (uint)Marshal.SizeOf(typeof(BE_CONFIG)); switch (format.SampleRate) { case 16000: case 22050: case 24000: dwMpegVersion = MPEG2; break; case 32000: case 44100: case 48000: dwMpegVersion = MPEG1; break; default: throw new ArgumentOutOfRangeException("format", "Unsupported sample rate"); } dwSampleRate = (uint)format.SampleRate; // INPUT FREQUENCY dwReSampleRate = 0; // DON'T RESAMPLE switch (format.ChannelCount) { case 1: nMode = MpegMode.MONO; break; case 2: nMode = MpegMode.STEREO; break; default: throw new ArgumentOutOfRangeException("format", "Invalid number of channels"); } switch (MpeBitRate) { case 0: case 32: case 40: case 48: case 56: case 64: case 80: case 96: case 112: case 128: case 160: //Allowed bit rates in MPEG1 and MPEG2 break; case 192: case 224: case 256: case 320: //Allowed only in MPEG1 if (dwMpegVersion != MPEG1) { throw new ArgumentOutOfRangeException("MpsBitRate", "Bit rate not compatible with input format"); } break; case 8: case 16: case 24: case 144: //Allowed only in MPEG2 if (dwMpegVersion != MPEG2) { throw new ArgumentOutOfRangeException("MpsBitRate", "Bit rate not compatible with input format"); } break; default: throw new ArgumentOutOfRangeException("MpsBitRate", "Unsupported bit rate"); } dwBitrate = MpeBitRate; // MINIMUM BIT RATE nPreset = LAME_QUALITY_PRESET.LQP_NORMAL_QUALITY; // QUALITY PRESET SETTING dwPsyModel = 0; // USE DEFAULT PSYCHOACOUSTIC MODEL dwEmphasis = 0; // NO EMPHASIS TURNED ON bOriginal = 1; // SET ORIGINAL FLAG bWriteVBRHeader = 0; bNoRes = 0; // No Bit resorvoir bCopyright = 0; bCRC = 0; bEnableVBR = 0; bPrivate = 0; bStrictIso = 0; dwMaxBitrate = 0; dwVbrAbr_bps = 0; nQuality = (ushort)(quality | ((~quality) << 8)); nVbrMethod = VBRMETHOD.VBR_METHOD_NONE; nVBRQuality = 0; }