Example #1
0
        void Initialize()
        {
            if (_decoderProcess != null)
            {
                return;
            }
            _decoderProcess = new Process();
            _decoderProcess.StartInfo.FileName               = _decoder;
            _decoderProcess.StartInfo.Arguments              = _decoderParams.Replace("%I", "\"" + Path + "\"");
            _decoderProcess.StartInfo.CreateNoWindow         = true;
            _decoderProcess.StartInfo.RedirectStandardOutput = true;
            _decoderProcess.StartInfo.UseShellExecute        = false;
            bool      started = false;
            Exception ex      = null;

            try
            {
                started = _decoderProcess.Start();
                if (started)
                {
                    _decoderProcess.PriorityClass = Process.GetCurrentProcess().PriorityClass;
                }
            }
            catch (Exception _ex)
            {
                ex = _ex;
            }
            if (!started)
            {
                throw new Exception(_decoder + ": " + (ex == null ? "please check the path" : ex.Message));
            }
            rdr = new WAVReader(Path, _decoderProcess.StandardOutput.BaseStream);
        }
Example #2
0
 public UserDefinedReader(string path, Stream IO, string decoder, string decoderParams)
 {
     Path            = path;
     _decoder        = decoder;
     _decoderParams  = decoderParams;
     _decoderProcess = null;
     rdr             = null;
 }
 public UserDefinedReader(string path, Stream IO, string decoder, string decoderParams)
 {
     _path = path;
     _decoder = decoder;
     _decoderParams = decoderParams;
     _decoderProcess = null;
     rdr = null;
 }
 public static Tuple<int, string> WavToFlac(byte[] wavBytes, string flacSavePath)
 {
     Tuple<int, string> sampleRateAndTargetFlac = null;
     string targetFlacPath = FormatFileName(flacSavePath, ".FLAC");
     using (Stream dataStream = new MemoryStream(wavBytes))
     {
         WAVReader audioSource = new WAVReader(null, dataStream);
         sampleRateAndTargetFlac = WavToFlacHelper(audioSource, targetFlacPath);
     }
     return sampleRateAndTargetFlac;
 }
Example #5
0
        public static AudioBuffer ReadAllSamples(string path, Stream IO)
        {
            WAVReader   reader = new WAVReader(path, IO);
            AudioBuffer buff   = new AudioBuffer(reader, (int)reader.Length);

            reader.Read(buff, -1);
            if (reader.Remaining != 0)
            {
                throw new Exception("couldn't read the whole file");
            }
            reader.Close();
            return(buff);
        }
 private static Tuple<int, string> WavToFlacHelper(WAVReader audioSource, string targetFlacPath)
 {
     int sampleRate;
     AudioBuffer buffer = new AudioBuffer(audioSource, 0x10000);
     FlakeWriterSettings settings = new FlakeWriterSettings();
     settings.PCM = audioSource.PCM;
     FlakeWriter audioDestination = new FlakeWriter(targetFlacPath, settings);
     while (audioSource.Read(buffer, -1) != 0)
     {
         audioDestination.Write(buffer);
     }
     sampleRate = settings.PCM.SampleRate;
     audioDestination.Close();
     audioSource.Close();
     return new Tuple<int, string>(sampleRate, targetFlacPath);
 }
        /// <summary> Конвертирование wav-файла во flac </summary>        
        /// <returns>Частота дискретизации</returns>
        public static int Wav2Flac(Stream wavStream, Stream flacStream)
        {
            int sampleRate = 0;

            IAudioSource audioSource = new WAVReader(null, wavStream);
            AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);

            FlakeWriter flakewriter = new FlakeWriter(null, flacStream, audioSource.PCM);
            sampleRate = audioSource.PCM.SampleRate;

            FlakeWriter audioDest = flakewriter;
            while (audioSource.Read(buff, -1) != 0)
            {
                audioDest.Write(buff);
            }
            return sampleRate;
        }
 public static Tuple<int, string> WavToFlac(string targetWavFile)
 {
     string targetFlacPath = FormatFileName(targetWavFile, ".FLAC");
     WAVReader audioSource = new WAVReader(targetWavFile, null);
     //AudioBuffer buffer = new AudioBuffer(audioSource, 0x10000);
     //FlakeWriterSettings settings = new FlakeWriterSettings();
     //settings.PCM = audioSource.PCM;
     //FlakeWriter audioDestination = new FlakeWriter(targetFlacPath, settings);
     //while (audioSource.Read(buffer, -1) != 0)
     //{
     //    audioDestination.Write(buffer);
     //}
     //sampleRate = settings.PCM.SampleRate;
     //audioDestination.Close();
     //audioSource.Close();
     //Tuple<int, string> output = new Tuple<int, string>(sampleRate, targetFlacPath);
     return WavToFlacHelper(audioSource, targetFlacPath);
 }
Example #9
0
 private void ConvertToFlac(Stream sourceStream, Stream destinationStream) {
   var audioSource = new WAVReader(null, sourceStream);
   try {
     if (audioSource.PCM.SampleRate != 16000) {
       throw new InvalidOperationException("Incorrect frequency - WAV file must be at 16 KHz.");
     }
     var buff = new AudioBuffer(audioSource, 0x10000);
     var flakeWriter = new FlakeWriter(null, destinationStream, audioSource.PCM);
     //flakeWriter.CompressionLevel = 8;
     while (audioSource.Read(buff, -1) != 0) {
       flakeWriter.Write(buff);
     }
     flakeWriter.Close();
   }
   finally {
     audioSource.Close();
   }
 }
Example #10
0
        public static int Wav2Flac(String wavName, string flacName)
        {
            int sampleRate = 0;
            IAudioSource audioSource = new WAVReader(wavName, null);
            AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);

            FlakeWriter flakewriter = new FlakeWriter(flacName, audioSource.PCM);
            sampleRate = audioSource.PCM.SampleRate;
            FlakeWriter audioDest = flakewriter;
            while (audioSource.Read(buff, -1) != 0)
            {
                audioDest.Write(buff);
            }
            audioDest.Close();

            audioDest.Close();
            audioSource.Close();
            return sampleRate;
        }
Example #11
0
 private byte[] Wav2FlacBuffConverter(byte[] Buffer)
 {
     Stream OutWavStream = new MemoryStream();
     Stream OutFlacStream = new MemoryStream();
     AudioPCMConfig pcmconf = new AudioPCMConfig(16, 1, 16000);
     WAVWriter wr = new WAVWriter(null, OutWavStream, pcmconf);
     wr.Write(new AudioBuffer(pcmconf, Buffer, Buffer.Length / 2));
     OutWavStream.Seek(0, SeekOrigin.Begin);
     WAVReader audioSource = new WAVReader(null, OutWavStream);
     if (audioSource.PCM.SampleRate != 16000) 
     return null;
     AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);
     FlakeWriter flakeWriter = new FlakeWriter(null, OutFlacStream, audioSource.PCM);
     flakeWriter.CompressionLevel = 8;
     while (audioSource.Read(buff, -1) != 0)
     {
         flakeWriter.Write(buff);
     }
     OutFlacStream.Seek(0, SeekOrigin.Begin);
     byte[] barr = new byte[OutFlacStream.Length];
     OutFlacStream.Read(barr, 0, (int)OutFlacStream.Length);
     return barr;
 }
Example #12
0
 void Initialize()
 {
     if (_decoderProcess != null)
         return;
     _decoderProcess = new Process();
     _decoderProcess.StartInfo.FileName = _decoder;
     _decoderProcess.StartInfo.Arguments = _decoderParams.Replace("%I", "\"" + _path + "\"");
     _decoderProcess.StartInfo.CreateNoWindow = true;
     _decoderProcess.StartInfo.RedirectStandardOutput = true;
     _decoderProcess.StartInfo.UseShellExecute = false;
     bool started = false;
     Exception ex = null;
     try
     {
         started = _decoderProcess.Start();
         if (started)
             _decoderProcess.PriorityClass = Process.GetCurrentProcess().PriorityClass;
     }
     catch (Exception _ex)
     {
         ex = _ex;
     }
     if (!started)
         throw new Exception(_decoder + ": " + (ex == null ? "please check the path" : ex.Message));
     rdr = new WAVReader(_path, _decoderProcess.StandardOutput.BaseStream);
 }
Example #13
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
			{
				WAVReader audioSource = new WAVReader(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);
				WAVWriter audioDest = new WAVWriter(Path.ChangeExtension(sourceFile, ".lossy.wav"), toStdout ? Console.OpenStandardOutput() : null, pcm);
				WAVWriter lwcdfDest = createCorrection ? new WAVWriter(Path.ChangeExtension(sourceFile, ".lwcdf.wav"), null, audioSource.PCM) : null;
				LossyWAVWriter lossyWAV = new LossyWAVWriter(audioDest, lwcdfDest, quality, 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
		}
Example #14
0
		static int Main(string[] args)
		{
			TextWriter stdout = Console.Out;
			Console.SetOut(Console.Error);

			var settings = new FLACCLWriterSettings();
			TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
			bool debug = false, quiet = false;
			string stereo_method = null;
			string window_function = null;
			string input_file = null;
			string output_file = null;
			string device_type = null;
			int min_partition_order = -1, max_partition_order = -1,
				min_lpc_order = -1, max_lpc_order = -1,
				min_fixed_order = -1, max_fixed_order = -1,
				min_precision = -1, max_precision = -1,
				orders_per_window = -1, orders_per_channel = -1,
				blocksize = -1;
			int input_len = 4096, input_val = 0, input_bps = 16, input_ch = 2, input_rate = 44100;
			int level = -1, padding = -1, vbr_mode = -1;
			bool do_seektable = true;
			bool estimate_window = false;
			bool buffered = false;
			bool ok = true;
			int intarg;

			for (int arg = 0; arg < args.Length; arg++)
			{
				if (args[arg].Length == 0)
					ok = false;
				else if (args[arg] == "--debug")
					debug = true;
				else if ((args[arg] == "-q" || args[arg] == "--quiet"))
					quiet = true;
				else if (args[arg] == "--verify")
					settings.DoVerify = true;
				else if (args[arg] == "--no-seektable")
					do_seektable = false;
				else if (args[arg] == "--slow-gpu")
					settings.GPUOnly = false;
				else if (args[arg] == "--fast-gpu")
					settings.DoRice = true;
				else if (args[arg] == "--no-md5")
					settings.DoMD5 = false;
				else if (args[arg] == "--buffered")
					buffered = true;
				else if (args[arg] == "--cpu-threads")
				{
					int val = settings.CPUThreads;
					ok = (++arg < args.Length) && int.TryParse(args[arg], out val);
					settings.CPUThreads = val;
				}
				else if (args[arg] == "--group-size" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					settings.GroupSize = intarg;
				else if (args[arg] == "--task-size" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					settings.TaskSize = intarg;
				else if (args[arg] == "--define" && arg + 2 < args.Length)
					settings.Defines += "#define " + args[++arg] + " " + args[++arg] + "\n";
				else if (args[arg] == "--opencl-platform" && ++arg < args.Length)
					settings.Platform = args[arg];
				else if (args[arg] == "--mapped-memory")
					settings.MappedMemory = true;
				else if (args[arg] == "--opencl-type" && ++arg < args.Length)
					device_type = args[arg];
				else if (args[arg] == "--input-length" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					input_len = intarg;
				else if (args[arg] == "--input-value" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					input_val = intarg;
				else if (args[arg] == "--input-bps" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					input_bps = intarg;
				else if (args[arg] == "--input-channels" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					input_ch = intarg;
				else if ((args[arg] == "-o" || args[arg] == "--output") && ++arg < args.Length)
					output_file = args[arg];
				else if ((args[arg] == "-s" || args[arg] == "--stereo") && ++arg < args.Length)
					stereo_method = args[arg];
				else if ((args[arg] == "-w" || args[arg] == "--window") && ++arg < args.Length)
					window_function = args[arg];
				else if ((args[arg] == "-r" || args[arg] == "--partition-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_partition_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_partition_order)) ||
						int.TryParse(args[arg], out max_partition_order);
				}
				else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_lpc_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_lpc_order)) ||
						int.TryParse(args[arg], out max_lpc_order);
				}
				else if (args[arg] == "--fixed-order" && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_fixed_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_fixed_order)) ||
						int.TryParse(args[arg], out max_fixed_order);
				}
				else if ((args[arg] == "-c" || args[arg] == "--max-precision") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_precision) &&
						int.TryParse(args[arg].Split(',')[1], out max_precision)) ||
						int.TryParse(args[arg], out max_precision);
				}
				else if ((args[arg] == "-v" || args[arg] == "--vbr"))
					ok = (++arg < args.Length) && int.TryParse(args[arg], out vbr_mode);
				else if (args[arg] == "--orders-per-window" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					orders_per_window = intarg;
				else if (args[arg] == "--orders-per-channel" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					orders_per_channel = intarg;
				else if (args[arg] == "--estimate-window")
					estimate_window = true;
				else if ((args[arg] == "-b" || args[arg] == "--blocksize") && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					blocksize = intarg;
				else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length && int.TryParse(args[arg], out intarg))
					padding = intarg;
				else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out level))
					ok = level >= 0 && level <= 11;
				else if ((args[arg][0] != '-' || args[arg] == "-") && input_file == null)
					input_file = args[arg];
				else
					ok = false;
				if (!ok)
					break;
			}
			if (!quiet)
			{
				Console.WriteLine("{0}, Copyright (C) 2010 Grigory Chudov.", FLACCLWriter.vendor_string);
				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 (!ok || input_file == null)
			{
				Usage();
				return 1;
			}

			if (((input_file == "-" || Path.GetExtension(input_file) == ".flac") && output_file == null))
			{
				Console.WriteLine();
				Console.WriteLine("Output file not specified.");
				Console.WriteLine();
				Usage();
				return 2;
			}

			IAudioSource audioSource;
			try
			{
				if (input_file == "-")
					audioSource = new WAVReader("", Console.OpenStandardInput());
				else if (input_file == "nul")
					audioSource = new SilenceGenerator(new AudioPCMConfig(input_bps, input_ch, input_rate), input_len, input_val);
				else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".wav")
					audioSource = new WAVReader(input_file, null);
				else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".flac")
					audioSource = new FlakeReader(input_file, null);
				else
				{
					Usage();
					return 2;
				}
			}
			catch (Exception ex)
			{
				Usage();
				Console.WriteLine("");
				Console.WriteLine("Error: {0}.", ex.Message);
				return 3;
			}
			if (buffered)
				audioSource = new AudioPipe(audioSource, FLACCLWriter.MAX_BLOCKSIZE);
			if (output_file == null)
				output_file = Path.ChangeExtension(input_file, "flac");
			FLACCLWriter encoder = new FLACCLWriter((output_file == "-" || output_file == "nul") ? "" : output_file,
				output_file == "-" ? Console.OpenStandardOutput() :
				output_file == "nul" ? new NullStream() : null,
				audioSource.PCM);
			encoder.FinalSampleCount = audioSource.Length;
			IAudioDest audioDest = encoder;
			AudioBuffer buff = new AudioBuffer(audioSource, FLACCLWriter.MAX_BLOCKSIZE);

			try
			{
				if (device_type != null)
					settings.DeviceType = (OpenCLDeviceType)(Enum.Parse(typeof(OpenCLDeviceType), device_type, true));
				encoder.Settings = settings;
				if (level >= 0)
					encoder.CompressionLevel = level;
				if (stereo_method != null)
					encoder.StereoMethod = Flake.LookupStereoMethod(stereo_method);
				if (window_function != null)
					encoder.WindowFunction = Flake.LookupWindowFunction(window_function);
				if (min_partition_order >= 0)
					encoder.MinPartitionOrder = min_partition_order;
				if (max_partition_order >= 0)
					encoder.MaxPartitionOrder = max_partition_order;
				if (min_lpc_order >= 0)
					encoder.MinLPCOrder = min_lpc_order;
				if (max_lpc_order >= 0)
					encoder.MaxLPCOrder = max_lpc_order;
				if (min_fixed_order >= 0)
					encoder.MinFixedOrder = min_fixed_order;
				if (max_fixed_order >= 0)
					encoder.MaxFixedOrder = max_fixed_order;
				if (max_precision >= 0)
					encoder.MaxPrecisionSearch = max_precision;
				if (min_precision >= 0)
					encoder.MinPrecisionSearch = min_precision;
				if (blocksize >= 0)
					encoder.BlockSize = blocksize;
				if (padding >= 0)
					encoder.Padding = padding;
				if (vbr_mode >= 0)
					encoder.VBRMode = vbr_mode;
				if (orders_per_window >= 0)
					encoder.OrdersPerWindow = orders_per_window;
				if (orders_per_channel >= 0)
					encoder.OrdersPerChannel = orders_per_channel;
				if (estimate_window)
					encoder.EstimateWindow = estimate_window;
				encoder.DoSeekTable = do_seektable;
			}
			catch (Exception ex)
			{
				Usage();
				Console.WriteLine("");
				Console.WriteLine("Error: {0}.", ex.Message);
				return 3;
			}

			if (!quiet)
			{
				Console.WriteLine("Filename  : {0}", input_file);
				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));
			}

			DateTime start = DateTime.Now;
			try
			{
				audioDest.Write(buff);
				start = DateTime.Now;
				while (audioSource.Read(buff, -1) != 0)
				{
					audioDest.Write(buff);
					TimeSpan elapsed = DateTime.Now - start;
					if (!quiet)
					{
						if ((elapsed - lastPrint).TotalMilliseconds > 60)
						{
							Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
								100.0 * audioSource.Position / audioSource.Length,
								audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
								elapsed,
								TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * audioSource.Length)
								);
							lastPrint = elapsed;
						}
					}
				}
				audioDest.Close();
			}
			catch (OpenCLNet.OpenCLBuildException ex)
			{
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Error     : {0}", ex.Message);
				Console.WriteLine("{0}", ex.BuildLogs[0]);
				if (debug)
					using (StreamWriter sw = new StreamWriter("debug.txt", true))
						sw.WriteLine("{0}\n{1}\n{2}", ex.Message, ex.StackTrace, ex.BuildLogs[0]);
				audioDest.Delete();
				audioSource.Close();
				return 4;
			}
#if !DEBUG
			catch (Exception ex)
			{
			    Console.Error.Write("\r                                                                         \r");
			    Console.WriteLine("Error     : {0}", ex.Message);
				if (debug)
					using (StreamWriter sw = new StreamWriter("debug.txt", true))
						sw.WriteLine("{0}\n{1}", ex.Message, ex.StackTrace);
			    audioDest.Delete();
			    audioSource.Close();
			    return 4;
			}
#endif

			TimeSpan totalElapsed = DateTime.Now - start;
			if (!quiet)
			{
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Results   : {0:0.00}x; {2} bytes in {1} seconds;",
					audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
					totalElapsed,
					encoder.TotalSize
					);
			}
			audioSource.Close();

			if (debug)
			{
				Console.SetOut(stdout);
				Console.Out.WriteLine("{0}\t{1}\t{2}\t{3}\t{4} ({5})\t{6}/{7}+{12}{13}\t{8}..{9}\t{10}\t{11}",
					encoder.TotalSize,
					encoder.UserProcessorTime.TotalSeconds > 0 ? encoder.UserProcessorTime.TotalSeconds : totalElapsed.TotalSeconds,
					(encoder.StereoMethod.ToString() + (encoder.OrdersPerChannel == 32 ? "" : "(" + encoder.OrdersPerChannel.ToString() + ")")).PadRight(15),
					encoder.WindowFunction.ToString().PadRight(15),
					encoder.MaxPartitionOrder,
					settings.GPUOnly ? "GPU" : "CPU",
					encoder.OrdersPerWindow,
					encoder.MaxLPCOrder,
					encoder.MinPrecisionSearch,
					encoder.MaxPrecisionSearch,
					encoder.BlockSize,
					encoder.VBRMode,
					encoder.MaxFixedOrder - encoder.MinFixedOrder + 1,
					encoder.DoConstant ? "c" : ""
					);
			}
			return 0;
		}
        /// <summary>
        /// Convert stream of wav to flac format and send it to google speech recognition service.
        /// </summary>
        /// <param name="stream">wav stream</param>
        /// <returns>recognized result</returns>
        /// // Step 1- Converts wav stream to flac 
        public static string WavStreamToGoogle(Stream stream)
        {
            FlakeWriter audioDest = null;
            IAudioSource audioSource = null;
            string answer;
            try
            {
                var outStream = new MemoryStream();

                stream.Position = 0;

                audioSource = new WAVReader("", stream);

                var buff = new AudioBuffer(audioSource, 0x10000);

                audioDest = new FlakeWriter("", outStream, audioSource.PCM);

                var sampleRate = audioSource.PCM.SampleRate;

                while (audioSource.Read(buff, -1) != 0)
                {
                    audioDest.Write(buff);
                }

                answer = GoogleRequest(outStream, sampleRate);

            }
            finally
            {
                if (audioDest != null) audioDest.Close();
                if (audioSource != null) audioSource.Close();
            }
            return answer;
        }
        /// <summary>
        /// Convert .wav file to .flac file with the same name
        /// </summary>
        /// <param name="WavName">path to .wav file</param>
        /// <returns>Sample Rate of converted .flac</returns>
        public static int Wav2Flac(string WavName)
        {
            int sampleRate;
            var flacName = Path.ChangeExtension(WavName, "flac");

            FlakeWriter audioDest = null;
            IAudioSource audioSource = null;
            try
            {
                audioSource = new WAVReader(WavName, null);

                AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);

                audioDest = new FlakeWriter(flacName, audioSource.PCM);

                sampleRate = audioSource.PCM.SampleRate;

                while (audioSource.Read(buff, -1) != 0)
                {
                    audioDest.Write(buff);
                }
            }
            finally
            {
                if (audioDest != null) audioDest.Close();
                if (audioSource != null) audioSource.Close();
            }
            return sampleRate;
        }
Example #17
0
 public static AudioBuffer ReadAllSamples(string path, Stream IO)
 {
     WAVReader reader = new WAVReader(path, IO);
     AudioBuffer buff = new AudioBuffer(reader, (int)reader.Length);
     reader.Read(buff, -1);
     if (reader.Remaining != 0)
         throw new Exception("couldn't read the whole file");
     reader.Close();
     return buff;
 }
Example #18
0
		public void MyTestInitialize()
		{
			pipe = new WAVReader("pipe.wav", null);
			wave = new WAVReader("test.wav", null);
		}
Example #19
0
		public void MyTestCleanup()
		{
			pipe.Close();
			pipe = null;
			wave.Close();
			wave = null;
		}
Example #20
0
		static int Main(string[] args)
		{
			TextWriter stdout = Console.Out;
			Console.SetOut(Console.Error);

			DateTime start = DateTime.Now;
			TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
			bool debug = false, quiet = false;
			string stereo_method = null;
			string window_method = null;
			string order_method = null;
			string window_function = null;
			string input_file = null;
			string output_file = null;
			int min_lpc_order = -1, max_lpc_order = -1,
				blocksize = -1, estimation_depth = -1,
				min_modifier = -1, max_modifier = -1;
			int level = -1, padding = -1;
			int initial_history = -1, history_mult = -1;
			int adaptive_passes = -1;
			bool do_seektable = true, do_verify = false;
			bool buffered = false;

			for (int arg = 0; arg < args.Length; arg++)
			{
				bool ok = true;
				if (args[arg].Length == 0)
					ok = false;
				else if (args[arg] == "--debug")
					debug = true;
				else if ((args[arg] == "-q" || args[arg] == "--quiet"))
					quiet = true;
				else if (args[arg] == "--verify")
					do_verify = true;
				else if (args[arg] == "--no-seektable")
					do_seektable = false;
				else if (args[arg] == "--buffered")
					buffered = true;
				else if ((args[arg] == "-o" || args[arg] == "--output") && ++arg < args.Length)
					output_file = args[arg];
				else if ((args[arg] == "-s" || args[arg] == "--stereo") && ++arg < args.Length)
					stereo_method = args[arg];
				else if ((args[arg] == "-m" || args[arg] == "--order-method") && ++arg < args.Length)
					order_method = args[arg];
				else if ((args[arg] == "-w" || args[arg] == "--window") && ++arg < args.Length)
					window_function = args[arg];
				else if (args[arg] == "--window-method" && ++arg < args.Length)
					window_method = args[arg];
				else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_lpc_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_lpc_order)) ||
						int.TryParse(args[arg], out max_lpc_order);
				}
				else if ((args[arg] == "--history-modifier") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_modifier) &&
						int.TryParse(args[arg].Split(',')[1], out max_modifier)) ||
						int.TryParse(args[arg], out max_modifier);
				}
				else if ((args[arg] == "--initial-history") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out initial_history);
				else if ((args[arg] == "--adaptive-passes") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out adaptive_passes);
				else if ((args[arg] == "--history-mult") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out history_mult);
				else if ((args[arg] == "-e" || args[arg] == "--estimation-depth") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out estimation_depth);
				else if ((args[arg] == "-b" || args[arg] == "--blocksize") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out blocksize);
				else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out padding);
				else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out level))
					ok = level >= 0 && level <= 11;
				else if ((args[arg][0] != '-' || args[arg] == "-") && input_file == null)
					input_file = args[arg];
				else
					ok = false;
				if (!ok)
				{
					Usage();
					return 1;
				}
			}
			if (input_file == null || ((input_file == "-" || Path.GetExtension(input_file) == ".m4a") && output_file == null))
			{
				Usage();
				return 2;
			}

			if (!quiet)
			{
				Console.WriteLine("CUETools.ALACEnc, Copyright (C) 2009 Grigory Chudov.");
				Console.WriteLine("Based on ffdshow ALAC audio encoder");
				Console.WriteLine("Copyright (c) 2008  Jaikrishnan Menon, <*****@*****.**>");
				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.");
			}

			//byte [] b = new byte[0x10000];
			//int len = 0;
			//Stream si = Console.OpenStandardInput();
			//Stream so = new FileStream(output_file, FileMode.Create);
			//do
			//{
			//    len = si.Read(b, 0, 0x10000);
			//    so.Write(b, 0, len);
			//} while (len > 0);
			//return 0;
			IAudioSource audioSource;
			if (input_file == "-")
				audioSource = new WAVReader("", Console.OpenStandardInput());
			else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".wav")
				audioSource = new WAVReader(input_file, null);
			else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".m4a")
				audioSource = new ALACReader(input_file, null);
			else
			{
				Usage();
				return 2;
			}
			if (buffered)
				audioSource = new AudioPipe(audioSource, 0x10000);
			if (output_file == null)
				output_file = Path.ChangeExtension(input_file, "m4a");
			ALACWriter alac = new ALACWriter((output_file == "-" || output_file == "nul") ? "" : output_file,
				output_file == "-" ? Console.OpenStandardOutput() :
				output_file == "nul" ? new NullStream() : null,
				audioSource.PCM);
			alac.FinalSampleCount = audioSource.Length;
			IAudioDest audioDest = alac;
			AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);

			try
			{
				if (level >= 0)
					alac.CompressionLevel = level;
				if (stereo_method != null)
					alac.StereoMethod = Alac.LookupStereoMethod(stereo_method);
				if (order_method != null)
					alac.OrderMethod = Alac.LookupOrderMethod(order_method);
				if (window_function != null)
					alac.WindowFunction = Alac.LookupWindowFunction(window_function);
				if (window_method != null)
					alac.WindowMethod = Alac.LookupWindowMethod(window_method);
				if (max_lpc_order >= 0)
					alac.MaxLPCOrder = max_lpc_order;
				if (min_lpc_order >= 0)
					alac.MinLPCOrder = min_lpc_order;
				if (max_modifier >= 0)
					alac.MaxHistoryModifier = max_modifier;
				if (min_modifier >= 0)
					alac.MinHistoryModifier = min_modifier;
				if (history_mult >= 0)
					alac.HistoryMult = history_mult;
				if (initial_history >= 0)
					alac.InitialHistory = initial_history;
				if (blocksize >= 0)
					alac.BlockSize = blocksize;
				if (estimation_depth >= 0)
					alac.EstimationDepth = estimation_depth;
				if (padding >= 0)
					alac.Padding = padding;
				if (adaptive_passes >= 0)
					alac.AdaptivePasses = adaptive_passes;
				alac.DoSeekTable = do_seektable;
				(alac.Settings as ALACWriterSettings).DoVerify = do_verify;
			}
			catch (Exception ex)
			{
				Usage();
				Console.WriteLine("");
				Console.WriteLine("Error: {0}.", ex.Message);
				return 3;
			}

			if (!quiet)
			{
				Console.WriteLine("Filename  : {0}", input_file);
				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));
			}

#if !DEBUG
			try
#endif
			{
				while (audioSource.Read(buff, -1) != 0)
				{
					audioDest.Write(buff);
					TimeSpan elapsed = DateTime.Now - start;
					if (!quiet)
					{
						if ((elapsed - lastPrint).TotalMilliseconds > 60)
						{
							Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
								100.0 * audioSource.Position / audioSource.Length,
								audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
								elapsed,
								TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * audioSource.Length)
								);
							lastPrint = elapsed;
						}
					}
				}
				audioDest.Close();
			}
#if !DEBUG
			catch (Exception ex)
			{
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Error     : {0}", ex.Message);
				audioDest.Delete();
				audioSource.Close();
				return 4;
			}
#endif

			if (!quiet)
			{
				TimeSpan totalElapsed = DateTime.Now - start;
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Results   : {0:0.00}x; {1}",
					audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
					totalElapsed
					);
			}
			audioSource.Close();

			if (debug)
			{
				Console.SetOut(stdout);
				Console.Out.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}..{6}\t{7}..{8}\t{9}",
					alac.TotalSize,
					alac.UserProcessorTime.TotalSeconds,
					alac.StereoMethod.ToString().PadRight(15),
					(alac.OrderMethod.ToString() + (alac.OrderMethod == OrderMethod.Estimate ? "(" + alac.EstimationDepth.ToString() + ")" : "")).PadRight(15),
					alac.WindowFunction.ToString() + "(" + alac.AdaptivePasses.ToString() + ")",
					alac.MinLPCOrder,
					alac.MaxLPCOrder,
					alac.MinHistoryModifier,
					alac.MaxHistoryModifier,
					alac.BlockSize
					);
			}
			//File.SetAttributes(output_file, FileAttributes.ReadOnly);
			return 0;
		}
        /// <summary>Конвертирование wav-файла во flac</summary>
        /// <returns>Частота дискретизации</returns>
        private static void _Wav2Flac(String wavName, string flacName)
        {
            Debug.Assert(wavName != null);
            Debug.Assert(!string.IsNullOrEmpty(flacName));

            IAudioSource audioSource = new WAVReader(wavName, null);
            AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);

            FlakeWriter flakewriter = new FlakeWriter(flacName, audioSource.PCM);

            FlakeWriter audioDest = flakewriter;
            while (audioSource.Read(buff, -1) != 0)
            {
                audioDest.Write(buff);
            }

            audioDest.Close();
            audioSource.Close();
        }
Example #22
0
		static int Main(string[] args)
		{
			TextWriter stdout = Console.Out;
			Console.SetOut(Console.Error);

			DateTime start = DateTime.Now;
			TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
			bool debug = false, quiet = false;
			string prediction_type = null;
			string stereo_method = null;
			string window_method = null;
			string order_method = null;
			string window_function = null;
			string input_file = null;
			string output_file = null;
			int min_partition_order = -1, max_partition_order = -1,
				min_lpc_order = -1, max_lpc_order = -1,
				min_fixed_order = -1, max_fixed_order = -1,
				min_precision = -1, max_precision = -1,
				blocksize = -1, estimation_depth = -1;
			int level = -1, padding = -1, vbr_mode = -1;
			bool do_md5 = true, do_seektable = true, do_verify = false;
			bool buffered = false;

			for (int arg = 0; arg < args.Length; arg++)
			{
				bool ok = true;
				if (args[arg].Length == 0)
					ok = false;
				else if (args[arg] == "--debug")
					debug = true;
				else if ((args[arg] == "-q" || args[arg] == "--quiet"))
					quiet = true;
				else if (args[arg] == "--verify")
					do_verify = true;
				else if (args[arg] == "--no-seektable")
					do_seektable = false;
				else if (args[arg] == "--no-md5")
					do_md5 = false;
				else if (args[arg] == "--buffered")
					buffered = true;
				else if ((args[arg] == "-o" || args[arg] == "--output") && ++arg < args.Length)
					output_file = args[arg];
				else if ((args[arg] == "-t" || args[arg] == "--prediction-type") && ++arg < args.Length)
					prediction_type = args[arg];
				else if ((args[arg] == "-s" || args[arg] == "--stereo") && ++arg < args.Length)
					stereo_method = args[arg];
				else if ((args[arg] == "-m" || args[arg] == "--order-method") && ++arg < args.Length)
					order_method = args[arg];
				else if ((args[arg] == "-w" || args[arg] == "--window") && ++arg < args.Length)
					window_function = args[arg];
				else if (args[arg] == "--window-method" && ++arg < args.Length)
					window_method = args[arg];
				else if ((args[arg] == "-r" || args[arg] == "--partition-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_partition_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_partition_order)) ||
						int.TryParse(args[arg], out max_partition_order);
				}
				else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_lpc_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_lpc_order)) ||
						int.TryParse(args[arg], out max_lpc_order);
				}
				else if ((args[arg] == "-f" || args[arg] == "--fixed-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_fixed_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_fixed_order)) ||
						int.TryParse(args[arg], out max_fixed_order);
				}
				else if ((args[arg] == "-e" || args[arg] == "--estimation-depth") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out estimation_depth);
				else if ((args[arg] == "-c" || args[arg] == "--max-precision") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_precision) &&
						int.TryParse(args[arg].Split(',')[1], out max_precision)) ||
						int.TryParse(args[arg], out max_precision);
				}
				else if ((args[arg] == "-v" || args[arg] == "--vbr"))
					ok = (++arg < args.Length) && int.TryParse(args[arg], out vbr_mode);
				else if ((args[arg] == "-b" || args[arg] == "--blocksize") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out blocksize);
				else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out padding);
				else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out level))
					ok = level >= 0 && level <= 11;
				else if ((args[arg][0] != '-' || args[arg] == "-") && input_file == null)
					input_file = args[arg];
				else
					ok = false;
				if (!ok)
				{
					Usage();
					return 1;
				}
			}
			if (input_file == null || ((input_file == "-" || Path.GetExtension(input_file) == ".flac") && output_file == null))
			{
				Usage();
				return 2;
			}

			if (!quiet)
			{
				Console.WriteLine("CUETools.Flake, Copyright (C) 2009 Grigory Chudov.");
				Console.WriteLine("Based on Flake encoder by Justin Ruggles, <http://flake-enc.sourceforge.net/>.");
				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.");
			}

			IAudioSource audioSource;
			if (input_file == "-")
				audioSource = new WAVReader("", Console.OpenStandardInput());
			else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".wav")
				audioSource = new WAVReader(input_file, null);
			else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".flac")
				audioSource = new FlakeReader(input_file, null);
			else
			{
				Usage();
				return 3;
			}
			if (buffered)
				audioSource = new AudioPipe(audioSource, 0x10000);
			if (output_file == null)
				output_file = Path.ChangeExtension(input_file, "flac");
			FlakeWriter flake = new FlakeWriter((output_file == "-" || output_file == "nul") ? "" : output_file,				
				output_file == "-" ? Console.OpenStandardOutput() :
				output_file == "nul" ? new NullStream() : null,
				audioSource.PCM);
			flake.FinalSampleCount = audioSource.Length;
			IAudioDest audioDest = flake;
			AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);

			try
			{
				if (level >= 0)
					flake.CompressionLevel = level;
				if (prediction_type != null)
					flake.PredictionType = Flake.LookupPredictionType(prediction_type);
				if (stereo_method != null)
					flake.StereoMethod = Flake.LookupStereoMethod(stereo_method);
				if (window_method != null)
					flake.WindowMethod = Flake.LookupWindowMethod(window_method);
				if (order_method != null)
					flake.OrderMethod = Flake.LookupOrderMethod(order_method);
				if (window_function != null)
					flake.WindowFunction = Flake.LookupWindowFunction(window_function);
				if (min_partition_order >= 0)
					flake.MinPartitionOrder = min_partition_order;
				if (max_partition_order >= 0)
					flake.MaxPartitionOrder = max_partition_order;
				if (min_lpc_order >= 0)
					flake.MinLPCOrder = min_lpc_order;
				if (max_lpc_order >= 0)
					flake.MaxLPCOrder = max_lpc_order;
				if (min_fixed_order >= 0)
					flake.MinFixedOrder = min_fixed_order;
				if (max_fixed_order >= 0)
					flake.MaxFixedOrder = max_fixed_order;
				if (max_precision >= 0)
					flake.MaxPrecisionSearch = max_precision;
				if (min_precision >= 0)
					flake.MinPrecisionSearch = min_precision;
				if (blocksize >= 0)
					flake.BlockSize = blocksize;
				if (estimation_depth >= 0)
					flake.EstimationDepth = estimation_depth;
				if (padding >= 0)
					flake.Padding = padding;
				if (vbr_mode >= 0)
					flake.VBRMode = vbr_mode;
				flake.DoSeekTable = do_seektable;
				(flake.Settings as FlakeWriterSettings).DoVerify = do_verify;
				(flake.Settings as FlakeWriterSettings).DoMD5 = do_md5;
			}
			catch (Exception ex)
			{
				Usage();
				Console.WriteLine("");
				Console.WriteLine("Error: {0}.", ex.Message);
				return 4;
			}

			if (!quiet)
			{
				Console.WriteLine("Filename  : {0}", input_file);
				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));
			}

#if !DEBUG
			try
#endif
			{
				while (audioSource.Read(buff, -1) != 0)
				{
					audioDest.Write(buff);
					TimeSpan elapsed = DateTime.Now - start;
					if (!quiet)
					{
						if ((elapsed - lastPrint).TotalMilliseconds > 60)
						{
							Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
								100.0 * audioSource.Position / audioSource.Length,
								audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
								elapsed,
								TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * audioSource.Length)
								);
							lastPrint = elapsed;
						}
					}
				}
				audioDest.Close();
			}
#if !DEBUG
			catch (Exception ex)
			{
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Error     : {0}", ex.Message);
				audioDest.Delete();
				audioSource.Close();
				return 5;
			}
#endif

			TimeSpan totalElapsed = DateTime.Now - start;
			if (!quiet)
			{
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Results   : {0:0.00}x; {2} bytes in {1} seconds;",
					audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
					totalElapsed,
					flake.TotalSize
					);
			}
			audioSource.Close();

			if (debug)
			{
				Console.SetOut(stdout);
				Console.Out.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}..{7}\t{8}..{9}\t{10}..{11}\t{12}..{13}\t{14}\t{15}",
					flake.TotalSize,
					flake.UserProcessorTime.TotalSeconds > 0 ? flake.UserProcessorTime.TotalSeconds : totalElapsed.TotalSeconds,
					flake.PredictionType.ToString().PadRight(15),
					flake.StereoMethod.ToString().PadRight(15),
					(flake.OrderMethod.ToString() + "(" + flake.EstimationDepth.ToString() + ")").PadRight(15),
					flake.WindowFunction,
					flake.MinPartitionOrder,
					flake.MaxPartitionOrder,
					flake.MinLPCOrder,
					flake.MaxLPCOrder,
					flake.MinFixedOrder,
					flake.MaxFixedOrder,
					flake.MinPrecisionSearch,
					flake.MaxPrecisionSearch,
					flake.BlockSize,
					flake.VBRMode
					);
			}
			return 0;
		}
Example #23
0
		static int Main(string[] args)
		{
			TextWriter stdout = Console.Out;
			Console.SetOut(Console.Error);

			DateTime start = DateTime.Now;
			TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
			bool debug = false, quiet = false;
			string stereo_method = null;
			string window_function = null;
			string input_file = null;
			string output_file = null;
			int min_partition_order = -1, max_partition_order = -1,
				min_lpc_order = -1, max_lpc_order = -1,
				min_fixed_order = -1, max_fixed_order = -1,
				min_precision = -1, max_precision = -1,
				orders_per_window = -1,
				blocksize = -1;
			int level = -1, padding = -1, vbr_mode = -1;
			bool do_md5 = true, do_seektable = true, do_verify = false, gpu_only = true, use_lattice = false;
			bool buffered = false;
			int cpu_threads = 0;
			bool ok = true;

			for (int arg = 0; arg < args.Length; arg++)
			{
				if (args[arg].Length == 0)
					ok = false;
				else if (args[arg] == "--debug")
					debug = true;
				else if ((args[arg] == "-q" || args[arg] == "--quiet"))
					quiet = true;
				else if (args[arg] == "--verify")
					do_verify = true;
				else if (args[arg] == "--no-seektable")
					do_seektable = false;
				else if (args[arg] == "--slow-gpu")
					gpu_only = false;
				else if (args[arg] == "--use-lattice")
					use_lattice = true;
				else if (args[arg] == "--no-md5")
					do_md5 = false;
				else if (args[arg] == "--buffered")
					buffered = true;
				else if (args[arg] == "--cpu-threads")
					ok = (++arg < args.Length) && int.TryParse(args[arg], out cpu_threads);
				else if ((args[arg] == "-o" || args[arg] == "--output") && ++arg < args.Length)
					output_file = args[arg];
				else if ((args[arg] == "-s" || args[arg] == "--stereo") && ++arg < args.Length)
					stereo_method = args[arg];
				else if ((args[arg] == "-w" || args[arg] == "--window") && ++arg < args.Length)
					window_function = args[arg];
				else if ((args[arg] == "-r" || args[arg] == "--partition-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_partition_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_partition_order)) ||
						int.TryParse(args[arg], out max_partition_order);
				}
				else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_lpc_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_lpc_order)) ||
						int.TryParse(args[arg], out max_lpc_order);
				}
				else if (args[arg] == "--fixed-order" && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_fixed_order) &&
						int.TryParse(args[arg].Split(',')[1], out max_fixed_order)) ||
						int.TryParse(args[arg], out max_fixed_order);
				}
				else if ((args[arg] == "-c" || args[arg] == "--max-precision") && ++arg < args.Length)
				{
					ok = (args[arg].Split(',').Length == 2 &&
						int.TryParse(args[arg].Split(',')[0], out min_precision) &&
						int.TryParse(args[arg].Split(',')[1], out max_precision)) ||
						int.TryParse(args[arg], out max_precision);
				}
				else if ((args[arg] == "-v" || args[arg] == "--vbr"))
					ok = (++arg < args.Length) && int.TryParse(args[arg], out vbr_mode);
				else if (args[arg] == "--orders-per-window")
					ok = (++arg < args.Length) && int.TryParse(args[arg], out orders_per_window);					
				else if ((args[arg] == "-b" || args[arg] == "--blocksize") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out blocksize);
				else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length)
					ok = int.TryParse(args[arg], out padding);
				else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out level))
					ok = level >= 0 && level <= 11;
				else if ((args[arg][0] != '-' || args[arg] == "-") && input_file == null)
					input_file = args[arg];
				else
					ok = false;
				if (!ok)
					break;
			}
			if (!quiet)
			{
				Console.WriteLine("{0}, Copyright (C) 2009 Grigory Chudov.", FlaCudaWriter.vendor_string);
				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 (!ok || input_file == null)
			{
				Usage();
				return 1;
			}

			if (((input_file == "-" || Path.GetExtension(input_file) == ".flac") && output_file == null))
			{
				Console.WriteLine();
				Console.WriteLine("Output file not specified.");
				Console.WriteLine();
				Usage();
				return 2;
			}

			IAudioSource audioSource;
			if (input_file == "-")
				audioSource = new WAVReader("", Console.OpenStandardInput());
			else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".wav")
				audioSource = new WAVReader(input_file, null);
			else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".flac")
				audioSource = new FlakeReader(input_file, null);
			else
			{
				Usage();
				return 2;
			}
			if (buffered)
				audioSource = new AudioPipe(audioSource, FlaCudaWriter.MAX_BLOCKSIZE);
			if (output_file == null)
				output_file = Path.ChangeExtension(input_file, "flac");
			FlaCudaWriter encoder = new FlaCudaWriter((output_file == "-" || output_file == "nul") ? "" : output_file,
				output_file == "-" ? Console.OpenStandardOutput() :
				output_file == "nul" ? new NullStream() : null,
				audioSource.PCM);
			encoder.FinalSampleCount = audioSource.Length;
			IAudioDest audioDest = encoder;
			AudioBuffer buff = new AudioBuffer(audioSource, FlaCudaWriter.MAX_BLOCKSIZE);

			try
			{
				(encoder.Settings as FlaCudaWriterSettings).GPUOnly = gpu_only;
				(encoder.Settings as FlaCudaWriterSettings).CPUThreads = cpu_threads;
				(encoder.Settings as FlaCudaWriterSettings).DoVerify = do_verify;
				(encoder.Settings as FlaCudaWriterSettings).DoMD5 = do_md5;
				if (level >= 0)
					encoder.CompressionLevel = level;
				if (stereo_method != null)
					encoder.StereoMethod = Flake.LookupStereoMethod(stereo_method);
				if (window_function != null)
					encoder.WindowFunction = Flake.LookupWindowFunction(window_function);
				if (min_partition_order >= 0)
					encoder.MinPartitionOrder = min_partition_order;
				if (max_partition_order >= 0)
					encoder.MaxPartitionOrder = max_partition_order;
				if (min_lpc_order >= 0)
					encoder.MinLPCOrder = min_lpc_order;
				if (max_lpc_order >= 0)
					encoder.MaxLPCOrder = max_lpc_order;
				if (min_fixed_order >= 0)
					encoder.MinFixedOrder = min_fixed_order;
				if (max_fixed_order >= 0)
					encoder.MaxFixedOrder = max_fixed_order;
				if (max_precision >= 0)
					encoder.MaxPrecisionSearch = max_precision;
				if (min_precision >= 0)
					encoder.MinPrecisionSearch = min_precision;
				if (blocksize >= 0)
					encoder.BlockSize = blocksize;
				if (padding >= 0)
					encoder.Padding = padding;
				if (vbr_mode >= 0)
					encoder.VBRMode = vbr_mode;
				if (orders_per_window >= 0)
					encoder.OrdersPerWindow = orders_per_window;
				encoder.UseLattice = use_lattice;
				encoder.DoSeekTable = do_seektable;
			}
			catch (Exception ex)
			{
				Usage();
				Console.WriteLine("");
				Console.WriteLine("Error: {0}.", ex.Message);
				return 3;
			}

			if (!quiet)
			{
				Console.WriteLine("Filename  : {0}", input_file);
				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));
			}

#if !DEBUG
			try
#endif
			{
				while (audioSource.Read(buff, -1) != 0)
				{
					audioDest.Write(buff);
					TimeSpan elapsed = DateTime.Now - start;
					if (!quiet)
					{
						if ((elapsed - lastPrint).TotalMilliseconds > 60)
						{
							Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
								100.0 * audioSource.Position / audioSource.Length,
								audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
								elapsed,
								TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * audioSource.Length)
								);
							lastPrint = elapsed;
						}
					}
				}
				audioDest.Close();
			}
#if !DEBUG
			catch (Exception ex)
			{
			    Console.Error.Write("\r                                                                         \r");
			    Console.WriteLine("Error     : {0}", ex.Message);
			    audioDest.Delete();
			    audioSource.Close();
			    return 4;
			}
#endif

			TimeSpan totalElapsed = DateTime.Now - start;
			if (!quiet)
			{
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Results   : {0:0.00}x; {2} bytes in {1} seconds;",
					audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
					totalElapsed,
					encoder.TotalSize
					);
			}
			audioSource.Close();

			if (debug)
			{
				Console.SetOut(stdout);
				Console.Out.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}..{5}\t{6}..{7}\t{8}..{9}\t{10}\t{11}",
					encoder.TotalSize,
					encoder.UserProcessorTime.TotalSeconds > 0 ? encoder.UserProcessorTime.TotalSeconds : totalElapsed.TotalSeconds,
					encoder.StereoMethod.ToString().PadRight(15),
					encoder.WindowFunction.ToString().PadRight(15),
					encoder.MinPartitionOrder,
					encoder.MaxPartitionOrder,
					encoder.MinLPCOrder,
					encoder.MaxLPCOrder,
					encoder.MinPrecisionSearch,
					encoder.MaxPrecisionSearch,
					encoder.BlockSize,
					encoder.VBRMode
					);
			}
			return 0;
		}
Example #24
0
        private byte[] Wav2Flac(MemoryStream waveStreamMemory)
        {
            if (waveStreamMemory.Length >= 3200) // 0
            {
                Log.Write("Ева услышала Вас.", Log.Category.Information);
                byte[] Array = null;

                WaveFileWriter writer = new WaveFileWriter("C:\\rec_temp.wav", waveInEvent.WaveFormat);
                writer.Write(waveStreamMemory.ToArray(), 0, waveStreamMemory.ToArray().Length);
                writer.Close();

                IAudioSource audioSource = new WAVReader("C:\\rec_temp.wav", null);
                AudioPCMConfig audioPCMConfig = new AudioPCMConfig(16, 1, 16000);

                AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);
                //AudioBuffer buffMemory = new AudioBuffer(audioPCMConfig, waveStreamMemory.ToArray(), Convert.ToInt32(waveStreamMemory.Length) / audioPCMConfig.BlockAlign);

                FlakeWriter flakewriter = new FlakeWriter(null, audioSource.PCM);

                FlakeWriter audioDest = flakewriter;
                while (audioSource.Read(buff, -1) != 0)
                {
                    audioDest.Write(buff);
                }

                if (flakewriter.BufferMemory != null)
                {
                    Array = flakewriter.BufferMemory.ToArray();
                }

                audioDest.Close();
                audioSource.Close();

                return Array;
            }

            return null;
        }