Пример #1
0
 //Скрипт в виде string
 public void ParseScript(string script)
 {
     try
     {
         this.environment = new AviSynthScriptEnvironment();
         this.clip        = environment.ParseScript(script, forced_colorspace, forced_sampletype);
         //if (!this.clip.HasVideo) throw new ArgumentException("Script doesn't contain video");
     }
     catch (Exception)
     {
         cleanup();
         throw;
     }
 }
Пример #2
0
        private void StartEncoding()
        {
            try
            {
                using (AviSynthScriptEnvironment env = new AviSynthScriptEnvironment())
                {
                    using (AviSynthClip a = env.ParseScript(script, AviSynthColorspace.Undefined, AudioSampleType.INT16))
                    {
                        if (a.ChannelsCount == 0)
                        {
                            throw new Exception("Can't find audio stream");
                        }

                        const int MAX_SAMPLES_PER_ONCE = 4096;
                        int       frameSample          = 0;

                        //MeGUI
                        int frameBufferTotalSize = MAX_SAMPLES_PER_ONCE * a.ChannelsCount * a.BytesPerSample;

                        byte[] frameBuffer = new byte[frameBufferTotalSize];

                        if (encoderPath != null)
                        {
                            createEncoderProcess();
                        }

                        if (!IsGainDetecting)
                        {
                            //Обычное кодирование/извлечение звука
                            using (Stream target = getOutputStream())
                            {
                                //let's write WAV Header
                                writeHeader(target, a);

                                GCHandle h       = GCHandle.Alloc(frameBuffer, GCHandleType.Pinned);
                                IntPtr   address = h.AddrOfPinnedObject();
                                try
                                {
                                    while (frameSample < a.SamplesCount)
                                    {
                                        locker.WaitOne();
                                        int nHowMany = Math.Min((int)(a.SamplesCount - frameSample), MAX_SAMPLES_PER_ONCE);
                                        a.ReadAudio(address, frameSample, nHowMany);

                                        locker.WaitOne();
                                        frame = (int)(((double)frameSample / (double)a.SamplesCount) * (double)a.num_frames);

                                        target.Write(frameBuffer, 0, nHowMany * a.ChannelsCount * a.BytesPerSample);

                                        target.Flush();
                                        frameSample += nHowMany;
                                        Thread.Sleep(0);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (_encoderProcess != null && _encoderProcess.HasExited)
                                    {
                                        throw new Exception("Abnormal encoder termination (exit code = " + _encoderProcess.ExitCode.ToString() + ")");
                                    }
                                    else
                                    {
                                        throw new Exception(ex.Message, ex);
                                    }
                                }
                                finally
                                {
                                    h.Free();
                                }

                                if (a.BytesPerSample % 2 == 1)
                                {
                                    target.WriteByte(0);
                                }
                            }
                        }
                        else
                        {
                            //Определяем peak level
                            int      max = 0, e = 0, ch = a.ChannelsCount;
                            GCHandle h       = GCHandle.Alloc(frameBuffer, GCHandleType.Pinned);
                            IntPtr   address = h.AddrOfPinnedObject();
                            try
                            {
                                while (frameSample < a.SamplesCount)
                                {
                                    locker.WaitOne();
                                    int nHowMany = Math.Min((int)(a.SamplesCount - frameSample), MAX_SAMPLES_PER_ONCE);
                                    frame = (int)(((double)frameSample / (double)a.SamplesCount) * (double)a.num_frames);
                                    a.ReadAudio(address, frameSample, nHowMany);

                                    locker.WaitOne();
                                    int n = 0, pos = 0;
                                    while (n < nHowMany)
                                    {
                                        //Ищем максимум для каждого канала
                                        for (int i = 0; i < ch; i += 1)
                                        {
                                            //Это годится только для 16-ти битного звука!
                                            e    = BitConverter.ToInt16(frameBuffer, pos);
                                            max  = Math.Max(max, Math.Abs(e));
                                            pos += 2;
                                        }

                                        n += 1;
                                    }

                                    frameSample += nHowMany;
                                    Thread.Sleep(0);
                                }

                                if (max != 0)
                                {
                                    gain = 20.0 * Math.Log10((32767.0 * Convert.ToDouble(m.volume.Replace("%", ""))) / ((double)max * 100.0));
                                }
                            }
                            finally
                            {
                                h.Free();
                            }
                        }
                        if (_encoderProcess != null)
                        {
                            _encoderProcess.WaitForExit();
                            _readFromStdErrThread.Join();
                            _readFromStdOutThread.Join();
                            if (_encoderProcess.ExitCode != 0)
                            {
                                throw new Exception("Abnormal encoder termination (exit code = " + _encoderProcess.ExitCode.ToString() + ")");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!IsAborted)
                {
                    IsErrors      = true;
                    exception_raw = ex;
                    error_text    = ((IsGainDetecting) ? "Gain Detector Error: " : "AviSynth Encoder Error: ") + ex.Message;
                    try
                    {
                        Thread.Sleep(500);
                        if (_encoderProcess != null && _encoderProcess.HasExited && _encoderProcess.ExitCode != 0)
                        {
                            error_text += ("\r\n" + (!string.IsNullOrEmpty(_encoderStdErr) ? "\r\n" + _encoderStdErr : "") +
                                           (!string.IsNullOrEmpty(_encoderStdOut) ? "\r\n" + _encoderStdOut : ""));
                        }
                    }
                    catch (Exception exc)
                    {
                        error_text += "\r\n\r\nThere was Exception while trying to get error info:\r\n" + exc.Message;
                    }
                }
            }
            finally
            {
                try
                {
                    if (_encoderProcess != null && !_encoderProcess.HasExited)
                    {
                        _encoderProcess.Kill();
                        _encoderProcess.WaitForExit();
                        _readFromStdErrThread.Join();
                        _readFromStdOutThread.Join();
                    }
                }
                catch { }
                _encoderProcess       = null;
                _readFromStdErrThread = null;
                _readFromStdOutThread = null;
                _encoderThread        = null;
            }
        }
Пример #3
0
 //Скрипт в виде string
 public void ParseScript(string script)
 {
     try
     {
         this.environment = new AviSynthScriptEnvironment();
         this.clip = environment.ParseScript(script, forced_colorspace, forced_sampletype);
         //if (!this.clip.HasVideo) throw new ArgumentException("Script doesn't contain video");
     }
     catch (Exception)
     {
         cleanup();
         throw;
     }
 }
Пример #4
0
        private void StartEncoding()
        {
            try
            {
                using (AviSynthScriptEnvironment env = new AviSynthScriptEnvironment())
                {
                    using (AviSynthClip a = env.ParseScript(script, AviSynthColorspace.Undefined, AudioSampleType.INT16))
                    {
                        if (a.ChannelsCount == 0) throw new Exception("Can't find audio stream");

                        const int MAX_SAMPLES_PER_ONCE = 4096;
                        int frameSample = 0;

                        //MeGUI
                        int frameBufferTotalSize = MAX_SAMPLES_PER_ONCE * a.ChannelsCount * a.BytesPerSample;

                        byte[] frameBuffer = new byte[frameBufferTotalSize];

                        if (encoderPath != null) createEncoderProcess();

                        if (!IsGainDetecting)
                        {
                            //Обычное кодирование/извлечение звука
                            using (Stream target = getOutputStream())
                            {
                                //let's write WAV Header
                                writeHeader(target, a);

                                GCHandle h = GCHandle.Alloc(frameBuffer, GCHandleType.Pinned);
                                IntPtr address = h.AddrOfPinnedObject();
                                try
                                {
                                    while (frameSample < a.SamplesCount)
                                    {
                                        locker.WaitOne();
                                        int nHowMany = Math.Min((int)(a.SamplesCount - frameSample), MAX_SAMPLES_PER_ONCE);
                                        a.ReadAudio(address, frameSample, nHowMany);

                                        locker.WaitOne();
                                        frame = (int)(((double)frameSample / (double)a.SamplesCount) * (double)a.num_frames);

                                        target.Write(frameBuffer, 0, nHowMany * a.ChannelsCount * a.BytesPerSample);

                                        target.Flush();
                                        frameSample += nHowMany;
                                        Thread.Sleep(0);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (_encoderProcess != null && _encoderProcess.HasExited)
                                        throw new Exception("Abnormal encoder termination (exit code = " + _encoderProcess.ExitCode.ToString() + ")");
                                    else throw new Exception(ex.Message, ex);
                                }
                                finally
                                {
                                    h.Free();
                                }

                                if (a.BytesPerSample % 2 == 1)
                                    target.WriteByte(0);
                            }
                        }
                        else
                        {
                            //Определяем peak level
                            int max = 0, e = 0, ch = a.ChannelsCount;
                            GCHandle h = GCHandle.Alloc(frameBuffer, GCHandleType.Pinned);
                            IntPtr address = h.AddrOfPinnedObject();
                            try
                            {
                                while (frameSample < a.SamplesCount)
                                {
                                    locker.WaitOne();
                                    int nHowMany = Math.Min((int)(a.SamplesCount - frameSample), MAX_SAMPLES_PER_ONCE);
                                    frame = (int)(((double)frameSample / (double)a.SamplesCount) * (double)a.num_frames);
                                    a.ReadAudio(address, frameSample, nHowMany);

                                    locker.WaitOne();
                                    int n = 0, pos = 0;
                                    while (n < nHowMany)
                                    {
                                        //Ищем максимум для каждого канала
                                        for (int i = 0; i < ch; i += 1)
                                        {
                                            //Это годится только для 16-ти битного звука!
                                            e = BitConverter.ToInt16(frameBuffer, pos);
                                            max = Math.Max(max, Math.Abs(e));
                                            pos += 2;
                                        }

                                        n += 1;
                                    }

                                    frameSample += nHowMany;
                                    Thread.Sleep(0);
                                }

                                if (max != 0)
                                    gain = 20.0 * Math.Log10((32767.0 * Convert.ToDouble(m.volume.Replace("%", ""))) / ((double)max * 100.0));
                            }
                            finally
                            {
                                h.Free();
                            }
                        }
                        if (_encoderProcess != null)
                        {
                            _encoderProcess.WaitForExit();
                            _readFromStdErrThread.Join();
                            _readFromStdOutThread.Join();
                            if (_encoderProcess.ExitCode != 0)
                                throw new Exception("Abnormal encoder termination (exit code = " + _encoderProcess.ExitCode.ToString() + ")");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!IsAborted)
                {
                    IsErrors = true;
                    exception_raw = ex;
                    error_text = ((IsGainDetecting) ? "Gain Detector Error: " : "AviSynth Encoder Error: ") + ex.Message;
                    try
                    {
                        Thread.Sleep(500);
                        if (_encoderProcess != null && _encoderProcess.HasExited && _encoderProcess.ExitCode != 0)
                            error_text += ("\r\n" + (!string.IsNullOrEmpty(_encoderStdErr) ? "\r\n" + _encoderStdErr : "") +
                                (!string.IsNullOrEmpty(_encoderStdOut) ? "\r\n" + _encoderStdOut : ""));
                    }
                    catch (Exception exc)
                    {
                        error_text += "\r\n\r\nThere was Exception while trying to get error info:\r\n" + exc.Message;
                    }
                }
            }
            finally
            {
                try
                {
                    if (_encoderProcess != null && !_encoderProcess.HasExited)
                    {
                        _encoderProcess.Kill();
                        _encoderProcess.WaitForExit();
                        _readFromStdErrThread.Join();
                        _readFromStdOutThread.Join();
                    }
                }
                catch { }
                _encoderProcess = null;
                _readFromStdErrThread = null;
                _readFromStdOutThread = null;
                _encoderThread = null;
            }
        }