Esempio n. 1
0
        public void Encode()
        {
            if (this.trackGain == null && this.drMeter == null)
            {
                throw new SkipEncodingItemException("Neither ReplayGain nor DynamicRange to calculate.");
            }

            AudioBuffer buffer = new AudioBuffer(audioSource.PCM, FileEncoderBase.BufferSize);

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

                ProgressChangedEventArgs eventArgs = new ProgressChangedEventArgs((double)this.audioSource.Position / this.audioSource.Length);
                this.OnProgressChanged(eventArgs);
                if (eventArgs.Cancel)
                {
                    this.trackGain = null;
                    this.drMeter   = null;
                    return;
                }
            }

            if (this.drMeter != null)
            {
                this.drMeter.Finish();
            }
        }
Esempio n. 2
0
 public static void AnalyzeSamples(TrackGain trackGain, AudioBuffer buffer)
 {
     int[] leftSamples  = new int[buffer.Length];
     int[] rightSamples = new int[buffer.Length];
     for (int j = 0; j < buffer.Length; ++j)
     {
         leftSamples[j]  = buffer.Samples[j, 0];
         rightSamples[j] = buffer.Samples[j, 1];
     }
     trackGain.AnalyzeSamples(leftSamples, rightSamples);
 }
Esempio n. 3
0
        public override async Task <(bool Changed, SongData song)> Execute(SongData song)
        {
            int stream = Bass.BASS_StreamCreateFile(song.FullFileName, 0, 0, BASSFlag.BASS_STREAM_DECODE);

            if (stream == 0)
            {
                log.Error("ReplayGain: Could not create stream for {0}. {1}", song.FullFileName, Bass.BASS_ErrorGetCode().ToString());
                return(false, song);
            }

            BASS_CHANNELINFO chInfo = Bass.BASS_ChannelGetInfo(stream);

            if (chInfo == null)
            {
                log.Error("ReplayGain: Could not get channel info for {0}. {1}", song.FullFileName, Bass.BASS_ErrorGetCode().ToString());
                return(false, song);
            }
            var trackGain = new TrackGain(chInfo.freq, 16);

            var leftSamples  = new List <int>();
            var rightSamples = new List <int>();

            var bufLen = 1024;
            var buf    = new short[bufLen];

            while (true)
            {
                int length = Bass.BASS_ChannelGetData(stream, buf, bufLen * sizeof(short));
                if (length == -1)
                {
                    break;
                }

                for (int i = 0; i < length / sizeof(short); i += 2)
                {
                    leftSamples.Add(Convert.ToInt32(buf[i]));
                    rightSamples.Add(Convert.ToInt32(buf[i + 1]));
                }
            }

            Bass.BASS_StreamFree(stream);

            trackGain.AnalyzeSamples(leftSamples.ToArray(), rightSamples.ToArray());

            _albumGain?.AppendTrackData(trackGain);

            double gain = Math.Round(trackGain.GetGain(), 2, MidpointRounding.ToEven);
            double peak = Math.Round(trackGain.GetPeak(), 2, MidpointRounding.ToEven);

            song.ReplayGainTrack     = gain.ToString(CultureInfo.InvariantCulture);
            song.ReplayGainTrackPeak = peak.ToString(CultureInfo.InvariantCulture);

            return(true, song);
        }
Esempio n. 4
0
        public void MixToFile(string filename, bool applyReplayGain)
        {
            Console.WriteLine("Mixing per-channel data...");
            Console.WriteLine("Computing ReplayGain...");
            // Mix the audio. We should probably not be re-reading it here... we could do this in the same pass as loading.
            foreach (var reader in _data.Select(channel => channel.WavReader))
            {
                reader.Position = 0;
            }

            if (applyReplayGain)
            {
                // We read it in a second at a time, to calculate Replay Gains
                var mixer      = new MixingSampleProvider(_data.Select(channel => channel.WavReader.ToSampleProvider().ToStereo()));
                var buffer     = new float[mixer.WaveFormat.SampleRate * 2];
                var replayGain = new TrackGain(SampleRate);
                for (;;)
                {
                    int numRead = mixer.Read(buffer, 0, buffer.Length);
                    if (numRead == 0)
                    {
                        break;
                    }

                    // And analyze
                    replayGain.AnalyzeSamples(buffer, numRead);
                }

                // The +3 is to make it at "YouTube loudness", which is a lot louder than ReplayGain defaults to.
                var gain = replayGain.GetGain() + 3;

                Console.WriteLine($"Applying ReplayGain ({gain:N} dB) and saving to {filename}");

                // Reset the readers again
                foreach (var reader in _data.Select(channel => channel.WavReader))
                {
                    reader.Position = 0;
                }

                mixer = new MixingSampleProvider(_data.Select(channel => channel.WavReader.ToSampleProvider().ToStereo()));
                var amplifier = new VolumeSampleProvider(mixer)
                {
                    Volume = (float)Math.Pow(10, gain / 20)
                };
                WaveFileWriter.CreateWaveFile(filename, amplifier.ToWaveProvider());
            }
            else
            {
                var mixer = new MixingSampleProvider(_data.Select(channel => channel.WavReader.ToSampleProvider().ToStereo()));
                WaveFileWriter.CreateWaveFile(filename, mixer.ToWaveProvider());
            }
        }
Esempio n. 5
0
        public FileEncoderBase(IAudioSource audioSource, string targetFilename, AudioFileTag tags, TrackGain trackGain, DrMeter drMeter)
        {
            if (audioSource == null)
            {
                throw new SkipEncodingItemException("Unsupported audio source.");
            }

            this.targetFilename = targetFilename;
            this.audioSource    = audioSource;
            Directory.CreateDirectory(Path.GetDirectoryName(this.targetFilename));
            this.tags      = tags;
            this.trackGain = trackGain;
            this.drMeter   = drMeter;
        }
Esempio n. 6
0
 public NativeFlacEncoder(IAudioSource audioSource, string targetFilename, AudioFileTag tags, int compressionLevel, TrackGain trackGain, DrMeter drMeter)
     : base(audioSource, targetFilename, tags, trackGain, drMeter)
 {
     this.AudioDest = new NativeFlacWriter(targetFilename, audioSource.PCM)
     {
         CompressionLevel = compressionLevel
     };
 }
Esempio n. 7
0
        private static void Go(string filename, ICollection <string> filenames, int width, int height, int fps,
                               string background,
                               string logo, string vgmFile, int previewFrameskip, float highPassFrequency, float scale,
                               Type triggerAlgorithm, int viewSamples, int numColumns, string ffMpegPath, string ffMpegExtraArgs,
                               string masterAudioFilename, float autoScale, Color gridColor, float gridWidth, bool gridOuter,
                               Color zeroLineColor, float zeroLineWidth, float lineWidth)
        {
            filename = Path.GetFullPath(filename);
            var waitForm = new WaitForm();

            waitForm.Show();

            int sampleRate;

            using (var reader = new WaveFileReader(filenames.First()))
            {
                sampleRate = reader.WaveFormat.SampleRate;
            }

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            int stepsPerFile  = 1 + (highPassFrequency > 0 ? 1 : 0) + 2;
            int totalProgress = filenames.Count * stepsPerFile;
            int progress      = 0;

            var loadTask = Task.Run(() =>
            {
                // Do a parallel read of all files
                var channels = filenames.AsParallel().Select((wavFilename, channelIndex) =>
                {
                    var reader = new WaveFileReader(wavFilename);
                    var buffer = new float[reader.SampleCount];

                    // We read the file and convert to mono
                    reader.ToSampleProvider().ToMono().Read(buffer, 0, (int)reader.SampleCount);
                    Interlocked.Increment(ref progress);

                    // We don't care about ones where the samples are all equal
                    // ReSharper disable once CompareOfFloatsByEqualityOperator
                    if (buffer.Length == 0 || buffer.All(s => s == buffer[0]))
                    {
                        // So we skip steps here
                        reader.Dispose();
                        Interlocked.Add(ref progress, stepsPerFile - 1);
                        return(null);
                    }

                    if (highPassFrequency > 0)
                    {
                        // Apply the high pass filter
                        var filter = BiQuadFilter.HighPassFilter(reader.WaveFormat.SampleRate, highPassFrequency, 1);
                        for (int i = 0; i < buffer.Length; ++i)
                        {
                            buffer[i] = filter.Transform(buffer[i]);
                        }

                        Interlocked.Increment(ref progress);
                    }

                    float max = float.MinValue;
                    foreach (var sample in buffer)
                    {
                        max = Math.Max(max, Math.Abs(sample));
                    }

                    return(new { Data = buffer, WavReader = reader, Max = max });
                }).Where(ch => ch != null).ToList();

                if (autoScale > 0 || scale > 1)
                {
                    // Calculate the multiplier
                    float multiplier = 1.0f;
                    if (autoScale > 0)
                    {
                        multiplier = autoScale / channels.Max(channel => channel.Max);
                    }

                    if (scale > 1)
                    {
                        multiplier *= scale;
                    }

                    // ...and we apply it
                    channels.AsParallel().Select(channel => channel.Data).ForAll(samples =>
                    {
                        for (int i = 0; i < samples.Length; ++i)
                        {
                            samples[i] *= multiplier;
                        }

                        Interlocked.Increment(ref progress);
                    });
                }

                return(channels.ToList());
            });

            while (!loadTask.IsCompleted)
            {
                Application.DoEvents();
                Thread.Sleep(1);
                waitForm.Progress("Reading data...", (double)progress / totalProgress);
            }

            var voiceData = loadTask.Result.Select(channel => channel.Data).ToList();

            waitForm.Close();

            // Emit normalised data to a WAV file for later mixing
            if (masterAudioFilename == null)
            {
                // Generate a temp filename
                masterAudioFilename = filename + ".wav";
                // Mix the audio. We should probably not be re-reading it here... should do this in one pass.
                foreach (var reader in loadTask.Result.Select(channel => channel.WavReader))
                {
                    reader.Position = 0;
                }
                var mixer     = new MixingSampleProvider(loadTask.Result.Select(channel => channel.WavReader.ToSampleProvider()));
                var length    = (int)loadTask.Result.Max(channel => channel.WavReader.SampleCount);
                var mixedData = new float[length * mixer.WaveFormat.Channels];
                mixer.Read(mixedData, 0, mixedData.Length);
                // Then we want to deinterleave it
                var leftChannel  = new float[length];
                var rightChannel = new float[length];
                for (int i = 0; i < length; ++i)
                {
                    leftChannel[i]  = mixedData[i * 2];
                    rightChannel[i] = mixedData[i * 2 + 1];
                }
                // Then Replay Gain it
                // The +3 is to make it at "YouTube loudness", which is a lot louder than ReplayGain defaults to.
                var replayGain = new TrackGain(sampleRate);
                replayGain.AnalyzeSamples(leftChannel, rightChannel);
                float multiplier = (float)Math.Pow(10, (replayGain.GetGain() + 3) / 20);
                Debug.WriteLine($"ReplayGain multiplier is {multiplier}");
                // And apply it
                for (int i = 0; i < mixedData.Length; ++i)
                {
                    mixedData[i] *= multiplier;
                }
                WaveFileWriter.CreateWaveFile(
                    masterAudioFilename,
                    new FloatArraySampleProvider(mixedData, sampleRate).ToWaveProvider());
            }

            var backgroundImage = new BackgroundRenderer(width, height, Color.Black);

            if (background != null)
            {
                using (var bm = Image.FromFile(background))
                {
                    backgroundImage.Add(new ImageInfo(bm, ContentAlignment.MiddleCenter, true, DockStyle.None, 0.5f));
                }
            }

            if (logo != null)
            {
                using (var bm = Image.FromFile(logo))
                {
                    backgroundImage.Add(new ImageInfo(bm, ContentAlignment.BottomRight, false, DockStyle.None, 1));
                }
            }

            if (vgmFile != null)
            {
                var gd3     = Gd3Tag.LoadFromVgm(vgmFile);
                var gd3Text = gd3.ToString();
                if (gd3Text.Length > 0)
                {
                    backgroundImage.Add(new TextInfo(gd3Text, "Tahoma", 16, ContentAlignment.BottomLeft, FontStyle.Regular,
                                                     DockStyle.Bottom, Color.White));
                }
            }

            var renderer = new WaveformRenderer
            {
                BackgroundImage            = backgroundImage.Image,
                Columns                    = numColumns,
                FramesPerSecond            = fps,
                Width                      = width,
                Height                     = height,
                SamplingRate               = sampleRate,
                RenderedLineWidthInSamples = viewSamples,
                RenderingBounds            = backgroundImage.WaveArea
            };

            if (gridColor != Color.Empty && gridWidth > 0)
            {
                renderer.Grid = new WaveformRenderer.GridConfig
                {
                    Color      = gridColor,
                    Width      = gridWidth,
                    DrawBorder = gridOuter
                };
            }

            if (zeroLineColor != Color.Empty && zeroLineWidth > 0)
            {
                renderer.ZeroLine = new WaveformRenderer.ZeroLineConfig
                {
                    Color = zeroLineColor,
                    Width = zeroLineWidth
                };
            }

            foreach (var channel in voiceData)
            {
                renderer.AddChannel(new Channel(channel, Color.White, lineWidth, "Hello world", Activator.CreateInstance(triggerAlgorithm) as ITriggerAlgorithm, 0));
            }

            var outputs = new List <IGraphicsOutput>();

            if (ffMpegPath != null)
            {
                outputs.Add(new FfmpegOutput(ffMpegPath, filename, width, height, fps, ffMpegExtraArgs, masterAudioFilename));
            }

            if (previewFrameskip > 0)
            {
                outputs.Add(new PreviewOutput(previewFrameskip));
            }

            try
            {
                renderer.Render(outputs);
            }
            catch (Exception)
            {
                // Should mean it was cancelled
            }
            finally
            {
                foreach (var graphicsOutput in outputs)
                {
                    graphicsOutput.Dispose();
                }
            }
        }
Esempio n. 8
0
 public LocalMp3Encoder(IAudioSource audioSource, string targetFilename, AudioFileTag tags, int vbrQuality, TrackGain trackGain, DrMeter drMeter)
     : base(audioSource, targetFilename, tags, trackGain, drMeter)
 {
     this.AudioDest = new LameWriter(targetFilename, audioSource.PCM)
     {
         Settings = LameWriterSettings.CreateVbr(vbrQuality)
     };
 }
Esempio n. 9
0
        public static void MixToFile(IList <Channel> channels, string filename, bool applyReplayGain)
        {
            Console.WriteLine("Mixing per-channel data...");

            // We make new readers...
            var readers = new List <WaveFileReader>();

            try
            {
                readers.AddRange(channels.Select(c => new WaveFileReader(c.Filename)));

                if (applyReplayGain)
                {
                    Console.WriteLine("Computing ReplayGain...");
                    // We read it in a second at a time, to calculate Replay Gains
                    var       mixer      = new MixingSampleProvider(readers.Select(x => x.ToSampleProvider().ToStereo()));
                    const int sampleRate = 44100;
                    var       resampler  = new WdlResamplingSampleProvider(mixer, sampleRate);
                    // We use a 1s buffer...
                    var buffer     = new float[sampleRate * 2]; // *2 for stereo
                    var replayGain = new TrackGain(sampleRate);
                    for (;;)
                    {
                        int numRead = resampler.Read(buffer, 0, buffer.Length);
                        if (numRead == 0)
                        {
                            break;
                        }

                        // And analyze
                        replayGain.AnalyzeSamples(buffer, numRead);
                    }

                    // The +3 is to make it at "YouTube loudness", which is a lot louder than ReplayGain defaults to.
                    // TODO make this configurable?
                    var gain = replayGain.GetGain() + 3;

                    Console.WriteLine($"Applying ReplayGain ({gain:N} dB) and saving to {filename}");

                    // Reset the readers
                    foreach (var reader in readers)
                    {
                        reader.Position = 0;
                    }

                    // We make a new mixer just in case resetting the previous one is problematic...
                    mixer = new MixingSampleProvider(readers.Select(x => x.ToSampleProvider().ToStereo()));
                    var amplifier = new VolumeSampleProvider(mixer)
                    {
                        Volume = (float)Math.Pow(10, gain / 20)
                    };
                    WaveFileWriter.CreateWaveFile(filename, amplifier.ToWaveProvider());
                }
                else
                {
                    var mixer = new MixingSampleProvider(readers.Select(x => x.ToSampleProvider().ToStereo()));
                    WaveFileWriter.CreateWaveFile(filename, mixer.ToWaveProvider());
                }
            }
            finally
            {
                foreach (var reader in readers)
                {
                    reader.Dispose();
                }
            }
        }
Esempio n. 10
0
 public DspCalculatorEncoder(IAudioSource audioSource, TrackGain trackGain, DrMeter drMeter)
 {
     this.audioSource = audioSource;
     this.trackGain   = trackGain;
     this.drMeter     = drMeter;
 }
Esempio n. 11
0
 public RemoteMp3VbrEncoder(IPAddress remoteAddress, IAudioSource audioSource, string targetFilename, AudioFileTag tags, int vbrQuality, TrackGain trackGain, DrMeter drMeter)
     : base(audioSource, targetFilename, tags, trackGain, drMeter)
 {
     this.AudioDest = new RemoteMp3VbrWriter(remoteAddress, targetFilename, audioSource.PCM)
     {
         CompressionLevel = vbrQuality
     };
 }