private void cleanup() { if (this.clip != null) { (this.clip as IDisposable).Dispose(); this.clip = null; } if (this.environment != null) { (this.environment as IDisposable).Dispose(); this.environment = null; } }
//Скрипт из файла public void OpenScript(string scriptPath) { try { this.environment = new AviSynthScriptEnvironment(); this.clip = environment.OpenScriptFile(scriptPath, forced_colorspace, forced_sampletype); //if (!this.clip.HasVideo) throw new ArgumentException("Script doesn't contain video"); } catch (Exception) { cleanup(); throw; } }
private void writeHeader(Stream target, AviSynthClip a) { const uint FAAD_MAGIC_VALUE = 0xFFFFFF00; const uint WAV_HEADER_SIZE = 36; bool useFaadTrick = a.AudioSizeInBytes >= ((long)uint.MaxValue - WAV_HEADER_SIZE); target.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"), 0, 4); target.Write(BitConverter.GetBytes(useFaadTrick ? FAAD_MAGIC_VALUE : (uint)(a.AudioSizeInBytes + WAV_HEADER_SIZE)), 0, 4); target.Write(System.Text.Encoding.ASCII.GetBytes("WAVEfmt "), 0, 8); target.Write(BitConverter.GetBytes((uint)0x10), 0, 4); target.Write(BitConverter.GetBytes((a.SampleType == AudioSampleType.FLOAT) ? (short)0x03 : (short)0x01), 0, 2); target.Write(BitConverter.GetBytes(a.ChannelsCount), 0, 2); target.Write(BitConverter.GetBytes(a.AudioSampleRate), 0, 4); target.Write(BitConverter.GetBytes(a.AvgBytesPerSec), 0, 4); target.Write(BitConverter.GetBytes(a.BytesPerSample * a.ChannelsCount), 0, 2); target.Write(BitConverter.GetBytes(a.BitsPerSample), 0, 2); target.Write(System.Text.Encoding.ASCII.GetBytes("data"), 0, 4); target.Write(BitConverter.GetBytes(useFaadTrick ? (FAAD_MAGIC_VALUE - WAV_HEADER_SIZE) : (uint)a.AudioSizeInBytes), 0, 4); }
public static bool RetrieveAviSynthInfo() { AVSIsMT = false; AVSVersionFloat = 0; AVSVersionString = Languages.Translate("AviSynth is not found!"); try { using (AviSynthClip clp = new AviSynthClip()) { AVSVersionString = clp.Invoke("VersionString", null, AVSVersionString); AVSVersionFloat = clp.Invoke("VersionNumber", null, AVSVersionFloat); AVSIsMT = clp.IsFuncExists("SetMTMode"); if (AVSVersionFloat > 0) { return(true); } } } catch (Exception) { } return(false); }
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; } }
//Скрипт в виде 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; } }