コード例 #1
0
        public int Step(AudioBuffer sampleBuffer)
        {
            if (Remaining == 0)
            {
                return(0);
            }
            int copyCount = source.Read(sampleBuffer, Remaining);

            if (copyCount == 0)
            {
                return(0);
            }
            if (ar != null)
            {
                ar.Write(sampleBuffer);
            }
            if (hdcd != null)
            {
                hdcd.Write(sampleBuffer);
                if (cueSheet.Config.wait750FramesForHDCD && source.Position > start + 750 * 588 && string.Format("{0:s}", hdcd) == "")
                {
                    hdcd = null;
                }
            }
            return(copyCount);
        }
コード例 #2
0
 public void Prepare(IAudioDest dest)
 {
     if (dest.PCM.ChannelCount != PCM.ChannelCount || dest.PCM.BitsPerSample != PCM.BitsPerSample)
     {
         throw new Exception("AudioBuffer format mismatch");
     }
 }
コード例 #3
0
 public Sapi4AudioTarget(IAudioDest audioDest)
 {
     this.audioDest = audioDest;
     this.audio     = audioDest as IAudio;
     Sapi4Engine.miniLog(
         String.Format(
             "audio target created, AudioDest is {0}, Audio is {1}", audioDest, audio));
 }
コード例 #4
0
 public CUEToolsVerifyTask(CUESheet cueSheet, int start, int end, AccurateRipVerify ar)
     : this(cueSheet, start, end, ar, null)
 {
     if (cueSheet.Config.detectHDCD && CUEProcessorPlugins.hdcd != null)
     {
         try { this.hdcd = Activator.CreateInstance(CUEProcessorPlugins.hdcd, 2, 44100, 20, false) as IAudioDest; }
         catch { this.hdcd = null; }
     }
 }
コード例 #5
0
 public CUEToolsVerifyTask(CUESheet cueSheet, int start, int end, AccurateRipVerify ar)
     : this(cueSheet, start, end, ar, null)
 {
     if (cueSheet.Config.detectHDCD && CUEProcessorPlugins.hdcd != null)
     {
         try { this.hdcd = Activator.CreateInstance(CUEProcessorPlugins.hdcd, 2, 44100, 20, false) as IAudioDest; }
         catch { this.hdcd = null; }
     }
 }
コード例 #6
0
		public void Write(IAudioDest dest)
		{
			if (start < 0 || start > end || end > toc.AudioLength * 588)
				throw new ArgumentOutOfRangeException();
			var src = new NoiseAndErrorsGenerator(AudioPCMConfig.RedBook, end - start, seed, offset + start, errors, maxStrideErrors);
			var buff = new AudioBuffer(src, 588 * 10);
			var rnd = new Random(seed);
			//dest.Position = start;
			while (src.Remaining > 0)
			{
				src.Read(buff, rnd.Next(1, buff.Size));
				dest.Write(buff);
			}
		}
コード例 #7
0
 private CUEToolsVerifyTask(CUESheet cueSheet, int start, int end, AccurateRipVerify ar, IAudioDest hdcd)
 {
     this.cueSheet = cueSheet;
     this.start = start;
     this.end = end;
     this.source = new CUESheetAudio(cueSheet);
     if (cueSheet.IsCD || cueSheet.Config.separateDecodingThread)
         this.source = new AudioPipe(this.source, 0x10000);
     this.source.Position = start;
     this.ar = cueSheet.IsUsingAccurateRip ? ar : null;
     this.hdcd = hdcd;
     if (this.ar != null)
         this.ar.Position = start;
 }
コード例 #8
0
        public void Write(IAudioDest dest)
        {
            if (start < 0 || start > end || end > toc.AudioLength * 588)
            {
                throw new ArgumentOutOfRangeException();
            }
            var src  = new NoiseAndErrorsGenerator(AudioPCMConfig.RedBook, end - start, seed, offset + start, errors, maxStrideErrors);
            var buff = new AudioBuffer(src, 588 * 10);
            var rnd  = new Random(seed);

            //dest.Position = start;
            while (src.Remaining > 0)
            {
                src.Read(buff, rnd.Next(1, buff.Size));
                dest.Write(buff);
            }
        }
コード例 #9
0
 public int Step(AudioBuffer sampleBuffer)
 {
     if (Remaining == 0)
         return 0;
     int copyCount = source.Read(sampleBuffer, Remaining);
     if (copyCount == 0)
         return 0;
     if (ar != null)
         ar.Write(sampleBuffer);
     if (hdcd != null)
     {
         hdcd.Write(sampleBuffer);
         if (cueSheet.Config.wait750FramesForHDCD && source.Position > start + 750 * 588 && string.Format("{0:s}", hdcd) == "")
             hdcd = null;
     }
     return copyCount;
 }
コード例 #10
0
 private CUEToolsVerifyTask(CUESheet cueSheet, int start, int end, AccurateRipVerify ar, IAudioDest hdcd)
 {
     this.cueSheet = cueSheet;
     this.start    = start;
     this.end      = end;
     this.source   = new CUESheetAudio(cueSheet);
     if (cueSheet.IsCD || cueSheet.Config.separateDecodingThread)
     {
         this.source = new AudioPipe(this.source, 0x10000);
     }
     this.source.Position = start;
     this.ar   = cueSheet.IsUsingAccurateRip ? ar : null;
     this.hdcd = hdcd;
     if (this.ar != null)
     {
         this.ar.Position = start;
     }
 }
コード例 #11
0
ファイル: Main.cs プロジェクト: darealshinji/Moitah.net
        private IAudioDest GetAudioDest(string path, int finalSampleCount)
        {
            IAudioDest dest = AudioReadWrite.GetAudioDest(path, 16, 2, 44100, finalSampleCount);

            if (dest is FLACWriter)
            {
                FLACWriter w = (FLACWriter)dest;
                w.CompressionLevel = _flacCompressionLevel;
                w.Verify           = _flacVerify;
            }
            if (dest is WavPackWriter)
            {
                WavPackWriter w = (WavPackWriter)dest;
                w.CompressionMode = _wvCompressionMode;
                w.ExtraMode       = _wvExtraMode;
            }

            return(dest);
        }
コード例 #12
0
        public void Encode()
        {
            AudioBuffer buffer = new AudioBuffer(audioSource.PCM, BufferSize);

            this.AudioDest.FinalSampleCount = this.audioSource.Length;

            while (audioSource.Read(buffer, BufferSize) > 0)
            {
                if (this.trackGain != null)
                {
                    DspHelper.AnalyzeSamples(this.trackGain, buffer);
                }
                if (this.drMeter != null)
                {
                    this.drMeter.Feed(buffer.Samples, buffer.Length);
                }

                this.AudioDest.Write(buffer);

                ProgressChangedEventArgs eventArgs = new ProgressChangedEventArgs((double)this.audioSource.Position / this.audioSource.Length);
                this.OnProgressChanged(eventArgs);
                if (eventArgs.Cancel)
                {
                    this.AudioDest.Close();
                    this.AudioDest = null;
                    Utility.TryDeleteFile(this.targetFilename);
                    return;
                }
            }

            if (this.drMeter != null)
            {
                this.drMeter.Finish();
            }

            this.AudioDest.Close();
            this.AudioDest = null;

            if (this.tags != null)
            {
                this.tags.WriteToFile(this.targetFilename);
            }
        }
コード例 #13
0
        public void Dispose()
        {
            try
            {
                if (this.audioSource != null)
                {
                    this.audioSource.Close();
                    this.audioSource = null;
                }
            }
            catch { }

            try
            {
                if (this.AudioDest != null)
                {
                    this.AudioDest.Close();
                    this.AudioDest = null;
                }
            }
            catch { }
        }
コード例 #14
0
        public void Dispose()
        {
            try
            {
                if (this.audioSource != null)
                {
                    this.audioSource.Close();
                    this.audioSource = null;
                }
            }
            catch { }

            try
            {
                if (this.AudioDest != null)
                {
                    this.AudioDest.Close();
                    this.AudioDest = null;
                }
            }
            catch { }
        }
コード例 #15
0
        public LossyWAVWriter(IAudioDest audioDest, IAudioDest lwcdfDest, double quality, Codecs.WAV.EncoderSettings settings)
        {
            _audioDest = audioDest;
            _lwcdfDest = lwcdfDest;
            m_settings = settings;

            if (_audioDest != null && _audioDest.Settings.PCM.BitsPerSample > Settings.PCM.BitsPerSample)
            {
                throw new Exception("audio parameters mismatch");
            }
            if (_lwcdfDest != null && _lwcdfDest.Settings.PCM.BitsPerSample != Settings.PCM.BitsPerSample)
            {
                throw new Exception("audio parameters mismatch");
            }

            int quality_integer = (int)Math.Floor(quality);

            fft_analysis_string = new string[4] {
                "0100010", "0110010", "0111010", "0111110"
            };
            bool[]   quality_auto_fft32_on                = { false, false, false, true, true, true, true, true, true, true, true };
            double[] quality_noise_threshold_shifts       = { 20, 16, 9, 6, 3, 0, -2.4, -4.8, -7.2, -9.6, -12 };
            double[] quality_signal_to_noise_ratio        = { -18, -22, -23.5, -23.5, -23.5, -25, -28, -31, -34, -37, -40 };
            double[] quality_dynamic_minimum_bits_to_keep = { 2.5, 2.75, 3.00, 3.25, 3.50, 3.75, 4.0, 4.25, 4.5, 4.75, 5.00 };
            double[] quality_maximum_clips_per_channel    = { 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0 };

            this_analysis_number = 2;
            impulse                      = quality_auto_fft32_on[quality_integer];
            linkchannels                 = false;
            noise_threshold_shift        = Math.Round(interpolate_param(quality_noise_threshold_shifts, quality) * 1000) / 1000;
            snr_value                    = Math.Round(interpolate_param(quality_signal_to_noise_ratio, quality) * 1000) / 1000;
            dynamic_minimum_bits_to_keep = Math.Round(interpolate_param(quality_dynamic_minimum_bits_to_keep, quality) * 1000) / 1000;
            maximum_clips_per_channel    = (int)Math.Round(interpolate_param(quality_maximum_clips_per_channel, quality));
            scaling_factor               = 1.0;
            shaping_factor               = Math.Min(1, quality / 10);
            shaping_is_on                = shaping_factor > 0;

            _audioBuffer = new AudioBuffer(Settings.PCM, 256);
        }
コード例 #16
0
        public void OnEncodingRequest(EncodingRequestMessage message)
        {
            this.outputStream = new MemoryStream();

            AudioPCMConfig pcm = new AudioPCMConfig(message.BitsPerSample, message.ChannelCount, message.SampleRate);

            if (message.OutputFormat == ".mp3")
            {
                this.audioDest = new LameWriter(outputStream, pcm)
                {
                    FinalSampleCount = message.FinalSampleCount,
                    Settings         = LameWriterSettings.CreateVbr(message.CompressionLevel)
                };
            }
            else if (message.OutputFormat == ".flac")
            {
                this.audioDest = new NativeFlacWriter(outputStream, pcm)
                {
                    FinalSampleCount = message.FinalSampleCount,
                    CompressionLevel = message.CompressionLevel
                };
            }
        }
コード例 #17
0
ファイル: CUESheet.cs プロジェクト: androidhacker/DotNetProjs
        public void WriteAudioFilesPass(string dir, CUEStyle style, int[] destLengths, bool htoaToFile, bool noOutput)
        {
            int iTrack, iIndex;
            AudioBuffer sampleBuffer = new AudioBuffer(AudioPCMConfig.RedBook, 0x10000);
            TrackInfo track;
            IAudioSource audioSource = null;
            IAudioDest audioDest = null;
            bool discardOutput;
            int iSource = -1;
            int iDest = -1;
            int samplesRemSource = 0;

            ApplyWriteOffset();

            int destBPS = 16;
            hdcdDecoder = null;
            if (_config.detectHDCD && CUEProcessorPlugins.hdcd != null)
            {
                // currently broken verifyThenConvert on HDCD detection!!!! need to check for HDCD results higher
                try
                {
                    destBPS = ((_outputLossyWAV && _config.decodeHDCDtoLW16) || !_config.decodeHDCDto24bit) ? 20 : 24;
                    hdcdDecoder = Activator.CreateInstance(CUEProcessorPlugins.hdcd, 2, 44100, destBPS, _config.decodeHDCD) as IAudioDest;
                }
                catch { }
                if (hdcdDecoder == null || !_config.decodeHDCD)
                    destBPS = 16;
            }

            if (style == CUEStyle.SingleFile || style == CUEStyle.SingleFileWithCUE)
            {
                iDest++;
                if (_isCD && style == CUEStyle.SingleFileWithCUE)
                    _padding += Encoding.UTF8.GetByteCount(GetCUESheetContents(style));
                audioDest = GetAudioDest(_destPaths[iDest], destLengths[iDest], destBPS, _padding, noOutput);
            }

            int currentOffset = 0, previousOffset = 0;
            int trackLength = (int)_toc.Pregap * 588;
            int diskLength = 588 * (int)_toc.AudioLength;
            int diskOffset = 0;

            // we init AR before CTDB so that CTDB gets inited with correct TOC
            if (isUsingAccurateRip || isUsingCUEToolsDB)
                _arVerify.Init(_toc);
            if (isUsingCUEToolsDB && !isUsingCUEToolsDBFix)
            {
                _CUEToolsDB.TOC = _toc; // This might be unnecessary, because they point to the same structure - if we modify _toc, _CUEToolsDB.TOC gets updated. Unless we set cueSheet.TOC...
                _CUEToolsDB.Init(_arVerify);
            }

            ShowProgress(String.Format("{2} track {0:00} ({1:00}%)...", 0, 0, noOutput ? "Verifying" : "Writing"), 0.0, null, null);

#if !DEBUG
            try
#endif
            {
                for (iTrack = 0; iTrack < TrackCount; iTrack++)
                {
                    track = _tracks[iTrack];

                    if ((style == CUEStyle.GapsPrepended) || (style == CUEStyle.GapsLeftOut))
                    {
                        iDest++;
                        if (hdcdDecoder != null)
                            (hdcdDecoder as IAudioFilter).AudioDest = null;
                        if (audioDest != null)
                            audioDest.Close();
                        audioDest = GetAudioDest(_destPaths[iDest], destLengths[iDest], destBPS, _padding, noOutput);
                    }

                    for (iIndex = 0; iIndex <= _toc[_toc.FirstAudio + iTrack].LastIndex; iIndex++)
                    {
                        int samplesRemIndex = (int)_toc.IndexLength(_toc.FirstAudio + iTrack, iIndex) * 588;

                        if (iIndex == 1)
                        {
                            previousOffset = currentOffset;
                            currentOffset = 0;
                            trackLength = (int)_toc[_toc.FirstAudio + iTrack].Length * 588;
                        }

                        if ((style == CUEStyle.GapsAppended) && (iIndex == 1))
                        {
                            if (hdcdDecoder != null)
                                (hdcdDecoder as IAudioFilter).AudioDest = null;
                            if (audioDest != null)
                                audioDest.Close();
                            iDest++;
                            audioDest = GetAudioDest(_destPaths[iDest], destLengths[iDest], destBPS, _padding, noOutput);
                        }

                        if ((style == CUEStyle.GapsAppended) && (iIndex == 0) && (iTrack == 0))
                        {
                            discardOutput = !htoaToFile;
                            if (htoaToFile)
                            {
                                iDest++;
                                audioDest = GetAudioDest(_destPaths[iDest], destLengths[iDest], destBPS, _padding, noOutput);
                            }
                        }
                        else if ((style == CUEStyle.GapsLeftOut) && (iIndex == 0))
                        {
                            discardOutput = true;
                        }
                        else
                        {
                            discardOutput = false;
                        }

                        while (samplesRemIndex != 0)
                        {
                            if (samplesRemSource == 0)
                            {
                                //                                if (_isCD && audioSource != null && audioSource is CDDriveReader)
                                //                                    updatedTOC = ((CDDriveReader)audioSource).TOC;
                                if (audioSource != null) audioSource.Close();
                                audioSource = GetAudioSource(++iSource, _config.separateDecodingThread || _isCD);
                                samplesRemSource = (int)_sources[iSource].Length;
                            }

                            int copyCount = Math.Min(samplesRemIndex, samplesRemSource);

                            if (trackLength > 0 && !_isCD)
                            {
                                double trackPercent = (double)currentOffset / trackLength;
                                ShowProgress(String.Format("{2} track {0:00} ({1:00}%)...", iIndex > 0 ? iTrack + 1 : iTrack, (int)(100 * trackPercent),
                                    noOutput ? "Verifying" : "Writing"), (int)diskOffset, (int)diskLength,
                                    _isCD ? string.Format("{0}: {1:00} - {2}", audioSource.Path, iTrack + 1, Metadata.Tracks[iTrack].Title) : audioSource.Path, discardOutput ? null : audioDest.Path);
                            }

                            copyCount = audioSource.Read(sampleBuffer, copyCount);
                            if (copyCount == 0)
                                throw new Exception("Unexpected end of file");
                            if (isUsingCUEToolsDB && isUsingCUEToolsDBFix)
                                _CUEToolsDB.SelectedEntry.repair.Write(sampleBuffer);
                            // we use AR after CTDB fix, so that we can verify what we fixed
                            if (isUsingAccurateRip || isUsingCUEToolsDB)
                                _arVerify.Write(sampleBuffer);
                            if (!discardOutput)
                            {
                                if (!_config.detectHDCD || !_config.decodeHDCD)
                                    audioDest.Write(sampleBuffer);
                                if (_config.detectHDCD && hdcdDecoder != null)
                                {
                                    if (_config.wait750FramesForHDCD && diskOffset > 750 * 588 && string.Format("{0:s}", hdcdDecoder) == "")
                                    {
                                        (hdcdDecoder as IAudioFilter).AudioDest = null;
                                        hdcdDecoder = null;
                                        if (_config.decodeHDCD)
                                        {
                                            audioSource.Close();
                                            audioDest.Delete();
                                            throw new Exception("HDCD not detected.");
                                        }
                                    }
                                    else
                                    {
                                        if (_config.decodeHDCD)
                                            (hdcdDecoder as IAudioFilter).AudioDest = (discardOutput || noOutput) ? null : audioDest;
                                        hdcdDecoder.Write(sampleBuffer);
                                    }
                                }
                            }

                            currentOffset += copyCount;
                            diskOffset += copyCount;
                            samplesRemIndex -= copyCount;
                            samplesRemSource -= copyCount;

                            CheckStop();
                        }
                    }
                }
                if (hdcdDecoder != null)
                    (hdcdDecoder as IAudioFilter).AudioDest = null;
                hdcdDecoder = null;
                if (audioSource != null)
                    audioSource.Close();
                audioSource = null;
                if (audioDest != null)
                    audioDest.Close();
                audioDest = null;
            }
#if !DEBUG
            catch (Exception ex)
            {
                if (hdcdDecoder != null)
                    (hdcdDecoder as IAudioFilter).AudioDest = null;
                hdcdDecoder = null;
                if (audioSource != null)
                    try { audioSource.Close(); } catch { }
                audioSource = null;
                if (audioDest != null)
                    try { audioDest.Delete(); } catch { }
                audioDest = null;
                throw ex;
            }
#endif
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: dan-huang/CUETools
        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   order_method = null;
            string   input_file = null;
            string   output_file = null;
            int      skip_a = 0, skip_b = 0;
            int      intarg = -1, vbr_mode = -1, magic = -1;
            bool     do_seektable = true;
            bool     buffered     = false;
            string   coeffs       = null;
            var      settings     = new FlakeWriterSettings()
            {
                AllowNonSubset = true
            };
            bool allowNonSubset     = false;
            bool ignore_chunk_sizes = false;
            bool force = false;

#if FINETUNE
            int finetune_depth = -1;
#endif

            for (int arg = 0; arg < args.Length; arg++)
            {
                bool ok = true;
                try
                {
                    if (args[arg].Length == 0)
                    {
                        ok = false;
                    }
                    else if (args[arg] == "--debug")
                    {
                        debug = true;
                    }
                    else if ((args[arg] == "-f" || args[arg] == "--force"))
                    {
                        force = true;
                    }
                    else if ((args[arg] == "-q" || args[arg] == "--quiet"))
                    {
                        quiet = true;
                    }
                    else if ((args[arg] == "-V" || args[arg] == "--verify"))
                    {
                        settings.DoVerify = true;
                    }
                    else if (args[arg] == "--no-seektable")
                    {
                        do_seektable = false;
                    }
                    else if (args[arg] == "--ignore-chunk-sizes")
                    {
                        ignore_chunk_sizes = true;
                    }
                    else if (args[arg] == "--no-md5")
                    {
                        settings.DoMD5 = false;
                    }
                    else if (args[arg] == "--lax")
                    {
                        allowNonSubset = true;
                    }
                    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] == "--tag") && ++arg < args.Length)
                    {
                        var tags = settings.Tags != null ? new List <string>(settings.Tags) : new List <string>();
                        tags.Add(args[arg]);
                        settings.Tags = tags.ToArray();
                    }
                    else if ((args[arg] == "-t" || args[arg] == "--prediction-type") && ++arg < args.Length)
                    {
                        settings.PredictionType = Flake.LookupPredictionType(args[arg]);
                    }
                    else if ((args[arg] == "-s" || args[arg] == "--stereo") && ++arg < args.Length)
                    {
                        settings.StereoMethod = Flake.LookupStereoMethod(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)
                    {
                        settings.WindowFunctions = Flake.LookupWindowFunction(args[arg]);
                    }
                    else if (args[arg] == "--window-method" && ++arg < args.Length)
                    {
                        settings.WindowMethod = Flake.LookupWindowMethod(args[arg]);
                    }
                    else if ((args[arg] == "-r" || args[arg] == "--partition-order") && ++arg < args.Length)
                    {
                        int min_partition_order, max_partition_order;
                        ok = (args[arg].Split(',').Length == 2 &&
                              int.TryParse(args[arg].Split(',')[0], out min_partition_order) &&
                              (settings.MinPartitionOrder = min_partition_order) != -1 &&
                              int.TryParse(args[arg].Split(',')[1], out max_partition_order) &&
                              (settings.MaxPartitionOrder = max_partition_order) != -1) ||
                             (int.TryParse(args[arg], out max_partition_order) &&
                              (settings.MaxPartitionOrder = max_partition_order) != -1);
                    }
                    else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length)
                    {
                        int min_lpc_order, max_lpc_order;
                        ok = (args[arg].Split(',').Length == 2 &&
                              int.TryParse(args[arg].Split(',')[0], out min_lpc_order) &&
                              (settings.MinLPCOrder = min_lpc_order) != -1 &&
                              int.TryParse(args[arg].Split(',')[1], out max_lpc_order) &&
                              (settings.MaxLPCOrder = max_lpc_order) != -1) ||
                             (int.TryParse(args[arg], out max_lpc_order) &&
                              (settings.MaxLPCOrder = max_lpc_order) != -1);
                    }
                    else if ((args[arg] == "--fixed-order") && ++arg < args.Length)
                    {
                        int min_fixed_order, max_fixed_order;
                        ok = (args[arg].Split(',').Length == 2 &&
                              int.TryParse(args[arg].Split(',')[0], out min_fixed_order) &&
                              (settings.MinFixedOrder = min_fixed_order) != -1 &&
                              int.TryParse(args[arg].Split(',')[1], out max_fixed_order) &&
                              (settings.MaxFixedOrder = max_fixed_order) != -1) ||
                             (int.TryParse(args[arg], out max_fixed_order) &&
                              (settings.MaxFixedOrder = max_fixed_order) != -1);
                    }
                    else if (args[arg] == "--skip" && ++arg < args.Length)
                    {
                        ok = (args[arg].Split(',').Length == 2 &&
                              int.TryParse(args[arg].Split(',')[0], out skip_a) &&
                              int.TryParse(args[arg].Split(',')[1], out skip_b)) ||
                             int.TryParse(args[arg], out skip_a);
                    }
                    else if ((args[arg] == "-e" || args[arg] == "--estimation-depth") && ++arg < args.Length)
                    {
                        settings.EstimationDepth = int.Parse(args[arg]);
                    }
                    else if (args[arg] == "--tukey-parts" && ++arg < args.Length)
                    {
                        settings.TukeyParts = int.Parse(args[arg]);
                    }
                    else if (args[arg] == "--tukey-overlap" && ++arg < args.Length)
                    {
                        settings.TukeyOverlap = double.Parse(args[arg]);
                    }
                    else if (args[arg] == "--tukey-p" && ++arg < args.Length)
                    {
                        settings.TukeyP = double.Parse(args[arg]);
                    }
                    else if ((args[arg] == "-c" || args[arg] == "--max-precision") && ++arg < args.Length)
                    {
                        int min_precision = -1, max_precision = -1;
                        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);
                        settings.MinPrecisionSearch = min_precision;
                        settings.MaxPrecisionSearch = max_precision;
                    }
                    else if (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 && int.TryParse(args[arg], out intarg))
                    {
                        settings.BlockSize = intarg;
                    }
                    else if ((args[arg] == "-P" || args[arg] == "--padding") && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                    {
                        settings.Padding = intarg;
                    }
                    else if (args[arg] == "--magic" && ++arg < args.Length)
                    {
                        ok = int.TryParse(args[arg], out magic);
                    }
#if FINETUNE
                    else if (args[arg] == "--depth" && ++arg < args.Length)
                    {
                        ok = int.TryParse(args[arg], out finetune_depth);
                    }
#endif
                    else if (args[arg] == "--coefs" && ++arg < args.Length)
                    {
                        coeffs = args[arg];
                    }
                    else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out intarg))
                    {
                        ok = intarg >= 0 && intarg <= 11;
                        settings.EncoderModeIndex = intarg;
                    }
                    else if ((args[arg][0] != '-' || args[arg] == "-") && input_file == null)
                    {
                        input_file = args[arg];
                    }
                    else
                    {
                        ok = false;
                    }
                    if (!ok)
                    {
                        Usage();
                        return(1);
                    }
                }
                catch (Exception ex)
                {
                    Usage();
                    Console.WriteLine("");
                    Console.WriteLine("{0}: {1}", args[arg - 1], ex.Message);
                    return(5);
                }
            }
            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-2014 Grigory Chudov.");
                Console.WriteLine("Initially based on Flake encoder by Justin Ruggles.");
                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 FINETUNE
            var prefix = new List <int>();
            if (coeffs != null)
            {
                var ps = coeffs.Split(',');
                for (int i = 0; i < ps.Length; i++)
                {
                    prefix.Add(ps[i].StartsWith("0x") ? int.Parse(ps[i].Substring(2), System.Globalization.NumberStyles.HexNumber) : int.Parse(ps[i]));
                }
            }
            string codefmt = "0x{0:x" + (max_lpc_order / 4 + 1).ToString() + "}";

            int max_prefix = magic >= 0 ? magic : 8;
            do
            {
                FineTuneTask best_task = null;
                var          tasks     = new Dictionary <int, FineTuneTask>();
                if (prefix.Count == 0)
                {
                    tasks.Add((1 << max_lpc_order) - 1, new FineTuneTask((1 << max_lpc_order) - 1, 1));
                    tasks.Add((2 << max_lpc_order) - 1, new FineTuneTask((2 << max_lpc_order) - 1, 2));
                    //tasks.Add((3 << max_lpc_order) - 1, new FineTuneTask((3 << max_lpc_order) - 1, 3));
                    //tasks.Add((4 << max_lpc_order) - 1, new FineTuneTask((4 << max_lpc_order) - 1, 4));
                }
                else
                {
                    foreach (var c in prefix)
                    {
                        tasks.Add(c, new FineTuneTask(c, 1));
                        tasks.Add((1 << max_lpc_order) ^ c, new FineTuneTask((1 << max_lpc_order) ^ c, 2));
                    }
                }
                int total_added_tasks = tasks.Values.Count;

                do
                {
                    foreach (var task in tasks.Values)
                    {
                        if (!task.done)
                        {
                            var prefixc = new List <int>(prefix);
                            prefixc.Add(task.code);
                            for (int i = 1; i < max_lpc_order; i++)
                            {
                                FlakeWriter.SetCoefs(i, new int[0]);
                            }
                            FlakeWriter.SetCoefs(max_lpc_order, prefixc.ToArray());
                            magic = prefixc.Count;
#endif

            IAudioSource audioSource;
            if (input_file == "-")
            {
                audioSource = new WAVReader("", Console.OpenStandardInput(), ignore_chunk_sizes);
            }
            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");
            }
            if (File.Exists(output_file) && !force)
            {
                Usage();
                Console.WriteLine();
                Console.WriteLine("File '{0}' already exists.", output_file);
                return(9);
            }
            settings.PCM            = audioSource.PCM;
            settings.AllowNonSubset = allowNonSubset;
            FlakeWriter flake;

            try
            {
                flake = new FlakeWriter((output_file == "-" || output_file == "nul") ? "" : output_file,
                                        output_file == "-" ? Console.OpenStandardOutput() :
                                        output_file == "nul" ? new NullStream() : null,
                                        settings);
                flake.FinalSampleCount = audioSource.Length < 0 ? -1 : audioSource.Length - skip_a - skip_b;

                if (order_method != null)
                {
                    flake.OrderMethod = Flake.LookupOrderMethod(order_method);
                }
                if (vbr_mode >= 0)
                {
                    flake.VBRMode = vbr_mode;
                }
                if (magic >= 0)
                {
                    flake.DevelopmentMode = magic;
                }
                flake.DoSeekTable = do_seektable;
            }
            catch (Exception ex)
            {
                Usage();
                Console.WriteLine("");
                Console.WriteLine("Error: {0}.", ex.Message);
                return(4);
            }

            IAudioDest audioDest = flake;
            AudioBuffer buff     = new AudioBuffer(audioSource, 0x10000);

            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));
            }

            bool keepRunning = true;
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                keepRunning = false;
                if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                {
                    e.Cancel = true;
                }
                else
                {
                    audioDest.Delete();
                }
            };

            start = DateTime.Now;

#if !DEBUG
            try
#endif
            {
                audioSource.Position = skip_a;
                while (audioSource.Read(buff, skip_b == 0 ? -1 : (int)audioSource.Remaining - skip_b) != 0)
                {
                    audioDest.Write(buff);
                    TimeSpan elapsed = DateTime.Now - start;
                    if (!quiet)
                    {
                        if ((elapsed - lastPrint).TotalMilliseconds > 60)
                        {
                            long length = Math.Max(audioSource.Position, audioSource.Length);
                            Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
                                                100.0 * audioSource.Position / length,
                                                audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
                                                elapsed,//.ToString(@"[-][d’.’]hh’:’mm’:’ss[‘.’ff]"),
                                                TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * length)
                                                );
                            lastPrint = elapsed;
                        }
                    }
                    if (!keepRunning)
                    {
                        throw new Exception("Aborted");
                    }
                }
                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 FINETUNE
            task.size = flake.TotalSize;
            Console.SetOut(stdout);
            Console.Out.WriteLine("{0}\t{1:0.00}\t{2}..{3}\t{4}\t{5}\t{6}/{7}\t{8}\t{9}\t{10}\t{11}",
                                  flake.TotalSize,
                                  flake.UserProcessorTime.TotalSeconds > 0 ? flake.UserProcessorTime.TotalSeconds : totalElapsed.TotalSeconds,
                                  flake.MinLPCOrder,
                                  flake.MaxLPCOrder,
                                  flake.BlockSize,
                                  task.gen,
                                  task.no.ToString().PadLeft(total_added_tasks.ToString().Length, '0'),
                                  total_added_tasks,
                                  task.min_depth,
                                  best_task != null && task.size < best_task.size ? "+" + (best_task.size - task.size).ToString() : task.IsImprovement ? "*" : "",
                                  string.Join(",", prefixc.ConvertAll(x => string.Format(codefmt, x)).ToArray()),
                                  string.Join(",", task.parents.ConvertAll(p => string.Format(codefmt, p.code)).ToArray())
                                  );
#else
            if (debug)
            {
                settings = flake.Settings as FlakeWriterSettings;
                Console.SetOut(stdout);
                Console.Out.WriteLine("{17}\t{0}\t{1:0.000}\t{2}\t{3}\t{4}\t{5}\t{6}..{7}\t{8}..{9}\t{10}..{11}\t{12}..{13}\t{14}\t{15}\t{16}\t{18}",
                                      flake.TotalSize,
                                      flake.UserProcessorTime.TotalSeconds > 0 ? flake.UserProcessorTime.TotalSeconds : totalElapsed.TotalSeconds,
                                      settings.PredictionType.ToString().PadRight(15),
                                      settings.StereoMethod.ToString().PadRight(15),
                                      (flake.OrderMethod.ToString() + "(" + settings.EstimationDepth.ToString() + ")").PadRight(15),
                                      (settings.WindowMethod.ToString().PadRight(10) + "(" +
                                       ((settings.WindowFunctions & WindowFunction.Tukey1X) != 0 ? "X" : (settings.WindowFunctions & WindowFunction.Tukey) != 0 ? "T" : (settings.WindowFunctions & WindowFunction.Tukey1A) != 0 ? "A" : (settings.WindowFunctions & WindowFunction.Tukey1B) != 0 ? "B" : " ") +
                                       ((settings.WindowFunctions & WindowFunction.Tukey2X) != 0 ? "X" : (settings.WindowFunctions & WindowFunction.Tukey2) != 0 ? "2" : (settings.WindowFunctions & WindowFunction.Tukey2A) != 0 ? "A" : (settings.WindowFunctions & WindowFunction.Tukey2B) != 0 ? "B" : " ") +
                                       ((settings.WindowFunctions & WindowFunction.Tukey3X) != 0 ? "X" : (settings.WindowFunctions & WindowFunction.Tukey3) != 0 ? "3" : (settings.WindowFunctions & WindowFunction.Tukey3A) != 0 ? "A" : (settings.WindowFunctions & WindowFunction.Tukey3B) != 0 ? "B" : " ") +
                                       ((settings.WindowFunctions & WindowFunction.Tukey4X) != 0 ? "X" : ((settings.WindowFunctions & WindowFunction.Tukey4) != 0 ? "4" : (settings.WindowFunctions & WindowFunction.Tukey4A) != 0 ? "A" : (settings.WindowFunctions & WindowFunction.Tukey4B) != 0 ? "B" : " ") +
                                        ((settings.WindowFunctions & WindowFunction.Welch) == 0 ? "" : "W") +
                                        ((settings.WindowFunctions & WindowFunction.Hann) == 0 ? "" : "H") +
                                        ((settings.WindowFunctions & WindowFunction.Flattop) == 0 ? "" : "F") +
                                        ((settings.WindowFunctions & WindowFunction.Bartlett) == 0 ? "" : "B")).PadRight(1))
                                      + ((settings.WindowFunctions & (WindowFunction.Tukey1X | WindowFunction.Tukey2X | WindowFunction.Tukey2X | WindowFunction.Tukey3X | WindowFunction.Tukey4X)) != 0 ?
                                         ("," + settings.TukeyOverlap.ToString("F3").PadLeft(6) + "," + settings.TukeyP.ToString("F3")) : "").PadRight(13)
                                      + ")",
                                      settings.MinPartitionOrder,
                                      settings.MaxPartitionOrder,
                                      settings.MinLPCOrder,
                                      settings.MaxLPCOrder,
                                      settings.MinFixedOrder,
                                      settings.MaxFixedOrder,
                                      settings.MinPrecisionSearch,
                                      settings.MaxPrecisionSearch,
                                      flake.Settings.BlockSize,
                                      flake.VBRMode,
                                      coeffs ?? "",
                                      audioSource.Position * audioSource.PCM.BlockAlign,
                                      settings.GuessEncoderMode().ToString().Replace("-1", "?")
                                      );
            }
#endif

#if FINETUNE
            if (best_task == null || task.size < best_task.size)
            {
                best_task = task;
            }
        }

        var promising_tasks = new List <FineTuneTask>();
        promising_tasks.AddRange(tasks.Values);
        promising_tasks.RemoveAll(task => !task.IsImprovement);
        promising_tasks.Sort((task1, task2) => task1.size.CompareTo(task2.size));
        if (finetune_depth >= 0 && promising_tasks.Count > finetune_depth)
        {
            promising_tasks.RemoveRange(finetune_depth, promising_tasks.Count - finetune_depth);
        }
        total_added_tasks = 0;
        foreach (var c in promising_tasks)
        {
            foreach (var c1 in c.GetDerivativeCodes(max_lpc_order))
            {
                if (!tasks.ContainsKey(c1))
                {
                    var new_task = new FineTuneTask(c1, ++total_added_tasks, c);
                    foreach (var c2 in new_task.GetDerivativeCodes(max_lpc_order))
                    {
                        if (tasks.ContainsKey(c2) && tasks[c2].done && !new_task.parents.Contains(tasks[c2]))
                        {
                            new_task.parents.Add(tasks[c2]);
                        }
                    }
                    new_task.min_depth = int.MaxValue;
                    foreach (var p in new_task.parents)
                        if (promising_tasks.IndexOf(p) >= 0)
                        {
                            new_task.min_depth = Math.Min(new_task.min_depth, Math.Max(p.min_depth, promising_tasks.IndexOf(p) + 1));
                        }
}
                    tasks.Add(c1, new_task);
                }
            }
        }
        if (total_added_tasks == 0)
        {
            break;
        }
    } while (true)
    {
        ;
    }

    prefix.Add(best_task.code);
} while (prefix.Count < max_prefix)
コード例 #19
0
        static int Main(string[] args)
        {
            bool             ok = true;
            string           sourceFile = null, destFile = null;
            int              padding            = 8192;
            string           encoderMode        = null;
            string           decoderName        = null;
            string           encoderName        = null;
            string           encoderFormat      = null;
            bool             ignore_chunk_sizes = false;
            AudioEncoderType audioEncoderType   = AudioEncoderType.NoAudio;
            var              decoderOptions     = new Dictionary <string, string>();

            for (int arg = 0; arg < args.Length; arg++)
            {
                if (args[arg].Length == 0)
                {
                    ok = false;
                }
                else if (args[arg] == "--ignore-chunk-sizes")
                {
                    ignore_chunk_sizes = true;
                }
                else if (args[arg] == "--decoder" && ++arg < args.Length)
                {
                    decoderName = args[arg];
                }
                else if (args[arg] == "--decoder-option" && arg + 2 < args.Length)
                {
                    var optionName  = args[++arg];
                    var optionValue = args[++arg];
                    decoderOptions.Add(optionName, optionValue);
                }
                else if (args[arg] == "--encoder" && ++arg < args.Length)
                {
                    encoderName = args[arg];
                }
                else if (args[arg] == "--encoder-format" && ++arg < args.Length)
                {
                    encoderFormat = args[arg];
                }
                else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length)
                {
                    ok = int.TryParse(args[arg], out padding);
                }
                else if ((args[arg] == "-m" || args[arg] == "--mode") && ++arg < args.Length)
                {
                    encoderMode = args[arg];
                }
                else if (args[arg] == "--lossy")
                {
                    audioEncoderType = AudioEncoderType.Lossy;
                }
                else if (args[arg] == "--lossless")
                {
                    audioEncoderType = AudioEncoderType.Lossless;
                }
                else if ((args[arg][0] != '-' || args[arg] == "-") && sourceFile == null)
                {
                    sourceFile = args[arg];
                }
                else if ((args[arg][0] != '-' || args[arg] == "-") && sourceFile != null && destFile == null)
                {
                    destFile = args[arg];
                }
                else
                {
                    ok = false;
                }
                if (!ok)
                {
                    break;
                }
            }

            Console.Error.WriteLine("CUETools.Converter, Copyright (C) 2009-2020 Grigory Chudov.");
            Console.Error.WriteLine("This is free software under the GNU GPLv3+ license; There is NO WARRANTY, to");
            Console.Error.WriteLine("the extent permitted by law. <http://www.gnu.org/licenses/> for details.");
            if (!ok || sourceFile == null || destFile == null)
            {
                Usage();
                return(22);
            }

            if (destFile != "-" && destFile != "nul" && File.Exists(destFile))
            {
                Console.Error.WriteLine("Error: file already exists.");
                return(17);
            }

            DateTime start     = DateTime.Now;
            TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
            var      config    = new CUEConfigAdvanced();

            config.Init();

#if !DEBUG
            try
#endif
            {
                IAudioSource audioSource = null;
                IAudioDest   audioDest   = null;
                TagLib.UserDefined.AdditionalFileTypes.Config = config;
                TagLib.File sourceInfo = sourceFile == "-" ? null : TagLib.File.Create(new TagLib.File.LocalFileAbstraction(sourceFile));

#if !DEBUG
                try
#endif
                {
                    audioSource = Program.GetAudioSource(config, sourceFile, decoderName, ignore_chunk_sizes, decoderOptions);

                    AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);
                    Console.Error.WriteLine("Filename  : {0}", sourceFile);
                    Console.Error.WriteLine("File Info : {0}kHz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample, audioSource.Duration);

                    CUEToolsFormat fmt;
                    if (encoderFormat == null)
                    {
                        if (destFile == "-" || destFile == "nul")
                        {
                            encoderFormat = "wav";
                        }
                        else
                        {
                            string extension = Path.GetExtension(destFile).ToLower();
                            if (!extension.StartsWith("."))
                            {
                                throw new Exception("Unknown encoder format: " + destFile);
                            }
                            encoderFormat = extension.Substring(1);
                        }
                    }
                    if (!config.formats.TryGetValue(encoderFormat, out fmt))
                    {
                        throw new Exception("Unsupported encoder format: " + encoderFormat);
                    }
                    AudioEncoderSettingsViewModel encoder =
                        audioEncoderType == AudioEncoderType.Lossless ? Program.GetEncoder(config, fmt, true, encoderName) :
                        audioEncoderType == AudioEncoderType.Lossy ? Program.GetEncoder(config, fmt, false, encoderName) :
                        Program.GetEncoder(config, fmt, true, encoderName) ?? Program.GetEncoder(config, fmt, false, encoderName);
                    if (encoder == null)
                    {
                        var lst = new List <AudioEncoderSettingsViewModel>(config.encodersViewModel).FindAll(
                            e => e.Extension == fmt.extension && (audioEncoderType == AudioEncoderType.NoAudio || audioEncoderType == (e.Lossless ? AudioEncoderType.Lossless : AudioEncoderType.Lossy))).
                                  ConvertAll(e => e.Name + (e.Lossless ? " (lossless)" : " (lossy)"));
                        throw new Exception("Encoders available for format " + fmt.extension + ": " + (lst.Count == 0 ? "none" : string.Join(", ", lst.ToArray())));
                    }
                    var settings = encoder.Settings.Clone();
                    settings.PCM         = audioSource.PCM;
                    settings.Padding     = padding;
                    settings.EncoderMode = encoderMode ?? settings.EncoderMode;
                    object o = null;
                    try
                    {
                        o = destFile == "-" ? Activator.CreateInstance(settings.EncoderType, settings, "", Console.OpenStandardOutput()) :
                            destFile == "nul" ? Activator.CreateInstance(settings.EncoderType, settings, "", new NullStream()) :
                            Activator.CreateInstance(settings.EncoderType, settings, destFile, null);
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        throw ex.InnerException;
                    }
                    if (o == null || !(o is IAudioDest))
                    {
                        throw new Exception("Unsupported audio type: " + destFile + ": " + settings.EncoderType.FullName);
                    }
                    audioDest = o as IAudioDest;
                    audioDest.FinalSampleCount = audioSource.Length;

                    bool keepRunning = true;
                    Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
                    {
                        keepRunning = false;
                        if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                        {
                            e.Cancel = true;
                        }
                        else
                        {
                            audioDest.Delete();
                        }
                    };

                    while (audioSource.Read(buff, -1) != 0)
                    {
                        audioDest.Write(buff);
                        TimeSpan elapsed = DateTime.Now - start;
                        if ((elapsed - lastPrint).TotalMilliseconds > 60)
                        {
                            var duration = audioSource.Duration;
                            var position = TimeSpan.FromSeconds((double)audioSource.Position / audioSource.PCM.SampleRate);
                            if (duration == TimeSpan.Zero && sourceInfo != null)
                            {
                                duration = sourceInfo.Properties.Duration;
                            }
                            if (duration < position)
                            {
                                duration = position;
                            }
                            if (duration < TimeSpan.FromSeconds(1))
                            {
                                duration = TimeSpan.FromSeconds(1);
                            }
                            Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
                                                100.0 * position.TotalSeconds / duration.TotalSeconds,
                                                position.TotalSeconds / elapsed.TotalSeconds,
                                                elapsed,
                                                TimeSpan.FromSeconds(elapsed.TotalSeconds / position.TotalSeconds * duration.TotalSeconds)
                                                );
                            lastPrint = elapsed;
                        }
                        if (!keepRunning)
                        {
                            throw new Exception("Aborted");
                        }
                    }

                    TimeSpan totalElapsed = DateTime.Now - start;
                    Console.Error.Write("\r                                                                         \r");
                    Console.Error.WriteLine("Results   : {0:0.00}x; {1}",
                                            audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
                                            totalElapsed
                                            );
                }
#if !DEBUG
                catch (Exception ex)
                {
                    if (audioSource != null)
                    {
                        audioSource.Close();
                    }
                    if (audioDest != null)
                    {
                        audioDest.Delete();
                    }
                    throw ex;
                }
#endif
                audioSource.Close();
                audioDest.Close();

                if (sourceFile != "-" && destFile != "-" && destFile != "nul")
                {
                    TagLib.File destInfo = TagLib.File.Create(new TagLib.File.LocalFileAbstraction(destFile));
                    if (Tagging.UpdateTags(destInfo, Tagging.Analyze(sourceInfo), config, false))
                    {
                        sourceInfo.Tag.CopyTo(destInfo.Tag, true);
                        destInfo.Tag.Pictures = sourceInfo.Tag.Pictures;
                        destInfo.Save();
                    }
                }
            }
#if !DEBUG
            catch (Exception ex)
            {
                Console.Error.Write("\r                                                                         \r");
                Console.Error.WriteLine("Error     : {0}", ex.Message);
                return(1);
                //Console.WriteLine("{0}", ex.StackTrace);
            }
#endif
            return(0);
        }
コード例 #20
0
        public void Encode()
        {
            AudioBuffer buffer = new AudioBuffer(audioSource.PCM, BufferSize);

            this.AudioDest.FinalSampleCount = this.audioSource.Length;

            while (audioSource.Read(buffer, BufferSize) > 0)
            {
                if (this.trackGain != null)
                {
                    DspHelper.AnalyzeSamples(this.trackGain, buffer);
                }
                if (this.drMeter != null)
                {
                    this.drMeter.Feed(buffer.Samples, buffer.Length);
                }

                this.AudioDest.Write(buffer);

                ProgressChangedEventArgs eventArgs = new ProgressChangedEventArgs((double)this.audioSource.Position / this.audioSource.Length);
                this.OnProgressChanged(eventArgs);
                if (eventArgs.Cancel)
                {
                    this.AudioDest.Close();
                    this.AudioDest = null;
                    Utility.TryDeleteFile(this.targetFilename);
                    return;
                }
            }

            if (this.drMeter != null)
            {
                this.drMeter.Finish();
            }

            this.AudioDest.Close();
            this.AudioDest = null;

            if (this.tags != null)
            {
                this.tags.WriteToFile(this.targetFilename);
            }
        }
コード例 #21
0
        public LossyWAVWriter(IAudioDest audioDest, IAudioDest lwcdfDest, double quality, AudioPCMConfig pcm)
        {
            _audioDest = audioDest;
            _lwcdfDest = lwcdfDest;
            _pcm = pcm;

            if (_audioDest != null && _audioDest.PCM.BitsPerSample > _pcm.BitsPerSample)
                throw new Exception("audio parameters mismatch");
            if (_lwcdfDest != null && _lwcdfDest.PCM.BitsPerSample != _pcm.BitsPerSample)
                throw new Exception("audio parameters mismatch");

            int quality_integer = (int)Math.Floor(quality);

            fft_analysis_string = new string[4] { "0100010", "0110010", "0111010", "0111110" };
            bool[] quality_auto_fft32_on = { false, false, false, true, true, true, true, true, true, true, true };
            double[] quality_noise_threshold_shifts = { 20, 16, 9, 6, 3, 0, -2.4, -4.8, -7.2, -9.6, -12 };
            double[] quality_signal_to_noise_ratio = { -18, -22, -23.5, -23.5, -23.5, -25, -28, -31, -34, -37, -40 };
            double[] quality_dynamic_minimum_bits_to_keep = { 2.5, 2.75, 3.00, 3.25, 3.50, 3.75, 4.0, 4.25, 4.5, 4.75, 5.00 };
            double[] quality_maximum_clips_per_channel = { 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0 };

            this_analysis_number = 2;
            impulse = quality_auto_fft32_on[quality_integer];
            linkchannels = false;
            noise_threshold_shift = Math.Round(interpolate_param(quality_noise_threshold_shifts, quality) * 1000) / 1000;
            snr_value = Math.Round(interpolate_param(quality_signal_to_noise_ratio, quality) * 1000) / 1000;
            dynamic_minimum_bits_to_keep = Math.Round(interpolate_param(quality_dynamic_minimum_bits_to_keep, quality) * 1000) / 1000;
            maximum_clips_per_channel = (int)Math.Round(interpolate_param(quality_maximum_clips_per_channel, quality));
            scaling_factor = 1.0;
            shaping_factor = Math.Min(1, quality / 10);
            shaping_is_on = shaping_factor > 0;

            _audioBuffer = new AudioBuffer(_pcm, 256);
        }
コード例 #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   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,
                     estimation_depth = -1,
                     min_modifier = -1, max_modifier = -1;
            int  intarg = -1;
            int  initial_history = -1, history_mult = -1;
            int  adaptive_passes = -1;
            bool do_seektable    = true;
            bool buffered        = false;
            var  settings        = new Codecs.ALAC.EncoderSettings();

            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")
                {
                    settings.DoVerify = 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 intarg);
                    settings.BlockSize = intarg;
                }
                else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length)
                {
                    ok = int.TryParse(args[arg], out intarg);
                    settings.Padding = intarg;
                }
                else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out intarg))
                {
                    ok = intarg >= 0 && intarg <= 11;
                    settings.SetEncoderModeIndex(intarg);
                }
                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-2021 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 Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings()
                {
                    IgnoreChunkSizes = true
                }, "", Console.OpenStandardInput());
            }
            else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".wav")
            {
                audioSource = new Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings(), input_file);
            }
            else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".m4a")
            {
                audioSource = new Codecs.ALAC.AudioDecoder(new Codecs.ALAC.DecoderSettings(), input_file);
            }
            else
            {
                Usage();
                return(2);
            }
            if (buffered)
            {
                audioSource = new AudioPipe(audioSource, 0x10000);
            }
            if (output_file == null)
            {
                output_file = Path.ChangeExtension(input_file, "m4a");
            }
            settings.PCM = audioSource.PCM;
            Codecs.ALAC.AudioEncoder alac = new Codecs.ALAC.AudioEncoder(settings,
                                                                         (output_file == "-" || output_file == "nul") ? "" : output_file,
                                                                         output_file == "-" ? Console.OpenStandardOutput() :
                                                                         output_file == "nul" ? new NullStream() : null);
            alac.FinalSampleCount = audioSource.Length;
            IAudioDest  audioDest = alac;
            AudioBuffer buff      = new AudioBuffer(audioSource, 0x10000);

            try
            {
                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 (estimation_depth >= 0)
                {
                    alac.EstimationDepth = estimation_depth;
                }
                if (adaptive_passes >= 0)
                {
                    alac.AdaptivePasses = adaptive_passes;
                }
                alac.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

            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.Settings.BlockSize
                                      );
            }
            //File.SetAttributes(output_file, FileAttributes.ReadOnly);
            return(0);
        }
コード例 #23
0
ファイル: Main.cs プロジェクト: darealshinji/Moitah.net
        public void WriteAudioFiles(string dir, CUEStyle style, SetStatus statusDel)
        {
            const int buffLen = 16384;
            int       iTrack, iIndex, iSource, iDest, i, j, samplesRemIndex, samplesRemSource, copyCount;

            string[]     destPaths;
            int[]        destLengths;
            byte[]       buff = new byte[buffLen * 2 * 2];
            TrackInfo    track;
            IAudioSource audioSource = null;
            IAudioDest   audioDest   = null;
            bool         htoaToFile  = ((style == CUEStyle.GapsAppended) && _preserveHTOA &&
                                        (_tracks[0].IndexLengths[0] != 0));
            bool discardOutput;

            if (_usePregapForFirstTrackInSingleFile)
            {
                throw new Exception("UsePregapForFirstTrackInSingleFile is not supported for writing audio files.");
            }

            if (style == CUEStyle.SingleFile)
            {
                destPaths    = new string[1];
                destPaths[0] = Path.Combine(dir, _singleFilename);
            }
            else
            {
                destPaths = new string[TrackCount + (htoaToFile ? 1 : 0)];
                if (htoaToFile)
                {
                    destPaths[0] = Path.Combine(dir, _htoaFilename);
                }
                for (i = 0; i < TrackCount; i++)
                {
                    destPaths[i + (htoaToFile ? 1 : 0)] = Path.Combine(dir, _trackFilenames[i]);
                }
            }
            for (i = 0; i < destPaths.Length; i++)
            {
                for (j = 0; j < _sourcePaths.Count; j++)
                {
                    if (destPaths[i].ToLower() == _sourcePaths[j].ToLower())
                    {
                        throw new Exception("Source and destination audio file paths cannot be the same.");
                    }
                }
            }

            if (_writeOffset != 0)
            {
                int        absOffset = Math.Abs(_writeOffset);
                SourceInfo sourceInfo;

                sourceInfo.Path   = null;
                sourceInfo.Offset = 0;
                sourceInfo.Length = absOffset;

                if (_writeOffset < 0)
                {
                    _sources.Insert(0, sourceInfo);

                    int last = _sources.Count - 1;
                    while (absOffset >= _sources[last].Length)
                    {
                        absOffset -= _sources[last].Length;
                        _sources.RemoveAt(last--);
                    }
                    sourceInfo         = _sources[last];
                    sourceInfo.Length -= absOffset;
                    _sources[last]     = sourceInfo;
                }
                else
                {
                    _sources.Add(sourceInfo);

                    while (absOffset >= _sources[0].Length)
                    {
                        absOffset -= _sources[0].Length;
                        _sources.RemoveAt(0);
                    }
                    sourceInfo         = _sources[0];
                    sourceInfo.Offset += absOffset;
                    sourceInfo.Length -= absOffset;
                    _sources[0]        = sourceInfo;
                }

                _appliedWriteOffset = true;
            }

            destLengths = CalculateAudioFileLengths(style);

            iSource          = -1;
            iDest            = -1;
            samplesRemSource = 0;

            if (style == CUEStyle.SingleFile)
            {
                iDest++;
                audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest]);
            }

            for (iTrack = 0; iTrack < TrackCount; iTrack++)
            {
                statusDel(String.Format("Writing track {0:00}...", iTrack + 1));

                track = _tracks[iTrack];

                if ((style == CUEStyle.GapsPrepended) || (style == CUEStyle.GapsLeftOut))
                {
                    if (audioDest != null)
                    {
                        audioDest.Close();
                    }
                    iDest++;
                    audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest]);
                }

                for (iIndex = 0; iIndex <= track.LastIndex; iIndex++)
                {
                    if ((style == CUEStyle.GapsAppended) && (iIndex == 1))
                    {
                        if (audioDest != null)
                        {
                            audioDest.Close();
                        }
                        iDest++;
                        audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest]);
                    }

                    samplesRemIndex = track.IndexLengths[iIndex] * 588;

                    if ((style == CUEStyle.GapsAppended) && (iIndex == 0) && (iTrack == 0))
                    {
                        discardOutput = !htoaToFile;
                        if (htoaToFile)
                        {
                            iDest++;
                            audioDest = GetAudioDest(destPaths[iDest], destLengths[iDest]);
                        }
                    }
                    else if ((style == CUEStyle.GapsLeftOut) && (iIndex == 0))
                    {
                        discardOutput = true;
                    }
                    else
                    {
                        discardOutput = false;
                    }

                    while (samplesRemIndex != 0)
                    {
                        if (samplesRemSource == 0)
                        {
                            if (audioSource != null)
                            {
                                audioSource.Close();
                            }
                            audioSource      = GetAudioSource(++iSource);
                            samplesRemSource = _sources[iSource].Length;
                        }

                        copyCount = Math.Min(Math.Min(samplesRemIndex, samplesRemSource), buffLen);

                        audioSource.Read(buff, copyCount);
                        if (!discardOutput)
                        {
                            audioDest.Write(buff, copyCount);
                        }

                        samplesRemIndex  -= copyCount;
                        samplesRemSource -= copyCount;

                        lock (this) {
                            if (_stop)
                            {
                                audioSource.Close();
                                try { audioDest.Close(); } catch {}
                                throw new StopException();
                            }
                        }
                    }
                }
            }

            if (audioSource != null)
            {
                audioSource.Close();
            }
            audioDest.Close();
        }
コード例 #24
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);
        }
コード例 #25
0
 internal Sapi4Engine(ModeInfo modeInfo, IntPtr pIUnknownForAudio)
 {
     this.modeInfo = modeInfo;
     Marshal.AddRef(pIUnknownForAudio);
     audioObject = Marshal.GetObjectForIUnknown(pIUnknownForAudio) as IAudioDest;
 }
コード例 #26
0
        static int Main(string[] args)
        {
            bool             ok = true;
            string           sourceFile = null, destFile = null;
            int              padding          = 8192;
            int              stream           = 0;
            string           encoderMode      = null;
            string           encoderName      = null;
            string           encoderFormat    = null;
            AudioEncoderType audioEncoderType = AudioEncoderType.NoAudio;
            var              decoderOptions   = new Dictionary <string, string>();
            bool             queryMeta        = false;

            for (int arg = 0; arg < args.Length; arg++)
            {
                if (args[arg].Length == 0)
                {
                    ok = false;
                }
                else if (args[arg] == "--encoder" && ++arg < args.Length)
                {
                    encoderName = args[arg];
                }
                else if (args[arg] == "--encoder-format" && ++arg < args.Length)
                {
                    encoderFormat = args[arg];
                }
                else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length)
                {
                    ok = int.TryParse(args[arg], out padding);
                }
                else if ((args[arg] == "-m" || args[arg] == "--mode") && arg + 1 < args.Length)
                {
                    encoderMode = args[++arg];
                }
                else if (args[arg] == "--lossy")
                {
                    audioEncoderType = AudioEncoderType.Lossy;
                }
                else if (args[arg] == "--lossless")
                {
                    audioEncoderType = AudioEncoderType.Lossless;
                }
                else if (args[arg] == "--ctdb")
                {
                    queryMeta = true;
                }
                else if (args[arg] == "--decoder-option" && arg + 2 < args.Length)
                {
                    var optionName  = args[++arg];
                    var optionValue = args[++arg];
                    decoderOptions.Add(optionName, optionValue);
                }
                else if ((args[arg][0] != '-' || args[arg] == "-") && sourceFile == null)
                {
                    sourceFile = args[arg];
                }
                else if ((args[arg][0] != '-' || args[arg] == "-") && sourceFile != null && destFile == null)
                {
                    destFile = args[arg];
                    var x = destFile.Split(':');
                    if (x.Length > 1)
                    {
                        stream = int.Parse(x[0]);
                        if (x[1] != "")
                        {
                            destFile = x[1];
                        }
                        else
                        {
                            arg++;
                            if (arg >= args.Length)
                            {
                                ok = false;
                                break;
                            }
                            destFile = args[arg];
                        }
                    }
                }
                else
                {
                    ok = false;
                }
                if (!ok)
                {
                    break;
                }
            }

            if (!ok || sourceFile == null)
            {
                Usage();
                return(22);
            }

            if (destFile != null && destFile != "-" && destFile != "nul" && File.Exists(destFile))
            {
                Console.Error.WriteLine("Error: file {0} already exists.", destFile);
                return(17);
            }

            DateTime start     = DateTime.Now;
            TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
            var      config    = new CUEConfigAdvanced();

            config.Init();

#if !DEBUG
            try
#endif
            {
                IAudioSource       audioSource    = null;
                IAudioTitleSet     audioContainer = null;
                IAudioDest         audioDest      = null;
                var                videos         = new List <Codecs.MPEG.MPLS.MPLSStream>();
                List <IAudioTitle> audios         = null;
                List <TimeSpan>    chapters       = null;
                TagLib.UserDefined.AdditionalFileTypes.Config = config;

#if !DEBUG
                try
#endif
                {
                    if (true)
                    {
                        IAudioDecoderSettings decoderSettings = null;
                        if (Path.GetExtension(sourceFile) == ".mpls")
                        {
                            decoderSettings = new Codecs.MPEG.MPLS.DecoderSettings();
                        }
                        else
                        {
                            decoderSettings = new Codecs.MPEG.ATSI.DecoderSettings();
                        }
                        foreach (var decOpt in decoderOptions)
                        {
                            var property = TypeDescriptor.GetProperties(decoderSettings).Find(decOpt.Key, true);
                            if (property == null)
                            {
                                throw new Exception($"{decoderSettings.Name} {decoderSettings.Extension} decoder settings object (of type {decoderSettings.GetType().FullName}) doesn't have a property named {decOpt.Key}.");
                            }
                            property.SetValue(decoderSettings,
                                              TypeDescriptor.GetConverter(property.PropertyType).ConvertFromString(decOpt.Value));
                        }
                        audioSource    = decoderSettings.Open(sourceFile);
                        audioContainer = audioSource as IAudioTitleSet;
                        if (audioContainer == null)
                        {
                            audioContainer = new SingleAudioTitleSet(audioSource);
                        }
                        Console.ForegroundColor = ConsoleColor.White;
                        int  frameRate  = 0;
                        bool interlaced = false;
                        audios = audioContainer.AudioTitles;
                        audios.ForEach(t => chapters = t.Chapters);
                        if (audioSource is Codecs.MPEG.MPLS.AudioDecoder)
                        {
                            var mpls = audioSource as Codecs.MPEG.MPLS.AudioDecoder;
                            mpls.MPLSHeader.play_item.ForEach(i => i.video.ForEach(v => { if (!videos.Exists(v1 => v1.pid == v.pid))
                                                                                          {
                                                                                              videos.Add(v);
                                                                                          }
                                                                                   }));
                        }
                        videos.ForEach(v => { frameRate = v.FrameRate; interlaced = v.Interlaced; });
                        Console.Error.Write($@"M2TS, {
                            videos.Count} video track{(videos.Count != 1 ? "s" : "")}, {
                            audios.Count} audio track{(audios.Count != 1 ? "s" : "")}, {
                            CDImageLayout.TimeToString(audios[0].GetDuration(), "{0:0}:{1:00}:{2:00}")}, {
                            (frameRate * (interlaced ? 2 : 1))}{
                            (interlaced ? "i" : "p")}");
                        Console.Error.WriteLine();
                        //foreach (var item in mpls.MPLSHeader.play_item)
                        //Console.Error.WriteLine("{0}.m2ts", item.clip_id);
                        {
                            Console.ForegroundColor = ConsoleColor.Gray;
                            int id = 1;
                            if (chapters.Count > 1)
                            {
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.Error.Write(id++);
                                Console.Error.Write(": ");
                                Console.ForegroundColor = ConsoleColor.Gray;
                                Console.Error.WriteLine("Chapters, {0} chapters", chapters.Count - 1);
                            }
                            foreach (var video in videos)
                            {
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.Error.Write(id++);
                                Console.Error.Write(": ");
                                Console.ForegroundColor = ConsoleColor.Gray;
                                Console.Error.WriteLine("{0}, {1}{2}", video.CodecString, video.FormatString, video.FrameRate * (video.Interlaced ? 2 : 1));
                            }
                            foreach (var audio in audios)
                            {
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.Error.Write(id++);
                                Console.Error.Write(": ");
                                Console.ForegroundColor = ConsoleColor.Gray;
                                Console.Error.WriteLine("{0}, {1}, {2}, {3}", audio.Codec, audio.Language, audio.GetFormatString(), audio.GetRateString());
                            }
                        }
                    }

                    if (destFile == null)
                    {
                        return(0);
                    }

                    string strtoc = "";
                    for (int i = 0; i < chapters.Count; i++)
                    {
                        strtoc += string.Format(" {0}", (int)Math.Round((chapters[i].TotalSeconds * 75)));
                    }
                    strtoc = strtoc.Substring(1);
                    CDImageLayout    toc  = new CDImageLayout(strtoc);
                    CTDBResponseMeta meta = null;
                    if (queryMeta)
                    {
                        var ctdb = new CUEToolsDB(toc, null);
                        Console.Error.WriteLine("Contacting CTDB...");
                        ctdb.ContactDB(null, "CUETools.eac3to 2.1.8", "", false, true, CTDBMetadataSearch.Extensive);
                        foreach (var imeta in ctdb.Metadata)
                        {
                            meta = imeta;
                            break;
                        }
                    }

                    if (stream > 0)
                    {
                        int chapterStreams = chapters.Count > 1 ? 1 : 0;
                        if (stream <= chapterStreams)
                        {
                            if (destFile == "-" || destFile == "nul")
                            {
                                encoderFormat = "txt";
                            }
                            else
                            {
                                string extension = Path.GetExtension(destFile).ToLower();
                                if (!extension.StartsWith("."))
                                {
                                    encoderFormat = destFile;
                                    if (meta == null || meta.artist == null || meta.album == null)
                                    {
                                        destFile = string.Format("{0}.{1}", Path.GetFileNameWithoutExtension(sourceFile), destFile);
                                    }
                                    else
                                    {
                                        destFile = string.Format("{0} - {1} - {2}.{3}", meta.artist, meta.year, meta.album, destFile);
                                    }
                                }
                                else
                                {
                                    encoderFormat = extension.Substring(1);
                                }
                                if (encoderFormat != "txt" && encoderFormat != "cue")
                                {
                                    throw new Exception(string.Format("Unsupported chapters file format \"{0}\"", encoderFormat));
                                }
                            }

                            Console.Error.WriteLine("Creating file \"{0}\"...", destFile);

                            if (encoderFormat == "txt")
                            {
                                using (TextWriter sw = destFile == "nul" ? (TextWriter) new StringWriter() : destFile == "-" ? Console.Out : (TextWriter) new StreamWriter(destFile))
                                {
                                    for (int i = 0; i < chapters.Count - 1; i++)
                                    {
                                        sw.WriteLine("CHAPTER{0:00}={1}", i + 1,
                                                     CDImageLayout.TimeToString(chapters[i]));
                                        if (meta != null && meta.track.Length >= toc[i + 1].Number)
                                        {
                                            sw.WriteLine("CHAPTER{0:00}NAME={1}", i + 1, meta.track[(int)toc[i + 1].Number - 1].name);
                                        }
                                        else
                                        {
                                            sw.WriteLine("CHAPTER{0:00}NAME=", i + 1);
                                        }
                                    }
                                }
                                Console.BackgroundColor = ConsoleColor.DarkGreen;
                                Console.Error.Write("Done.");
                                Console.BackgroundColor = ConsoleColor.Black;
                                Console.Error.WriteLine();
                                return(0);
                            }

                            if (encoderFormat == "cue")
                            {
                                using (StreamWriter cueWriter = new StreamWriter(destFile, false, Encoding.UTF8))
                                {
                                    cueWriter.WriteLine("REM COMMENT \"{0}\"", "Created by CUETools.eac3to");
                                    if (meta != null && meta.year != null)
                                    {
                                        cueWriter.WriteLine("REM DATE {0}", meta.year);
                                    }
                                    else
                                    {
                                        cueWriter.WriteLine("REM DATE XXXX");
                                    }
                                    if (meta != null)
                                    {
                                        cueWriter.WriteLine("PERFORMER \"{0}\"", meta.artist);
                                        cueWriter.WriteLine("TITLE \"{0}\"", meta.album);
                                    }
                                    else
                                    {
                                        cueWriter.WriteLine("PERFORMER \"\"");
                                        cueWriter.WriteLine("TITLE \"\"");
                                    }
                                    if (meta != null)
                                    {
                                        //cueWriter.WriteLine("FILE \"{0}\" WAVE", Path.GetFileNameWithoutExtension(destFile) + (extension ?? ".wav"));
                                        cueWriter.WriteLine("FILE \"{0}\" WAVE", Path.GetFileNameWithoutExtension(destFile) + (".wav"));
                                    }
                                    else
                                    {
                                        cueWriter.WriteLine("FILE \"{0}\" WAVE", "");
                                    }
                                    for (int track = 1; track <= toc.TrackCount; track++)
                                    {
                                        if (toc[track].IsAudio)
                                        {
                                            cueWriter.WriteLine("  TRACK {0:00} AUDIO", toc[track].Number);
                                            if (meta != null && meta.track.Length >= toc[track].Number)
                                            {
                                                cueWriter.WriteLine("    TITLE \"{0}\"", meta.track[(int)toc[track].Number - 1].name);
                                                if (meta.track[(int)toc[track].Number - 1].artist != null)
                                                {
                                                    cueWriter.WriteLine("    PERFORMER \"{0}\"", meta.track[(int)toc[track].Number - 1].artist);
                                                }
                                            }
                                            else
                                            {
                                                cueWriter.WriteLine("    TITLE \"\"");
                                            }
                                            if (toc[track].ISRC != null)
                                            {
                                                cueWriter.WriteLine("    ISRC {0}", toc[track].ISRC);
                                            }
                                            for (int index = toc[track].Pregap > 0 ? 0 : 1; index <= toc[track].LastIndex; index++)
                                            {
                                                cueWriter.WriteLine("    INDEX {0:00} {1}", index, toc[track][index].MSF);
                                            }
                                        }
                                    }
                                }
                                Console.BackgroundColor = ConsoleColor.DarkGreen;
                                Console.Error.Write("Done.");
                                Console.BackgroundColor = ConsoleColor.Black;
                                Console.Error.WriteLine();
                                return(0);
                            }

                            throw new Exception("Unknown encoder format: " + destFile);
                        }
                        if (stream - chapterStreams <= videos.Count)
                        {
                            throw new Exception("Video extraction not supported.");
                        }
                        if (stream - chapterStreams - videos.Count > audios.Count)
                        {
                            throw new Exception(string.Format("The source file doesn't contain a track with the number {0}.", stream));
                        }
                        int streamId = audios[stream - chapterStreams - videos.Count - 1].StreamId;
                        if (audioSource is Codecs.MPEG.MPLS.AudioDecoder)
                        {
                            (audioSource.Settings as Codecs.MPEG.MPLS.DecoderSettings).StreamId = streamId;
                        }
                    }

                    AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);
                    Console.Error.WriteLine("Filename  : {0}", sourceFile);
                    Console.Error.WriteLine("File Info : {0}kHz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample,
                                            audioSource.Duration);

                    CUEToolsFormat fmt;
                    if (encoderFormat == null)
                    {
                        if (destFile == "-" || destFile == "nul")
                        {
                            encoderFormat = "wav";
                        }
                        else
                        {
                            string extension = Path.GetExtension(destFile).ToLower();
                            if (!extension.StartsWith("."))
                            {
                                encoderFormat = destFile;
                                if (meta == null || meta.artist == null || meta.album == null)
                                {
                                    destFile = string.Format("{0} - {1}.{2}", Path.GetFileNameWithoutExtension(sourceFile), stream, destFile);
                                }
                                else
                                {
                                    destFile = string.Format("{0} - {1} - {2}.{3}", meta.artist, meta.year, meta.album, destFile);
                                }
                            }
                            else
                            {
                                encoderFormat = extension.Substring(1);
                            }
                            if (File.Exists(destFile))
                            {
                                throw new Exception(string.Format("Error: file {0} already exists.", destFile));
                            }
                        }
                    }
                    if (!config.formats.TryGetValue(encoderFormat, out fmt))
                    {
                        throw new Exception("Unsupported encoder format: " + encoderFormat);
                    }
                    AudioEncoderSettingsViewModel encoder =
                        audioEncoderType == AudioEncoderType.Lossless ? Program.GetEncoder(config, fmt, true, encoderName) :
                        audioEncoderType == AudioEncoderType.Lossy ? Program.GetEncoder(config, fmt, false, encoderName) :
                        Program.GetEncoder(config, fmt, true, encoderName) ?? Program.GetEncoder(config, fmt, false, encoderName);
                    if (encoder == null)
                    {
                        var lst = new List <AudioEncoderSettingsViewModel>(config.encodersViewModel).FindAll(
                            e => e.Extension == fmt.extension && (audioEncoderType == AudioEncoderType.NoAudio || audioEncoderType == (e.Lossless ? AudioEncoderType.Lossless : AudioEncoderType.Lossy))).
                                  ConvertAll(e => e.Name + (e.Lossless ? " (lossless)" : " (lossy)"));
                        throw new Exception("Encoders available for format " + fmt.extension + ": " + (lst.Count == 0 ? "none" : string.Join(", ", lst.ToArray())));
                    }
                    Console.Error.WriteLine("Output {0}  : {1}", stream, destFile);
                    var settings = encoder.Settings.Clone();
                    settings.PCM         = audioSource.PCM;
                    settings.Padding     = padding;
                    settings.EncoderMode = encoderMode ?? settings.EncoderMode;
                    object o = null;
                    try
                    {
                        o = destFile == "-" ? Activator.CreateInstance(settings.EncoderType, settings, "", Console.OpenStandardOutput()) :
                            destFile == "nul" ? Activator.CreateInstance(settings.EncoderType, settings, "", new NullStream()) :
                            Activator.CreateInstance(settings.EncoderType, settings, destFile, null);
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        throw ex.InnerException;
                    }
                    if (o == null || !(o is IAudioDest))
                    {
                        throw new Exception("Unsupported audio type: " + destFile + ": " + settings.EncoderType.FullName);
                    }
                    audioDest = o as IAudioDest;
                    audioDest.FinalSampleCount = audioSource.Length;

                    bool keepRunning = true;
                    Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
                    {
                        keepRunning = false;
                        if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                        {
                            e.Cancel = true;
                        }
                        else
                        {
                            audioDest.Delete();
                        }
                    };

                    while (audioSource.Read(buff, -1) != 0)
                    {
                        audioDest.Write(buff);
                        TimeSpan elapsed = DateTime.Now - start;
                        if ((elapsed - lastPrint).TotalMilliseconds > 60)
                        {
                            var duration = audioSource.Duration;
                            var position = TimeSpan.FromSeconds((double)audioSource.Position / audioSource.PCM.SampleRate);
                            if (duration < position)
                            {
                                duration = position;
                            }
                            if (duration < TimeSpan.FromSeconds(1))
                            {
                                duration = TimeSpan.FromSeconds(1);
                            }
                            Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
                                                100.0 * position.TotalSeconds / duration.TotalSeconds,
                                                position.TotalSeconds / elapsed.TotalSeconds,
                                                elapsed,
                                                TimeSpan.FromSeconds(elapsed.TotalSeconds / position.TotalSeconds * duration.TotalSeconds)
                                                );
                            lastPrint = elapsed;
                        }
                        if (!keepRunning)
                        {
                            throw new Exception("Aborted");
                        }
                    }

                    TimeSpan totalElapsed = DateTime.Now - start;
                    Console.Error.Write("\r                                                                         \r");
                    Console.Error.WriteLine("Results   : {0:0.00}x; {1}",
                                            audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
                                            totalElapsed
                                            );
                }
#if !DEBUG
                catch (Exception ex)
                {
                    if (audioSource != null)
                    {
                        audioSource.Close();
                    }
                    if (audioDest != null)
                    {
                        audioDest.Delete();
                    }
                    throw ex;
                }
#endif
                audioSource.Close();
                audioDest.Close();

                if (sourceFile != "-" && destFile != "-" && destFile != "nul")
                {
                    //TagLib.File destInfo = TagLib.File.Create(new TagLib.File.LocalFileAbstraction(destFile));
                    //NameValueCollection tags;
                    //if (Tagging.UpdateTags(destInfo, tags, config, false))
                    //{
                    //    destInfo.Save();
                    //}
                }
            }
#if !DEBUG
            catch (Exception ex)
            {
                Console.Error.Write("\r                                                                         \r");
                Console.BackgroundColor = ConsoleColor.DarkRed;
                Console.Error.Write("Error     : {0}", ex.Message);
                Console.BackgroundColor = ConsoleColor.Black;
                Console.Error.WriteLine();
                return(1);
                //Console.WriteLine("{0}", ex.StackTrace);
            }
#endif
            return(0);
        }
コード例 #27
0
 public void Prepare(IAudioDest dest)
 {
     if (dest.PCM.ChannelCount != pcm.ChannelCount || dest.PCM.BitsPerSample != pcm.BitsPerSample)
         throw new Exception("AudioBuffer format mismatch");
 }
コード例 #28
0
ファイル: CUESheet.cs プロジェクト: androidhacker/DotNetProjs
        public void VerifyAudio()
        {
            ApplyWriteOffset();

            hdcdDecoder = null;

            // we init AR before CTDB so that CTDB gets inited with correct TOC
            if (isUsingAccurateRip || isUsingCUEToolsDB)
                _arVerify.Init(_toc);
            if (isUsingCUEToolsDB && !isUsingCUEToolsDBFix)
            {
                _CUEToolsDB.TOC = _toc;
                _CUEToolsDB.Init(_arVerify);
            }

            ShowProgress(String.Format("Verifying ({0:00}%)...", 0), 0.0, null, null);

            AudioBuffer sampleBuffer = new AudioBuffer(AudioPCMConfig.RedBook, 0x10000);

            List<CUEToolsVerifyTask> tasks = new List<CUEToolsVerifyTask>();
            // also make sure all sources are seekable!!!
            // use overlapped io with large buffers?
            // ar.verify in each thread?
            int nThreads = 1;// _isCD || !_config.separateDecodingThread || isUsingCUEToolsDB || _config.detectHDCD ? 1 : Environment.ProcessorCount;

            int diskLength = 588 * (int)_toc.AudioLength;
            tasks.Add(new CUEToolsVerifyTask(this, 0, diskLength / nThreads, _arVerify));
            for (int iThread = 1; iThread < nThreads; iThread++)
                tasks.Add(new CUEToolsVerifyTask(this, iThread * diskLength / nThreads, (iThread + 1) * diskLength / nThreads));

#if !DEBUG
            try
#endif
            {
                int lastProgress = -588 * 75;
                int diskOffset = 0;
                int sourcesActive;
                do
                {
                    sourcesActive = 0;
                    for (int iSource = 0; iSource < tasks.Count; iSource++)
                    {
                        CUEToolsVerifyTask task = tasks[iSource];
                        if (task.Remaining == 0)
                            continue;
                        sourcesActive++;
                        if (tasks.Count == 1 && task.source.Position - lastProgress >= 588 * 75)
                        {
                            lastProgress = (int)task.source.Position;
                            int pos = 0;
                            int trackStart = 0;
                            int trackLength = (int)_toc.Pregap * 588;
                            for (int iTrack = 0; iTrack < TrackCount; iTrack++)
                                for (int iIndex = 0; iIndex <= _toc[_toc.FirstAudio + iTrack].LastIndex; iIndex++)
                                {
                                    int indexLen = (int)_toc.IndexLength(_toc.FirstAudio + iTrack, iIndex) * 588;
                                    if (iIndex == 1)
                                    {
                                        trackStart = pos;
                                        trackLength = (int)_toc[_toc.FirstAudio + iTrack].Length * 588;
                                    }
                                    if (task.source.Position < pos + indexLen)
                                    {
                                        if (trackLength > 0 && !_isCD)
                                        {
                                            double trackPercent = (double)(task.source.Position - trackStart) / trackLength;
                                            ShowProgress(String.Format("{2} track {0:00} ({1:00}%)...", iIndex > 0 ? iTrack + 1 : iTrack, (int)(100 * trackPercent),
                                                "Verifying"), diskOffset, diskLength, task.source.Path, null);
                                        }
                                        iTrack = TrackCount;
                                        break;
                                    }
                                    pos += indexLen;
                                }
                        }
                        else if (tasks.Count > 1)
                        {
                            ShowProgress(String.Format("Verifying ({0:00}%)...", (uint)(100.0 * diskOffset / diskLength)),
                                diskOffset, diskLength, InputPath, null);
                        }

                        int copyCount = task.Step(sampleBuffer);
                        if (copyCount == 0)
                            throw new Exception("Unexpected end of file");
                        diskOffset += copyCount;

                        CheckStop();
                    }
                } while (sourcesActive > 0);
            }
#if !DEBUG
            catch (Exception ex)
            {
                tasks.ForEach(t => t.TryClose());
                tasks.Clear();
                throw ex;
            }
#endif
            hdcdDecoder = tasks[0].hdcd;
            for (int iThread = 1; iThread < nThreads; iThread++)
                tasks[0].Combine(tasks[iThread]);
            tasks.ForEach(t => t.Close());
            tasks.Clear();
        }
コード例 #29
0
ファイル: CUESheet.cs プロジェクト: androidhacker/DotNetProjs
 public CUESheet(CUEConfig config)
 {
     _config = config;
     _progress = new CUEToolsProgressEventArgs();
     _progress.cueSheet = this;
     _attributes = new List<CUELine>();
     _tracks = new List<TrackInfo>();
     _trackFilenames = new List<string>();
     _toc = new CDImageLayout();
     _sources = new List<SourceInfo>();
     _sourcePaths = new List<string>();
     _stop = false;
     _pause = false;
     _outputPath = null;
     _paddedToFrame = false;
     _truncated4608 = false;
     _usePregapForFirstTrackInSingleFile = false;
     _action = CUEAction.Encode;
     _appliedWriteOffset = false;
     _minDataTrackLength = null;
     hdcdDecoder = null;
     _hasEmbeddedCUESheet = false;
     _isArchive = false;
     _isCD = false;
     _useLocalDB = false;
     proxy = _config.GetProxy();
 }
コード例 #30
0
        static int Main(string[] args)
        {
            TextWriter stdout = Console.Out;

            Console.SetOut(Console.Error);

            var settings = new Codecs.FLACCL.EncoderSettings()
            {
                AllowNonSubset = true
            };
            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_precision = -1, max_precision = -1,
                     orders_per_window = -1, orders_per_channel = -1;
            int  input_len = 4096, input_val = 0, input_bps = 16, input_ch = 2, input_rate = 44100;
            int  level = -1, vbr_mode = -1;
            bool do_seektable    = true;
            bool estimate_window = false;
            bool buffered        = false;
            bool ok                 = true;
            bool allowNonSubset     = false;
            bool ignore_chunk_sizes = false;
            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] == "--ignore-chunk-sizes")
                {
                    ignore_chunk_sizes = true;
                }
                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] == "--lax")
                {
                    allowNonSubset = true;
                }
                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)
                {
                    int min_partition_order, max_partition_order;
                    ok = (args[arg].Split(',').Length == 2 &&
                          int.TryParse(args[arg].Split(',')[0], out min_partition_order) &&
                          (settings.MinPartitionOrder = min_partition_order) != -1 &&
                          int.TryParse(args[arg].Split(',')[1], out max_partition_order) &&
                          (settings.MaxPartitionOrder = max_partition_order) != -1) ||
                         (int.TryParse(args[arg], out max_partition_order) &&
                          (settings.MaxPartitionOrder = max_partition_order) != -1);
                }
                else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length)
                {
                    int min_lpc_order, max_lpc_order;
                    ok = (args[arg].Split(',').Length == 2 &&
                          int.TryParse(args[arg].Split(',')[0], out min_lpc_order) &&
                          (settings.MinLPCOrder = min_lpc_order) != -1 &&
                          int.TryParse(args[arg].Split(',')[1], out max_lpc_order) &&
                          (settings.MaxLPCOrder = max_lpc_order) != -1) ||
                         (int.TryParse(args[arg], out max_lpc_order) &&
                          (settings.MaxLPCOrder = max_lpc_order) != -1);
                }
                else if (args[arg] == "--fixed-order" && ++arg < args.Length)
                {
                    int min_fixed_order, max_fixed_order;
                    ok = (args[arg].Split(',').Length == 2 &&
                          int.TryParse(args[arg].Split(',')[0], out min_fixed_order) &&
                          (settings.MinFixedOrder = min_fixed_order) != -1 &&
                          int.TryParse(args[arg].Split(',')[1], out max_fixed_order) &&
                          (settings.MaxFixedOrder = max_fixed_order) != -1) ||
                         (int.TryParse(args[arg], out max_fixed_order) &&
                          (settings.MaxFixedOrder = max_fixed_order) != -1);
                }
                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))
                {
                    settings.BlockSize = intarg;
                }
                else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    settings.Padding = intarg;
                }
                else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out level))
                {
                    ok = level >= 0 && level <= 11;
                    settings.SetEncoderModeIndex(level);
                }
                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-2021 Grigory Chudov.", Codecs.FLACCL.AudioEncoder.Vendor);
                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))
            {
                Usage();
                Console.WriteLine();
                Console.WriteLine("Output file not specified.");
                return(2);
            }

            IAudioSource audioSource;

            try
            {
                if (input_file == "-")
                {
                    audioSource = new Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings()
                    {
                        IgnoreChunkSizes = true
                    }, "", Console.OpenStandardInput());
                }
                else if (input_file == "nul")
                {
                    audioSource = new Codecs.NULL.AudioDecoder(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 Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings(), input_file);
                }
                else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".flac")
                {
                    audioSource = new AudioDecoder(new DecoderSettings(), input_file);
                }
                else
                {
                    Usage();
                    Console.WriteLine();
                    Console.WriteLine("Input file \"{0}\" does not exist.", input_file);
                    return(2);
                }
            }
            catch (Exception ex)
            {
                Usage();
                Console.WriteLine("");
                Console.WriteLine("Error: {0}.", ex.Message);
                return(3);
            }
            if (buffered)
            {
                audioSource = new AudioPipe(audioSource, Codecs.FLACCL.AudioEncoder.MAX_BLOCKSIZE);
            }
            if (output_file == null)
            {
                output_file = Path.ChangeExtension(input_file, "flac");
            }
            settings.PCM            = audioSource.PCM;
            settings.AllowNonSubset = allowNonSubset;
            Codecs.FLACCL.AudioEncoder encoder;

            try
            {
                if (device_type != null)
                {
                    settings.DeviceType = (OpenCLDeviceType)(Enum.Parse(typeof(OpenCLDeviceType), device_type, true));
                }
                encoder = new Codecs.FLACCL.AudioEncoder((output_file == "-" || output_file == "nul") ? "" : output_file,
                                                         output_file == "-" ? Console.OpenStandardOutput() :
                                                         output_file == "nul" ? new NullStream() : null,
                                                         settings);
                settings = encoder.Settings as Codecs.FLACCL.EncoderSettings;
                encoder.FinalSampleCount = audioSource.Length;
                if (stereo_method != null)
                {
                    encoder.StereoMethod = FlakeConstants.LookupStereoMethod(stereo_method);
                }
                if (window_function != null)
                {
                    encoder.WindowFunction = FlakeConstants.LookupWindowFunction(window_function);
                }
                if (max_precision >= 0)
                {
                    encoder.MaxPrecisionSearch = max_precision;
                }
                if (min_precision >= 0)
                {
                    encoder.MinPrecisionSearch = min_precision;
                }
                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);
            }

            IAudioDest  audioDest = encoder;
            AudioBuffer buff      = new AudioBuffer(audioSource, Codecs.FLACCL.AudioEncoder.MAX_BLOCKSIZE);

            if (!quiet)
            {
                Console.WriteLine("Filename  : {0}", input_file);
                Console.WriteLine("File Info : {0} Hz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample, TimeSpan.FromSeconds(audioSource.Length * 1.0 / audioSource.PCM.SampleRate));
                Console.WriteLine("Device    : {0}, Platform: \"{1}\", Version: {2}, Driver: {3}", settings.Device.Trim(), settings.Platform, settings.PlatformVersion.Trim(), settings.DriverVersion.Trim());
            }

            bool keepRunning = true;

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                keepRunning = false;
                if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                {
                    e.Cancel = true;
                }
                else
                {
                    audioDest.Delete();
                }
            };

            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)
                        {
                            long length = Math.Max(audioSource.Position, audioSource.Length);
                            Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
                                                100.0 * audioSource.Position / length,
                                                audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
                                                elapsed,
                                                TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * length)
                                                );
                            lastPrint = elapsed;
                        }
                    }
                    if (!keepRunning)
                    {
                        throw new Exception("Aborted");
                    }
                }
                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),
                                      settings.MaxPartitionOrder,
                                      settings.GPUOnly ? "GPU" : "CPU",
                                      encoder.OrdersPerWindow,
                                      settings.MaxLPCOrder,
                                      encoder.MinPrecisionSearch,
                                      encoder.MaxPrecisionSearch,
                                      encoder.Settings.BlockSize,
                                      encoder.VBRMode,
                                      settings.MaxFixedOrder - settings.MinFixedOrder + 1,
                                      encoder.DoConstant ? "c" : ""
                                      );
            }
            return(0);
        }