Esempio n. 1
0
        public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle srcRT, RTHandle destRT)
        {
            if (_ditherType != ditherType.value || _ditherTexture == null)
            {
                CoreUtils.Destroy(_ditherTexture);
                _ditherType    = ditherType.value;
                _ditherTexture = GenerateDitherTexture(_ditherType);
            }

#if UNITY_EDITOR
            // In Editor, the gradient will be modified without any hint,
            // so we have to copy the color keys every frame.
            if (true)
#else
            // In Player, we assume no one can modify gradients in profiles,
            // so we update the cache only when the reference was updated.
            if (_cachedGradient != fillGradient.value)
#endif
            {
                _cachedGradient  = fillGradient.value;
                _cachedColorKeys = _cachedGradient.colorKeys;
            }

            Vector2 edgeThresh;

            if (edgeSource.value == EdgeSource.Depth)
            {
                var thresh = 1 / Mathf.Lerp(1000, 1, edgeThreshold.value);
                var scaler = 1 + 2 / (1.01f - edgeContrast.value);
                edgeThresh = new Vector2(thresh, thresh * scaler);
            }
            else // Depth & Color
            {
                var t1 = edgeThreshold.value;
                var t2 = t1 + 1.01f - edgeContrast.value;
                edgeThresh = new Vector2(t1, t2);
            }

            _material.SetColor(ShaderIDs.EdgeColor, edgeColor.value);
            _material.SetVector(ShaderIDs.EdgeThresholds, edgeThresh);
            _material.SetFloat(ShaderIDs.FillOpacity, fillOpacity.value);
            GradientUtility.SetColorKeys(_material, _cachedColorKeys);

            _material.SetTexture(ShaderIDs.DitherTexture, _ditherTexture);
            _material.SetFloat(ShaderIDs.DitherStrength, ditherStrength.value);

            var pass = (int)edgeSource.value;
            if (fillOpacity.value > 0 && _cachedColorKeys.Length > 4)
            {
                pass += 3;
            }
            if (fillGradient.value.mode == GradientMode.Blend)
            {
                pass += 6;
            }

            // Blit to destRT with the overlay shader.
            _material.SetTexture(ShaderIDs.InputTexture, srcRT);
            HDUtils.DrawFullScreen(cmd, _material, destRT, null, pass);
        }
 public static void ChangeTo4bppIndexed(this Bitmap Bmp, PaletteType palettetype = PaletteType.PaletteTypeOptimal,
     DitherType ditherType = DitherType.DitherTypeErrorDiffusion, int optimalColors = 16)
 {
     int Entries;
     // http://msdn.microsoft.com/en-us/library/ms534159(v=vs.85).aspx
     switch (palettetype)
     {
         case PaletteType.PaletteTypeFixedBW:
             Entries = 2;
             break;
         case PaletteType.PaletteTypeFixedHalftone8:
             Entries = 16;
             break;
         case PaletteType.PaletteTypeOptimal:
             if (optimalColors <= 0 || optimalColors > 16)
                 throw new ArgumentOutOfRangeException("Colors should be between 0 (inclusive) and 16 (exclusive)");
             Entries = optimalColors;
             break;
         default:
             throw new ArgumentException("Error");
     }
     var Pal = new int[2 + Entries];
     Pal[0] = (int) PaletteFlags.GrayScale; // Flag
     Pal[1] = Entries; // Count
     if (palettetype == PaletteType.PaletteTypeOptimal)
         GdipInitializePalette(Pal, palettetype, Entries, 0, Bmp.NativeHandle());
     else
         GdipInitializePalette(Pal, palettetype, Entries, 0, IntPtr.Zero);
     if (palettetype == PaletteType.PaletteTypeOptimal)
         if (ditherType != DitherType.DitherTypeNone && ditherType != DitherType.DitherTypeSolid &&
             ditherType != DitherType.DitherTypeErrorDiffusion)
             throw new ArgumentException("Arguments error");
     GdipBitmapConvertFormat(Bmp.NativeHandle(), Convert.ToInt32(PixelFormat.Format4bppIndexed), ditherType,
         palettetype, Pal, 50f);
 }
Esempio n. 3
0
        static void DitherWithMethod(MagickImage img, int colors, DitherType type)
        {
            if (type != DitherType.Random)
            {
                Logger.Log("-> Colors: " + colors + ", Dither Method: " + type.ToString());
            }

            if (type == DitherType.FloydSteinberg)
            {
                img.Quantize(new QuantizeSettings {
                    Colors = colors, DitherMethod = DitherMethod.FloydSteinberg
                });
            }

            if (type == DitherType.Riemersma)
            {
                img.Quantize(new QuantizeSettings {
                    Colors = colors, DitherMethod = DitherMethod.Riemersma
                });
            }

            if (type == DitherType.Ordered4x4)
            {
                img.OrderedDither("o4x4");
            }

            if (type == DitherType.Halftone4x4)
            {
                img.OrderedDither("h4x4a");
            }

            var random = new Random();
            int i      = random.Next(0, 4);

            if (type == DitherType.Random)
            {
                if (i == 0)
                {
                    DitherWithMethod(img, colors, DitherType.FloydSteinberg);
                }
                if (i == 1)
                {
                    DitherWithMethod(img, colors, DitherType.Riemersma);
                }
                if (i == 2)
                {
                    DitherWithMethod(img, colors, DitherType.Ordered4x4);
                }
                if (i == 3)
                {
                    DitherWithMethod(img, colors, DitherType.Halftone4x4);
                }
            }
        }
 public static void ChangeTo1bppIndexed(this Bitmap Bmp,
     DitherType ditherType = DitherType.DitherTypeErrorDiffusion)
 {
     if (ditherType != DitherType.DitherTypeSolid && ditherType != DitherType.DitherTypeErrorDiffusion)
         throw new ArgumentException("Arguments error.");
     var Pal = new int[4];
     Pal[0] = (int) PaletteFlags.GrayScale; // Flag
     Pal[1] = 2; // Count
     GdipInitializePalette(Pal, PaletteType.PaletteTypeFixedBW, 2, 0, IntPtr.Zero);
     GdipBitmapConvertFormat(Bmp.NativeHandle(), Convert.ToInt32(PixelFormat.Format1bppIndexed), ditherType,
         PaletteType.PaletteTypeFixedBW, Pal, 50f);
 }
Esempio n. 5
0
        public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle srcRT, RTHandle destRT)
        {
            if (_ditherType != ditherType.value)
            {
                CoreUtils.Destroy(_ditherTexture);
                _ditherType    = ditherType.value;
                _ditherTexture = GenerateDitherTexture(_ditherType);
            }

        #if UNITY_EDITOR
            // In editor, copy gradient color keys every frame.
            _gradientCache = fillGradient.value.colorKeys;
        #endif

            Vector2 edgeThresh;

            if (edgeSource == EdgeSource.Depth)
            {
                var thresh = 1 / Mathf.Lerp(1000, 1, edgeThreshold.value);
                var scaler = 1 + 2 / (1.01f - edgeContrast.value);
                edgeThresh = new Vector2(thresh, thresh * scaler);
            }
            else // Depth & Color
            {
                var t1 = edgeThreshold.value;
                var t2 = t1 + 1.01f - edgeContrast.value;
                edgeThresh = new Vector2(t1, t2);
            }

            _material.SetColor(ShaderIDs.EdgeColor, edgeColor.value);
            _material.SetVector(ShaderIDs.EdgeThresholds, edgeThresh);
            _material.SetFloat(ShaderIDs.FillOpacity, fillOpacity.value);
            GradientUtility.SetColorKeys(_material, _gradientCache);

            _material.SetTexture(ShaderIDs.DitherTexture, _ditherTexture);
            _material.SetFloat(ShaderIDs.DitherStrength, ditherStrength.value);

            var pass = (int)edgeSource.value;
            if (fillOpacity.value > 0 && _gradientCache.Length > 3)
            {
                pass += 3;
            }
            if (fillGradient.value.mode == GradientMode.Blend)
            {
                pass += 6;
            }

            // Blit to destRT with the overlay shader.
            _material.SetTexture(ShaderIDs.InputTexture, srcRT);
            HDUtils.DrawFullScreen(cmd, _material, destRT, null, pass);
        }
Esempio n. 6
0
        private void Initialize(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format)
        {
            NumChannels   = numChannels;
            SampleRate    = sampleRate;
            BitsPerSample = bitsPerSample;
            _audioFormat  = format;
            _dither       = dither;
            _sampleCount  = 0;
            _doneHeader   = false;

            _fs = null;
            _bs = new BufferedStream(output);
            _w  = new BinaryWriter(_bs);
        }
Esempio n. 7
0
        static Texture2D GenerateDitherTexture(DitherType type)
        {
            if (type == DitherType.Bayer2x2)
            {
                var tex = new Texture2D(2, 2, TextureFormat.R8, false, true);
                tex.LoadRawTextureData(new byte [] { 0, 170, 255, 85 });
                tex.Apply();
                return(tex);
            }

            if (type == DitherType.Bayer3x3)
            {
                var tex = new Texture2D(3, 3, TextureFormat.R8, false, true);
                tex.LoadRawTextureData(new byte [] {
                    0, 223, 95, 191, 159, 63, 127, 31, 255
                });
                tex.Apply();
                return(tex);
            }

            if (type == DitherType.Bayer4x4)
            {
                var tex = new Texture2D(4, 4, TextureFormat.R8, false, true);
                tex.LoadRawTextureData(new byte [] {
                    0, 136, 34, 170, 204, 68, 238, 102,
                    51, 187, 17, 153, 255, 119, 221, 85
                });
                tex.Apply();
                return(tex);
            }

            if (type == DitherType.Bayer8x8)
            {
                var tex = new Texture2D(8, 8, TextureFormat.R8, false, true);
                tex.LoadRawTextureData(new byte [] {
                    0, 194, 48, 242, 12, 206, 60, 255,
                    129, 64, 178, 113, 141, 76, 190, 125,
                    32, 226, 16, 210, 44, 238, 28, 222,
                    161, 97, 145, 80, 174, 109, 157, 93,
                    8, 202, 56, 250, 4, 198, 52, 246,
                    137, 72, 186, 121, 133, 68, 182, 117,
                    40, 234, 24, 218, 36, 230, 20, 214,
                    170, 105, 153, 89, 165, 101, 149, 85
                });
                tex.Apply();
                return(tex);
            }

            return(null);
        }
Esempio n. 8
0
        public static Texture2D DitherTexture(DitherType type)
        {
            switch (type)
            {
            case DitherType.Bayer2x2: return(bayer2x2Texture);

            case DitherType.Bayer3x3: return(bayer3x3Texture);

            case DitherType.Bayer4x4: return(bayer4x4Texture);

            case DitherType.Bayer8x8: return(bayer8x8Texture);

            default: return(bnoise64x64Texture);
            }
        }
Esempio n. 9
0
        public static void Dither(string path, int colorsMin, int colorsMax, DitherType type)
        {
            MagickImage img = IOUtils.ReadImage(path);

            if (img == null)
            {
                return;
            }
            int colors = new Random().Next(colorsMin, colorsMax);

            //Program.Print("-> Colors: " + colors + ", Dither Method: " + quantSettings.DitherMethod.ToString());
            DitherWithMethod(img, colors, type);
            img.Quality = Program.GetDefaultQuality(img);
            img.Write(path);
        }
Esempio n. 10
0
        static private double[] FilterArray(DitherType type)
        {
            switch (type)
            {
            case DitherType.SHAPED:
                return(_Wannamaker);

            case DitherType.SBM:
                return(_SBM);

            case DitherType.NONE:
            case DitherType.TRIANGULAR:
            default:
                return(new double[0]);
            }
        }
Esempio n. 11
0
        public Dither(DitherType type, uint sampleRate, ushort bitsPerSample)
        {
            _type          = type;
            _sampleRate    = sampleRate;
            _bitsPerSample = bitsPerSample;

            _minv = MinValue(_bitsPerSample);
            _maxv = MaxValue(_bitsPerSample);

            _filter  = FilterArray(type);
            _EH      = new double[2 * _filter.Length];
            _HistPos = _filter.Length - 1;

            // Tweak the random number source
            _random = new Random();
        }
Esempio n. 12
0
        public static async Task Dither(string path, int colorsMin, int colorsMax, DitherType type)
        {
            MagickImage img = IOUtils.ReadImage(path);

            if (img == null)
            {
                return;
            }
            int colors = new Random().Next(colorsMin, colorsMax);

            //Logger.Log("-> Colors: " + colors + ", Dither Method: " + quantSettings.DitherMethod.ToString());
            DitherWithMethod(img, colors, type);
            img.Quality = await Program.GetFormatQuality(img);

            img.Write(path);
        }
Esempio n. 13
0
        public static int ChangeTo1bppIndexed(this Bitmap Bmp,
                                              DitherType ditherType = DitherType.ErrorDiffusion)
        {
            if (ditherType != DitherType.Solid && ditherType != DitherType.ErrorDiffusion)
            {
                return(2);
            }

            var Pal = new int[4];

            Pal[0] = (int)PaletteFlags.GrayScale; // Flag
            Pal[1] = 2;                           // Count
            GdipInitializePalette(Pal, PaletteType.FixedBW, 2, 0, IntPtr.Zero);

            return(GdipBitmapConvertFormat(Bmp.NativeHandle(), Convert.ToInt32(PixelFormat.Format1bppIndexed), ditherType,
                                           PaletteType.FixedBW, Pal, 50f));
        }
Esempio n. 14
0
        public static (int, int) GetQualityRange(DitherType dither)
        {
            // Returns valid ranges for FXAA_QUALITY__PRESET (as in FXAAShader.xksl)
            switch (dither)
            {
            case DitherType.Medium:
                return(0, 5);

            case DitherType.Low:
                return(0, 9);

            case DitherType.None:
                return(9, 9);

            default:
                throw new ArgumentOutOfRangeException(nameof(Dither));
            }
        }
Esempio n. 15
0
        public static async void DitherDir(int colorsMin, int colorsMax, DitherType type)
        {
            int counter = 1;

            FileInfo[] files = IOUtils.GetFiles();
            Program.PreProcessing();
            foreach (FileInfo file in files)
            {
                Program.ShowProgress("Dithering Image ", counter, files.Length);
                counter++;
                Dither(file.FullName, colorsMin, colorsMax, type);
                if (counter % 2 == 0)
                {
                    await Program.PutTaskDelay();
                }
            }
            Program.PostProcessing(files.Length);
        }
Esempio n. 16
0
    public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle srcRT, RTHandle destRT)
    {
        if (_ditherType != ditherType.value || _ditherTexture == null)
        {
            CoreUtils.Destroy(_ditherTexture);
            _ditherType    = ditherType.value;
            _ditherTexture = GenerateDitherTexture(_ditherType);
        }

        if (_material == null)
        {
            return;
        }
        _material.SetFloat(IDs.Dithering, dithering.value);
        _material.SetFloat(IDs.Levels, colorLevels.value);
        _material.SetFloat(IDs.Downsampling, downsampling.value);

        _material.SetTexture(IDs.InputTexture, srcRT);
        _material.SetTexture(IDs.DitherTexture, _ditherTexture);
        HDUtils.DrawFullScreen(cmd, _material, destRT);
    }
Esempio n. 17
0
        // //////////////////////////////////////////////////////////////////////////////////////////////////
        // Helpers
        // //////////////////////////////////////////////////////////////////////////////////////////////////

        private void Initialize(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format, bool rewrite)
        {
            NumChannels   = numChannels;
            SampleRate    = sampleRate;
            BitsPerSample = bitsPerSample;
            _audioFormat  = format;
            _dither       = dither;
            _sampleCount  = 0;
            _doneHeader   = false;

            if (File.Exists(fileName))
            {
                if (rewrite == false)
                {
                    throw (new Exception("File already exists: " + fileName));
                }
            }

            _fs = new FileStream(fileName, FileMode.Create);
            _bs = new BufferedStream(_fs);
            _w  = new BinaryWriter(_bs);
        }
Esempio n. 18
0
        public async void SaveGIFAsync(string filepath, PaletteType paletteType, DitherType dithertype, int colorCount = 256)
        {
            if (FCaptureState != CaptureState.Idle)
            {
                return;
            }

            FCaptureState = CaptureState.Writing;
            FSaveFilePath = filepath;

            DoReportProgress();

            foreach (var frame in FFrames)
            {
                FGIF.AddFrame(frame.Image, FDelayInMilliseconds / 10);
            }

            try
            {
                var fileStream = new FileStream(filepath, FileMode.OpenOrCreate);
                FGIF.Save(fileStream, paletteType, dithertype, colorCount);
                fileStream.Dispose();
            }
            catch
            {
                //silently fail
            }
            finally
            {
                FFrames.Clear();
                FGIF.Clear();

                FCaptureState = CaptureState.Idle;
                DoReportProgress();
            }
        }
 internal static extern int /* HRESULT */ Initialize(
     System.Windows.Media.SafeMILHandle /* IWICFormatConverter */ THIS_PTR, 
     System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ source,
     ref Guid dstFormat,
     DitherType dither,
     System.Windows.Media.SafeMILHandle /* IWICBitmapPalette */ bitmapPalette, 
     double alphaThreshold,
     WICPaletteType paletteTranslate 
     ); 
Esempio n. 20
0
 public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither)
 {
     Initialize(fileName, numChannels, sampleRate, bitsPerSample, dither, WaveFormat.ANY, true);
 }
Esempio n. 21
0
 private static extern int GdipBitmapConvertFormat(IntPtr bitmap, int pixelFormat, DitherType dithertype,
                                                   PaletteType palettetype, IntPtr Pal, float alphaThresholdPercent);
Esempio n. 22
0
        public static int ChangeTo8bppIndexed(this Bitmap Bmp, PaletteType palettetype = PaletteType.Optimal,
                                              DitherType ditherType = DitherType.ErrorDiffusion, int optimalColors = 256)
        {
            int Entries;

            // http://msdn.microsoft.com/en-us/library/ms534159(v=vs.85).aspx
            switch (palettetype)
            {
            case PaletteType.FixedBW:
                Entries = 2;
                break;

            case PaletteType.FixedHalftone8:
                Entries = 16;
                break;

            case PaletteType.FixedHalftone27:
                Entries = 36;
                break;

            case PaletteType.FixedHalftone64:
                Entries = 73;
                break;

            case PaletteType.FixedHalftone125:
                Entries = 134;
                break;

            case PaletteType.FixedHalftone216:
                Entries = 225;
                break;

            case PaletteType.FixedHalftone252:
                Entries = 253;
                break;

            case PaletteType.FixedHalftone256:
                Entries = 256;
                break;

            case PaletteType.Optimal:
                Entries = Math.Min(Math.Max(optimalColors, 1), 256);
                break;

            default:
                throw new ArgumentException("Error");
            }
            var Pal = new int[2 + Entries];

            Pal[0] = (int)PaletteFlags.GrayScale; // Flag
            Pal[1] = Entries;                     // Count
            if (palettetype == PaletteType.Optimal)
            {
                GdipInitializePalette(Pal, palettetype, Entries, 0, Bmp.NativeHandle());
            }
            else
            {
                GdipInitializePalette(Pal, palettetype, Entries, 0, IntPtr.Zero);
            }

            if (palettetype == PaletteType.Optimal)
            {
                if (ditherType != DitherType.None && ditherType != DitherType.Solid &&
                    ditherType != DitherType.ErrorDiffusion)
                {
                    return(2);
                }
            }

            return(GdipBitmapConvertFormat(Bmp.NativeHandle(), Convert.ToInt32(PixelFormat.Format8bppIndexed), ditherType, palettetype, Pal, 0));
        }
Esempio n. 23
0
        // -----
        static bool LoadConfig1()
        {
            // Some settings are basically obsolete
            // - never configurable by the client-settings document
            // - but we still allow override from app.config
            // Load them here (rather than in ReadConfig) because the appsettings is always cached anyway...
            // even if we watched it, it would never change...

            System.Configuration.AppSettingsReader rdr;
            try
            {
                rdr = new System.Configuration.AppSettingsReader();
            }
            catch (Exception e)
            {
                Trace.WriteLine("AppSettings error: {0}", e.Message);
                return true;
            }

            try { _debug |= (bool)rdr.GetValue("debug", typeof(bool)); }
            catch (Exception) { }
            try { _inPath = (string)rdr.GetValue("input", typeof(string)); }
            catch (Exception) { }
            try { _isRawIn = (bool)rdr.GetValue("rawIn", typeof(bool)); }
            catch (Exception) { }
            try { _rawtype = (WaveFormat)rdr.GetValue("rawtype", typeof(int)); }
            catch (Exception) { }
            try { _rawbits = (ushort)rdr.GetValue("rawbits", typeof(ushort)); }
            catch (Exception) { }
            try { _rawchan = (ushort)rdr.GetValue("rawchan", typeof(ushort)); }
            catch (Exception) { }

            try { _outPath = (string)rdr.GetValue("output", typeof(string)); }
            catch (Exception) { }
            try { _outBits = (ushort)rdr.GetValue("outbits", typeof(ushort)); }
            catch (Exception) { }

            try { _dither = (DitherType)rdr.GetValue("dither", typeof(int)); }
            catch (Exception) { }
            try { _isRawOut = (bool)rdr.GetValue("rawOut", typeof(bool)); }
            catch (Exception) { }
            try { _partitions = (int)rdr.GetValue("partitions", typeof(int)); }
            catch (Exception) { }

            try { _maxImpulseLength = (int)rdr.GetValue("maximpulse", typeof(int)); }
            catch (Exception) { }

            try { _tail = (bool)rdr.GetValue("tail", typeof(bool)); }
            catch (Exception) { }

            try { _slow = (bool)rdr.GetValue("slow", typeof(bool)); }
            catch (Exception) { }

            // sox settings
            try { _soxExe = (string)rdr.GetValue("soxExe", typeof(string)); }
            catch (Exception) { }

            try { _soxFmt = (string)rdr.GetValue("soxFmt", typeof(string)); }
            catch (Exception) { }

            // aften (or other output device) settings
            try { _aftenExe = (string)rdr.GetValue("aftenExe", typeof(string)); }
            catch (Exception) { }

            try { _aftenFmt = (string)rdr.GetValue("aftenFmt", typeof(string)); }
            catch (Exception) { }

            // Ambisonic settings
            try { _ambiDistance = (double)rdr.GetValue("ambiDistance", typeof(double)); }
            catch (Exception) { }

            try { _ambiShelfFreq = (double)rdr.GetValue("ambiShelfFreq", typeof(double)); }
            catch (Exception) { }

            return true;
        }
Esempio n. 24
0
 public static int ChangeTo16bppRgb555(this Bitmap Bmp,
                                       DitherType ditherType = DitherType.ErrorDiffusion)
 {
     return(GdipBitmapConvertFormat(Bmp.NativeHandle(), Convert.ToInt32(PixelFormat.Format16bppRgb555), ditherType,
                                    PaletteType.Custom, IntPtr.Zero, 50f));
 }
Esempio n. 25
0
 private static double[] FilterArray(DitherType type)
 {
     switch (type)
     {
         case DitherType.SHAPED:
             return _Wannamaker;
         case DitherType.SBM:
             return _SBM;
         case DitherType.NONE:
         case DitherType.TRIANGULAR:
         default:
             return new double[0];
     }
 }
Esempio n. 26
0
        public Dither(DitherType type, uint sampleRate, ushort bitsPerSample)
        {
            _type = type;
            _sampleRate = sampleRate;
            _bitsPerSample = bitsPerSample;

            _minv = MinValue(_bitsPerSample);
            _maxv = MaxValue(_bitsPerSample);

            _filter = FilterArray(type);
            _EH = new double[2 * _filter.Length];
            _HistPos = _filter.Length - 1;

            // Tweak the random number source
            _random = new Random();
        }
Esempio n. 27
0
 public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither)
 {
     Initialize(fileName, numChannels, sampleRate, bitsPerSample, dither, WaveFormat.ANY, true);
 }
Esempio n. 28
0
 public WaveWriter(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format)
 {
     Initialize(output, numChannels, sampleRate, bitsPerSample, dither, format);
 }
Esempio n. 29
0
 // //////////////////////////////////////////////////////////////////////////////////////////////////
 // Constructors
 // //////////////////////////////////////////////////////////////////////////////////////////////////
 public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format, bool rewrite)
 {
     Initialize(fileName, numChannels, sampleRate, bitsPerSample, dither, format, rewrite);
 }
Esempio n. 30
0
 public WaveWriter(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither)
 {
     Initialize(output, numChannels, sampleRate, bitsPerSample, dither, WaveFormat.ANY);
 }
Esempio n. 31
0
        static void InguzDSP(bool doRun)
        {
            DateTime dtStartRun = DateTime.Now;
            string sigdesc = null;

            // We need a few convolvers, of course
            if (_slow)
            {
                _MatrixConvolver = new SlowConvolver();
                _MainConvolver = new SlowConvolver();
                _EQConvolver = new SlowConvolver();
            }
            else
            {
                _MatrixConvolver = new FastConvolver();
                _MainConvolver = new FastConvolver();
                _EQConvolver = new FastConvolver();
            }

            // Shuffler
            _widthShuffler = new Shuffler();

            // Two skewers
            _depthSkewer = new Skewer(true);
            _skewSkewer = new Skewer(true);

            // Writer
            if (_outPath == null)
            {
                _writer = new WaveWriter();  // stdout
            }
            else
            {
                _writer = new WaveWriter(_outPath);
            }
            _writer.NumChannels = _outChannels;
            if (_debug)
            {
                TimeSpan ts = DateTime.Now.Subtract(dtStartRun);
                Trace.WriteLine("Setup " + ts.TotalMilliseconds);
            }

            /*
            DateTime exp = DSPUtil.DSPUtil.EXPIRY;
            if (exp != null)
            {
                if (DateTime.Now.CompareTo(exp) >= 0)
                {
                    Trace.WriteLine("**** THIS EVALUATION VERSION EXPIRED {0}", DSPUtil.DSPUtil.EXPIRY);
                    Trace.WriteLine("**** SEE http://www.inguzaudio.com/DSP/ FOR DETAILS");
                    _MatrixConvolver.Enabled = false;
                    _MainConvolver.Enabled = false;
                    _EQConvolver.Enabled = false;
                    Show("", "InguzDSP has expired.", 2);
                }
                else
                {
                    Trace.WriteLine("This evaluation version will expire {0}", DSPUtil.DSPUtil.EXPIRY);
                }
            }
            */

            // Read the configuration file
            doRun = LoadConfig2();

            // Do any cleanup required before we start
            CleanUp();

            // The main convolver should persist and re-use its leftovers between invocations
            // under this user's (=squeezebox's) ID
            _MainConvolver.partitions = _partitions;
            if (_tail && !IsSigGenNonEQ())
            {
                _MainConvolver.PersistPath = _tempFolder;
                _MainConvolver.PersistTail = _userID;
            }

            // Construct a second convolver for the "tone" (EQ) control.
            _EQConvolver.partitions = _partitions;
            if (_tail && !IsSigGenNonEQ())
            {
                _EQConvolver.PersistPath = _tempFolder;
                _EQConvolver.PersistTail = _userID + ".eq";
            }

            // Make a reader
            // _inPath is the data stream
            WaveReader inputReader = null;
            bool ok = false;
            try
            {
                if (_inStream != null)
                {
                    inputReader = new WaveReader(_inStream);
                }
                else if (_isRawIn)
                {
                    inputReader = new WaveReader(_inPath, _rawtype, _rawbits, _rawchan, _startTime);
                }
                else
                {
                    inputReader = new WaveReader(_inPath, _startTime);
                }
                inputReader.BigEndian = _bigEndian;
                ok = true;
            }
            catch (Exception e)
            {
                Trace.WriteLine("Unable to read: " + e.Message);
                // Just stop (no need to report the stack)
            }

            if (ok)
            {
                if (inputReader.IsSPDIF)
                {
                    // The wave file is just a SPDIF (IEC61937) stream, we shouldn't touch it
                    _inputSPDIF = true;
                    _isBypass = true;
                }
                if (_isBypass)
                {
                    // The settings file says bypass, we shouldn't touch it
                    _gain = 0;
                    _dither = DitherType.NONE;
                }

                uint sr = _inputSampleRate; // Yes, the commandline overrides the source-file...
                if (sr == 0)
                {
                    sr = inputReader.SampleRate;
                }
                if (sr == 0)
                {
                    sr = 44100;
                }
                _inputSampleRate = sr;

                if (WaveFormatEx.AMBISONIC_B_FORMAT_IEEE_FLOAT.Equals(inputReader.FormatEx) ||
                    WaveFormatEx.AMBISONIC_B_FORMAT_PCM.Equals(inputReader.FormatEx))
                {
                    _isBFormat = true;
                }

            }

            ISoundObj source = inputReader;
            if (IsSigGen())
            {
                // Signal-generator source instead of music.
                _isBFormat = false;
                source = GetSignalGenerator(-12, out sigdesc);
                Show("Test signal", sigdesc, 20);
            }

            if (IsSigGenNonEQ() || _isBypass)
            {
                // Signal-generator mode.  Overrides everything else!
                _writer.Input = source;
            }
            else
            {
                if (ok)
                {
                    // Load the room correction impulse to the convolver
                    // (NB: don't do this until we've created the reader, otherwise we can't be user of the samplerate yet...)
                    LoadImpulse();
                    GC.Collect();
                }

                if (ok && _isBFormat)
                {
                    source = DecodeBFormat(source);
                }

                if (ok)
                {
                    ISoundObj nextSrc;

                    // Perform width (matrix) processing on the signal
                    // - Shuffle the channels
                    // - Convolve if there's a filter
                    // - Apply gain to boost or cut the 'side' channel
                    // - Shuffle back
                    _widthShuffler.Input = source;
                    nextSrc = _widthShuffler;

                    // Use a convolver for the matrix filter
                    if (_matrixFilter != null)
                    {
                        LoadMatrixFilter();
                        _MatrixConvolver.Input = TwoChannel(nextSrc);
                        nextSrc = _MatrixConvolver as ISoundObj;
                    }

                    //                if (_depth != 0)
                    //                {
                    //                    // Time-alignment between the LR and MS
                    //                    _depthSkewer.Input = nextSrc;
                    //                    nextSrc = _depthSkewer;
                    //                }

                    // Shuffle back again
                    Shuffler shMSLR = new Shuffler();
                    shMSLR.Input = nextSrc;
                    nextSrc = shMSLR;

                    // Do the room-correction convolution
                    _MainConvolver.Input = TwoChannel(shMSLR);
                    nextSrc = _MainConvolver;

                    if (_skew != 0)
                    {
                        // time-alignment between left and right
                        _skewSkewer.Input = nextSrc;
                        nextSrc = _skewSkewer;
                    }

                    // Splice EQ and non-EQ channels
                    if (IsSigGenEQ())
                    {
                        ChannelSplicer splice = new ChannelSplicer();
                        if (IsSigGenEQL())
                        {
                            splice.Add(new SingleChannel(nextSrc, 0));
                        }
                        else
                        {
                            splice.Add(new SingleChannel(source, 0));
                        }
                        if (IsSigGenEQR())
                        {
                            splice.Add(new SingleChannel(nextSrc, 1));
                        }
                        else
                        {
                            splice.Add(new SingleChannel(source, 1));
                        }
                        nextSrc = splice;
                    }

                    // Process externally with aften or equivalent?
                    if (_aftenNeeded && !_isBypass)
                    {
                        nextSrc = AftenProcess(nextSrc);
                        _outFormat = WaveFormat.PCM;
                        _outBits = 16;
                        _dither = DitherType.NONE;
                    }

                    // Finally pipe this to the writer
                    _writer.Input = nextSrc;
                }
            }
            if (ok)
            {
                //dt = System.DateTime.Now;       // time to here is approx 300ms

                // Dither and output raw-format override anything earlier in the chain
                _writer.Dither = _isBypass ? DitherType.NONE : _dither;
                _writer.Raw = _isRawOut;
                _writer.Format = (_outFormat == WaveFormat.ANY) ? inputReader.Format : _outFormat;
                _writer.BitsPerSample = (_outBits == 0 || _isBypass) ? inputReader.BitsPerSample : _outBits;
                _writer.SampleRate = (_outRate == 0 || _isBypass) ? _inputSampleRate : _outRate;
                SetWriterGain();
                if (IsSigGen())
                {
                    Trace.WriteLine("Test signal: {0}, -12dBfs, {1}/{2} {3} {4}", sigdesc, _writer.BitsPerSample, _writer.SampleRate, _writer.Format, _writer.Dither);
                }
                string amb1 = "";
                string amb2 = "";
                if(_isBFormat)
                {
                    amb1 = "B-Format ";
                    amb2 = _ambiType + " ";
                }
                string big = inputReader.BigEndian ? "(Big-Endian) " : "";
                if (_inputSPDIF)
                {
                    Trace.WriteLine("Stream is SPDIF-wrapped; passing through");
                }
                else if (_isBypass)
                {
                    Trace.WriteLine("Processing is disabled; passing through");
                }
                Trace.WriteLine("{0}/{1} {2}{3} {4}=> {5}/{6} {7}{8} {9}, gain {10} dB", inputReader.BitsPerSample, _inputSampleRate, amb1, inputReader.Format, big, _writer.BitsPerSample, _writer.SampleRate, amb2, _writer.Format, _writer.Dither, _gain);

                TimeSpan elapsedInit = System.DateTime.Now.Subtract(dtStartRun);
                int n = _writer.Run();

                TimeSpan elapsedTotal = System.DateTime.Now.Subtract(dtStartRun);
                double realtime = n / _writer.SampleRate;
                double runtime = elapsedTotal.TotalMilliseconds / 1000;
                Trace.WriteLine("{0} samples, {1} ms ({2} init), {3} * realtime, peak {4} dBfs", n, elapsedTotal.TotalMilliseconds, elapsedInit.TotalMilliseconds, Math.Round(realtime / runtime, 4), Math.Round(_writer.dbfsPeak, 4));

                StopConfigListening();

                _writer.Close();
            }
        }
Esempio n. 32
0
        private void Initialize(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format)
        {
            NumChannels = numChannels;
            SampleRate = sampleRate;
            BitsPerSample = bitsPerSample;
            _audioFormat = format;
            _dither = dither;
            _sampleCount = 0;
            _doneHeader = false;

            _fs = null;
            _bs = new BufferedStream(output);
            _w = new BinaryWriter(_bs);
        }
Esempio n. 33
0
        // //////////////////////////////////////////////////////////////////////////////////////////////////
        // Constructors
        // //////////////////////////////////////////////////////////////////////////////////////////////////

        public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format, bool rewrite)
        {
            Initialize(fileName, numChannels, sampleRate, bitsPerSample, dither, format, rewrite);
        }
Esempio n. 34
0
        // //////////////////////////////////////////////////////////////////////////////////////////////////
        // Helpers
        // //////////////////////////////////////////////////////////////////////////////////////////////////
        private void Initialize(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format, bool rewrite)
        {
            NumChannels = numChannels;
            SampleRate = sampleRate;
            BitsPerSample = bitsPerSample;
            _audioFormat = format;
            _dither = dither;
            _sampleCount = 0;
            _doneHeader = false;

            if (File.Exists(fileName))
            {
                if (rewrite == false)
                    throw (new Exception("File already exists: " + fileName));
            }

            _fs = new FileStream(fileName, FileMode.Create);
            _bs = new BufferedStream(_fs);
            _w = new BinaryWriter(_bs);
        }
Esempio n. 35
0
        public void Save(Stream OutStream, PaletteType paletteType, DitherType ditherType, int colorCount)
        {
            using (var Writer = new BinaryWriter(OutStream))
            {
                //Header
                Writer.Write(FileType.ToCharArray());
                Writer.Write(FileVersion.ToCharArray());

                //Logical Screen Descriptor
                var w = Frames[0].Image.Width;
                var h = Frames[0].Image.Height;
                Writer.Write((short)(DefaultWidth == 0 ? w : DefaultWidth));   // Initial Logical Width
                Writer.Write((short)(DefaultHeight == 0 ? h : DefaultHeight)); // Initial Logical Height

                byte gctInfo = 0;
                if (paletteType != PaletteType.Optimal) //use a global colortable
                {
                    using (var gifStream = new MemoryStream())
                    {
                        var bitmap = new Bitmap(Frames[0].Image);
                        bitmap.ChangeTo8bppIndexed(paletteType, ditherType, colorCount);
                        bitmap.Save(gifStream, ImageFormat.Gif);

                        gifStream.Position = SourceGlobalColorInfoPosition;
                        gctInfo            = (byte)gifStream.ReadByte();
                        var bv          = new BitVector32(gctInfo);
                        var sizeSection = BitVector32.CreateSection(7);
                        SourceColorBlockLength = (1 << (bv[sizeSection] + 1)) * 3;
                        SourceGraphicControlExtensionPosition = SourceColorBlockLength + 13;
                        SourceImageBlockPosition = SourceGraphicControlExtensionPosition;

                        Writer.Write(gctInfo); // Global Color Table Info
                        Writer.Write((byte)0); // Background Color Index
                        Writer.Write((byte)0); // Pixel aspect ratio

                        WriteColorTable(gifStream, Writer);
                    }
                }
                else //local colortables will be used for each frame
                {
                    Writer.Write(gctInfo); // Global Color Table Info
                    Writer.Write((byte)0); // Background Color Index
                    Writer.Write((byte)0); // Pixel aspect ratio
                }

                //Netscape extension for looping animations
                unchecked { Writer.Write((short)ApplicationExtensionBlockIdentifier); };
                Writer.Write((byte)ApplicationBlockSize);
                Writer.Write(NetscapeIdentification.ToCharArray());
                Writer.Write((byte)3);       // Application block length
                Writer.Write((byte)1);
                Writer.Write((short)Repeat); // Repeat count for images.
                Writer.Write((byte)0);       // terminator

                // vvvv Extension Header
                unchecked { Writer.Write((short)ApplicationExtensionBlockIdentifier); };
                Writer.Write((byte)ApplicationBlockSize);
                Writer.Write(VVVVIdentification.ToCharArray());
                Writer.Write((byte)1); // Application block length
                Writer.Write((byte)0); // dummy
                Writer.Write((byte)0); // terminator

                //individual frames
                for (int i = 0; i < Count; ++i)
                {
                    var frame = Frames[i];
                    {
                        using (var gifStream = new MemoryStream())
                        {
                            var bitmap = new Bitmap(frame.Image);
                            if (bitmap.ChangeTo8bppIndexed(paletteType, ditherType, colorCount) == 0)
                            {
                                bitmap.Save(gifStream, ImageFormat.Gif);
                            }
                            else
                            {
                                frame.Image.Save(gifStream, ImageFormat.Gif);
                            }

                            WriteGraphicControlBlock(gifStream, Writer, frame.Delay);
                            WriteImageBlock(gifStream, Writer, paletteType == PaletteType.Optimal, frame.XOffset, frame.YOffset, bitmap.Width, bitmap.Height);
                        }
                    }
                }

                // Complete File
                Writer.Write(FileTrailer);
            }
        }