Пример #1
0
        public FlakeFileReader(string path)
        {
            _flakeFileReader = new FlakeReader(path, null);
            _streamInfo = _flakeFileReader.PCM;
            _waveFormat =  new WaveFormat(_streamInfo.SampleRate, _streamInfo.BitsPerSample, _streamInfo.ChannelCount);

            var len = 65546 * _streamInfo.BitsPerSample / 8 * _streamInfo.ChannelCount;
            _audioBuffer = new AudioBuffer(_streamInfo, len);
            _decompressBuffer = new byte[len];
        }
Пример #2
0
		int flake_encode_init()
		{
			int i, header_len;

			//if(flake_validate_params(s) < 0)

			ch_code = channels - 1;

			// find samplerate in table
			for (i = 4; i < 12; i++)
			{
				if (_pcm.SampleRate == Flake.flac_samplerates[i])
				{
					sr_code0 = i;
					break;
				}
			}

			// if not in table, samplerate is non-standard
			if (i == 12)
				throw new Exception("non-standard samplerate");

			for (i = 1; i < 8; i++)
			{
				if (_pcm.BitsPerSample == Flake.flac_bitdepths[i])
				{
					bps_code = i;
					break;
				}
			}
			if (i == 8)
				throw new Exception("non-standard bps");

			if (_blocksize == 0)
			{
				if (eparams.block_size == 0)
					eparams.block_size = select_blocksize(_pcm.SampleRate, eparams.block_time_ms);
				_blocksize = eparams.block_size;
			}
			else
				eparams.block_size = _blocksize;

			// set maximum encoded frame size (if larger, re-encodes in verbatim mode)
			if (channels == 2)
				max_frame_size = 16 + ((eparams.block_size * (_pcm.BitsPerSample + _pcm.BitsPerSample + 1) + 7) >> 3);
			else
				max_frame_size = 16 + ((eparams.block_size * channels * _pcm.BitsPerSample + 7) >> 3);

			if (_IO.CanSeek && eparams.do_seektable && sample_count > 0)
			{
				int seek_points_distance = _pcm.SampleRate * 10;
				int num_seek_points = 1 + sample_count / seek_points_distance; // 1 seek point per 10 seconds
				if (sample_count % seek_points_distance == 0)
					num_seek_points--;
				seek_table = new SeekPoint[num_seek_points];
				for (int sp = 0; sp < num_seek_points; sp++)
				{
					seek_table[sp].framesize = 0;
					seek_table[sp].offset = 0;
					seek_table[sp].number = sp * seek_points_distance;
				}
			}

			// output header bytes
			header = new byte[eparams.padding_size + 1024 + (seek_table == null ? 0 : seek_table.Length * 18)];
			header_len = write_headers();

			// initialize CRC & MD5
			if (_IO.CanSeek && _settings.DoMD5)
				md5 = new MD5CryptoServiceProvider();

			if (_settings.DoVerify)
			{
				verify = new FlakeReader(_pcm);
				verifyBuffer = new int[Flake.MAX_BLOCKSIZE * channels];
			}

			frame_buffer = new byte[max_frame_size];

			return header_len;
		}
Пример #3
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;
		}
Пример #4
0
		unsafe public FLACCLTask(Program _openCLProgram, int channelsCount, int channels, uint bits_per_sample, int max_frame_size, FLACCLWriter writer, int groupSize, bool gpuOnly, bool gpuRice)
		{
			this.UseGPUOnly = gpuOnly;
			this.UseGPURice = gpuOnly && gpuRice;
			this.UseMappedMemory = writer._settings.MappedMemory || writer._settings.DeviceType == OpenCLDeviceType.CPU;
			this.groupSize = groupSize;
			this.channels = channels;
			this.channelsCount = channelsCount;
			this.writer = writer;
			openCLProgram = _openCLProgram;
#if DEBUG
			var prop = CommandQueueProperties.PROFILING_ENABLE;
#else
			var prop = CommandQueueProperties.NONE;
#endif
			openCLCQ = openCLProgram.Context.CreateCommandQueue(openCLProgram.Context.Devices[0], prop);

            int MAX_ORDER = this.writer.eparams.max_prediction_order;
			int MAX_FRAMES = this.writer.framesPerTask;
			int MAX_CHANNELSIZE = MAX_FRAMES * ((writer.eparams.block_size + 3) & ~3);
			residualTasksLen = sizeof(FLACCLSubframeTask) * 32 * channelsCount * MAX_FRAMES;
			bestResidualTasksLen = sizeof(FLACCLSubframeTask) * channels * MAX_FRAMES;
			int samplesBufferLen = writer.PCM.BlockAlign * MAX_CHANNELSIZE * channelsCount;
			int residualBufferLen = sizeof(int) * MAX_CHANNELSIZE * channels; // need to adjust residualOffset?
			int partitionsLen = sizeof(int) * ((writer.PCM.BitsPerSample > 16 ? 31 : 15) * 2 << 8) * channels * MAX_FRAMES;
			int riceParamsLen = sizeof(int) * (4 << 8) * channels * MAX_FRAMES;
			int autocorLen = sizeof(float) * (MAX_ORDER + 1) * lpc.MAX_LPC_WINDOWS * channelsCount * MAX_FRAMES;
            int lpcDataLen = autocorLen * 32;
			int resOutLen = sizeof(int) * channelsCount * (lpc.MAX_LPC_WINDOWS * lpc.MAX_LPC_ORDER + 8) * MAX_FRAMES;
			int wndLen = sizeof(float) * MAX_CHANNELSIZE /** 2*/ * lpc.MAX_LPC_WINDOWS;
			int selectedLen = sizeof(int) * 32 * channelsCount * MAX_FRAMES;
			int riceLen = sizeof(int) * channels * MAX_CHANNELSIZE;

            if (!this.UseMappedMemory)
            {
                clSamplesBytes = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, samplesBufferLen / 2);
				clResidual = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, residualBufferLen);
                clBestRiceParams = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, riceParamsLen / 4);
                clResidualTasks = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, residualTasksLen);
                clBestResidualTasks = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, bestResidualTasksLen);
                clWindowFunctions = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, wndLen);
				clSelectedTasks = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, selectedLen);
				clRiceOutput = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, riceLen);

                clSamplesBytesPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, samplesBufferLen / 2);
				clResidualPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, residualBufferLen);
                clBestRiceParamsPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, riceParamsLen / 4);
                clResidualTasksPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, residualTasksLen);
                clBestResidualTasksPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, bestResidualTasksLen);
                clWindowFunctionsPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, wndLen);
				clSelectedTasksPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, selectedLen);
				clRiceOutputPinned = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, riceLen);

                clSamplesBytesPtr = openCLCQ.EnqueueMapBuffer(clSamplesBytesPinned, true, MapFlags.READ_WRITE, 0, samplesBufferLen / 2);
				clResidualPtr = openCLCQ.EnqueueMapBuffer(clResidualPinned, true, MapFlags.READ_WRITE, 0, residualBufferLen);
				clBestRiceParamsPtr = openCLCQ.EnqueueMapBuffer(clBestRiceParamsPinned, true, MapFlags.READ_WRITE, 0, riceParamsLen / 4);
				clResidualTasksPtr = openCLCQ.EnqueueMapBuffer(clResidualTasksPinned, true, MapFlags.READ_WRITE, 0, residualTasksLen);
				clBestResidualTasksPtr = openCLCQ.EnqueueMapBuffer(clBestResidualTasksPinned, true, MapFlags.READ_WRITE, 0, bestResidualTasksLen);
				clWindowFunctionsPtr = openCLCQ.EnqueueMapBuffer(clWindowFunctionsPinned, true, MapFlags.READ_WRITE, 0, wndLen);
				clSelectedTasksPtr = openCLCQ.EnqueueMapBuffer(clSelectedTasksPinned, true, MapFlags.READ_WRITE, 0, selectedLen);
				clRiceOutputPtr = openCLCQ.EnqueueMapBuffer(clRiceOutputPinned, true, MapFlags.READ_WRITE, 0, riceLen);
			}
            else
            {
                clSamplesBytes = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, (uint)samplesBufferLen / 2);
				clResidual = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, residualBufferLen);
                clBestRiceParams = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, riceParamsLen / 4);
                clResidualTasks = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, residualTasksLen);
                clBestResidualTasks = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, bestResidualTasksLen);
                clWindowFunctions = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, wndLen);
				clSelectedTasks = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, selectedLen);
				clRiceOutput = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE | MemFlags.ALLOC_HOST_PTR, riceLen);

				clSamplesBytesPtr = openCLCQ.EnqueueMapBuffer(clSamplesBytes, true, MapFlags.READ_WRITE, 0, samplesBufferLen / 2);
				clResidualPtr = openCLCQ.EnqueueMapBuffer(clResidual, true, MapFlags.READ_WRITE, 0, residualBufferLen);
				clBestRiceParamsPtr = openCLCQ.EnqueueMapBuffer(clBestRiceParams, true, MapFlags.READ_WRITE, 0, riceParamsLen / 4);
				clResidualTasksPtr = openCLCQ.EnqueueMapBuffer(clResidualTasks, true, MapFlags.READ_WRITE, 0, residualTasksLen);
				clBestResidualTasksPtr = openCLCQ.EnqueueMapBuffer(clBestResidualTasks, true, MapFlags.READ_WRITE, 0, bestResidualTasksLen);
				clWindowFunctionsPtr = openCLCQ.EnqueueMapBuffer(clWindowFunctions, true, MapFlags.READ_WRITE, 0, wndLen);
				clSelectedTasksPtr = openCLCQ.EnqueueMapBuffer(clSelectedTasks, true, MapFlags.READ_WRITE, 0, selectedLen);
				clRiceOutputPtr = openCLCQ.EnqueueMapBuffer(clRiceOutput, true, MapFlags.READ_WRITE, 0, riceLen);

                //clSamplesBytesPtr = clSamplesBytes.HostPtr;
                //clResidualPtr = clResidual.HostPtr;
                //clBestRiceParamsPtr = clBestRiceParams.HostPtr;
                //clResidualTasksPtr = clResidualTasks.HostPtr;
                //clBestResidualTasksPtr = clBestResidualTasks.HostPtr;
                //clWindowFunctionsPtr = clWindowFunctions.HostPtr;
            }

            clSamples = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, samplesBufferLen);
            clLPCData = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, lpcDataLen);
            clAutocorOutput = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, autocorLen);
			clSelectedTasksSecondEstimate = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, selectedLen);
			clSelectedTasksBestMethod = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, selectedLen);
			if (UseGPUOnly)
            {
                clPartitions = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, partitionsLen);
                clRiceParams = openCLProgram.Context.CreateBuffer(MemFlags.READ_WRITE, riceParamsLen);
            }

            //openCLCQ.EnqueueMapBuffer(clSamplesBytes, true, MapFlags.WRITE, 0, samplesBufferLen / 2);

            clComputeAutocor = openCLProgram.CreateKernel("clComputeAutocor");
			clStereoDecorr = openCLProgram.CreateKernel("clStereoDecorr");
			//cudaChannelDecorr = openCLProgram.CreateKernel("clChannelDecorr");
			clChannelDecorr2 = openCLProgram.CreateKernel("clChannelDecorr2");
			clChannelDecorrX = openCLProgram.CreateKernel("clChannelDecorrX");
			clFindWastedBits = openCLProgram.CreateKernel("clFindWastedBits");
			clComputeLPC = openCLProgram.CreateKernel("clComputeLPC");
			clQuantizeLPC = openCLProgram.CreateKernel("clQuantizeLPC");
			//cudaComputeLPCLattice = openCLProgram.CreateKernel("clComputeLPCLattice");
            clSelectStereoTasks = openCLProgram.CreateKernel("clSelectStereoTasks");
			clEstimateResidual = openCLProgram.CreateKernel("clEstimateResidual");
			clChooseBestMethod = openCLProgram.CreateKernel("clChooseBestMethod");
			if (UseGPUOnly)
			{
				clEncodeResidual = openCLProgram.CreateKernel("clEncodeResidual");
				if (openCLCQ.Device.DeviceType != DeviceType.CPU)
				{
					clCalcPartition = openCLProgram.CreateKernel("clCalcPartition");
					clCalcPartition16 = openCLProgram.CreateKernel("clCalcPartition16");
				}
				clSumPartition = openCLProgram.CreateKernel("clSumPartition");
				clFindRiceParameter = openCLProgram.CreateKernel("clFindRiceParameter");
				clFindPartitionOrder = openCLProgram.CreateKernel("clFindPartitionOrder");
				if (UseGPURice)
				{
					clCalcOutputOffsets = openCLProgram.CreateKernel("clCalcOutputOffsets");
					clRiceEncoding = openCLProgram.CreateKernel("clRiceEncoding");
				}
			}

			samplesBuffer = new int[MAX_CHANNELSIZE * channelsCount];
			outputBuffer = new byte[max_frame_size * MAX_FRAMES + 1];
			frame = new FlacFrame(channelsCount);
			frame.writer = new BitWriter(outputBuffer, 0, outputBuffer.Length);

			if (writer._settings.DoVerify)
			{
				verify = new FlakeReader(new AudioPCMConfig((int)bits_per_sample, channels, 44100));
				verify.DoCRC = false;
			}
		}
Пример #5
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;
		}
Пример #6
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;
		}
Пример #7
0
 public void SeekTest()
 {
     var r = new FlakeReader("test.flac", null);
     var buff1 = new AudioBuffer(r, 16536);
     var buff2 = new AudioBuffer(r, 16536);
     Assert.AreEqual(0, r.Position);
     r.Read(buff1, 7777);
     Assert.AreEqual(7777, r.Position);
     r.Position = 0;
     Assert.AreEqual(0, r.Position);
     r.Read(buff2, 7777);
     Assert.AreEqual(7777, r.Position);
     AudioBufferTest.AreEqual(buff1, buff2);
     r.Read(buff1, 7777);
     Assert.AreEqual(7777 + 7777, r.Position);
     r.Position = 7777;
     Assert.AreEqual(7777, r.Position);
     r.Read(buff2, 7777);
     Assert.AreEqual(7777 + 7777, r.Position);
     AudioBufferTest.AreEqual(buff1, buff2);
     r.Close();
 }
Пример #8
0
		unsafe public FlaCudaTask(CUDA _cuda, int channelCount, int channels, uint bits_per_sample, int max_frame_size, bool do_verify)
		{
			cuda = _cuda;

			residualTasksLen = sizeof(FlaCudaSubframeTask) * channelCount * (lpc.MAX_LPC_ORDER * lpc.MAX_LPC_WINDOWS + 8) * FlaCudaWriter.maxFrames;
			bestResidualTasksLen = sizeof(FlaCudaSubframeTask) * channelCount * FlaCudaWriter.maxFrames;
			samplesBufferLen = sizeof(int) * FlaCudaWriter.MAX_BLOCKSIZE * channelCount;
			int partitionsLen = sizeof(int) * (30 << 8) * channelCount * FlaCudaWriter.maxFrames;
			int riceParamsLen = sizeof(int) * (4 << 8) * channelCount * FlaCudaWriter.maxFrames;
			int lpcDataLen = sizeof(float) * 32 * 33 * lpc.MAX_LPC_WINDOWS * channelCount * FlaCudaWriter.maxFrames;

			cudaSamplesBytes = cuda.Allocate((uint)samplesBufferLen / 2);
			cudaSamples = cuda.Allocate((uint)samplesBufferLen);
			cudaResidual = cuda.Allocate((uint)samplesBufferLen);
			cudaLPCData = cuda.Allocate((uint)lpcDataLen);
			cudaPartitions = cuda.Allocate((uint)partitionsLen);
			cudaRiceParams = cuda.Allocate((uint)riceParamsLen);
			cudaBestRiceParams = cuda.Allocate((uint)riceParamsLen / 4);
			cudaAutocorOutput = cuda.Allocate((uint)(sizeof(float) * channelCount * lpc.MAX_LPC_WINDOWS * (lpc.MAX_LPC_ORDER + 1) * (FlaCudaWriter.maxAutocorParts + FlaCudaWriter.maxFrames)));
			cudaResidualTasks = cuda.Allocate((uint)residualTasksLen);
			cudaBestResidualTasks = cuda.Allocate((uint)bestResidualTasksLen);
			cudaResidualOutput = cuda.Allocate((uint)(sizeof(int) * channelCount * (lpc.MAX_LPC_WINDOWS * lpc.MAX_LPC_ORDER + 8) * 64 /*FlaCudaWriter.maxResidualParts*/ * FlaCudaWriter.maxFrames));
			CUResult cuErr = CUResult.Success;
			if (cuErr == CUResult.Success)
				cuErr = CUDADriver.cuMemAllocHost(ref samplesBytesPtr, (uint)samplesBufferLen/2);
			if (cuErr == CUResult.Success)
				cuErr = CUDADriver.cuMemAllocHost(ref residualBufferPtr, (uint)samplesBufferLen);
			if (cuErr == CUResult.Success)
				cuErr = CUDADriver.cuMemAllocHost(ref bestRiceParamsPtr, (uint)riceParamsLen / 4);
			if (cuErr == CUResult.Success)
				cuErr = CUDADriver.cuMemAllocHost(ref residualTasksPtr, (uint)residualTasksLen);
			if (cuErr == CUResult.Success)
				cuErr = CUDADriver.cuMemAllocHost(ref bestResidualTasksPtr, (uint)bestResidualTasksLen);
			if (cuErr != CUResult.Success)
			{
				if (samplesBytesPtr != IntPtr.Zero) CUDADriver.cuMemFreeHost(samplesBytesPtr); samplesBytesPtr = IntPtr.Zero;
				if (residualBufferPtr != IntPtr.Zero) CUDADriver.cuMemFreeHost(residualBufferPtr); residualBufferPtr = IntPtr.Zero;
				if (bestRiceParamsPtr != IntPtr.Zero) CUDADriver.cuMemFreeHost(bestRiceParamsPtr); bestRiceParamsPtr = IntPtr.Zero;
				if (residualTasksPtr != IntPtr.Zero) CUDADriver.cuMemFreeHost(residualTasksPtr); residualTasksPtr = IntPtr.Zero;
				if (bestResidualTasksPtr != IntPtr.Zero) CUDADriver.cuMemFreeHost(bestResidualTasksPtr); bestResidualTasksPtr = IntPtr.Zero;
				throw new CUDAException(cuErr);
			}

			cudaComputeAutocor = cuda.GetModuleFunction("cudaComputeAutocor");
			cudaStereoDecorr = cuda.GetModuleFunction("cudaStereoDecorr");
			cudaChannelDecorr = cuda.GetModuleFunction("cudaChannelDecorr");
			cudaChannelDecorr2 = cuda.GetModuleFunction("cudaChannelDecorr2");
			cudaFindWastedBits = cuda.GetModuleFunction("cudaFindWastedBits");
			cudaComputeLPC = cuda.GetModuleFunction("cudaComputeLPC");
			cudaQuantizeLPC = cuda.GetModuleFunction("cudaQuantizeLPC");
			cudaComputeLPCLattice = cuda.GetModuleFunction("cudaComputeLPCLattice");
			cudaEstimateResidual = cuda.GetModuleFunction("cudaEstimateResidual");
			cudaEstimateResidual8 = cuda.GetModuleFunction("cudaEstimateResidual8");
			cudaEstimateResidual12 = cuda.GetModuleFunction("cudaEstimateResidual12");
			cudaEstimateResidual1 = cuda.GetModuleFunction("cudaEstimateResidual1");
			cudaChooseBestMethod = cuda.GetModuleFunction("cudaChooseBestMethod");
			cudaCopyBestMethod = cuda.GetModuleFunction("cudaCopyBestMethod");
			cudaCopyBestMethodStereo = cuda.GetModuleFunction("cudaCopyBestMethodStereo");
			cudaEncodeResidual = cuda.GetModuleFunction("cudaEncodeResidual");
			cudaCalcPartition = cuda.GetModuleFunction("cudaCalcPartition");
			cudaCalcPartition16 = cuda.GetModuleFunction("cudaCalcPartition16");
			cudaCalcLargePartition = cuda.GetModuleFunction("cudaCalcLargePartition");
			cudaSumPartition = cuda.GetModuleFunction("cudaSumPartition");
			cudaFindRiceParameter = cuda.GetModuleFunction("cudaFindRiceParameter");
			cudaFindPartitionOrder = cuda.GetModuleFunction("cudaFindPartitionOrder");

			stream = cuda.CreateStream();
			samplesBuffer = new int[FlaCudaWriter.MAX_BLOCKSIZE * channelCount];
			outputBuffer = new byte[max_frame_size * FlaCudaWriter.maxFrames + 1];
			frame = new FlacFrame(channelCount);
			frame.writer = new BitWriter(outputBuffer, 0, outputBuffer.Length);

			if (do_verify)
			{
				verify = new FlakeReader(new AudioPCMConfig((int)bits_per_sample, channels, 44100));
				verify.DoCRC = false;
			}
		}