public void FromVegas(Vegas vegas)
        {
            string         rendererName = Script.Args.ValueOf("renderer");
            string         templateName = Script.Args.ValueOf("template");
            Renderer       renderer     = vegas.Renderers.FindByName(rendererName);
            RenderTemplate template     = null;

            if (renderer != null)
            {
                template = renderer.Templates.FindByName(templateName);
            }
            if (template == null)
            {
                vegas.ShowError("Render template not found.");
                return;
            }
            string       path   = vegas.Project.FilePath;
            string       saveas = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + ".rendered.mp4";
            RenderStatus status = vegas.Render(saveas, template);

            if (status == RenderStatus.Complete || status == RenderStatus.Canceled || status == RenderStatus.Quit)
            {
                vegas.Exit();
            }
            else
            {
                vegas.ShowError("Render incomplete. Please try again.");
                return;
            }
        }
        public void FromVegas(Vegas vegas)
        {
            string         rendererName = Script.Args.ValueOf("renderer");
            string         templateName = Script.Args.ValueOf("template");
            string         saveas       = Script.Args.ValueOf("saveas", true);
            Renderer       renderer     = vegas.Renderers.FindByName(rendererName);
            RenderTemplate template     = null;

            if (renderer != null)
            {
                template = renderer.Templates.FindByName(templateName);
            }
            if (template == null)
            {
                vegas.ShowError("Render template not found.");
                return;
            }
            if (string.IsNullOrWhiteSpace(saveas))
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    Filter           = ".mp4 file (*.mp4)|*.mp4",
                    Title            = "Select render location",
                    InitialDirectory = vegas.Project.FilePath,
                    CheckPathExists  = true,
                    AddExtension     = true
                };

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    saveas = Path.GetFullPath(saveFileDialog.FileName);
                }
            }
            if (string.IsNullOrWhiteSpace(saveas))
            {
                vegas.ShowError("No valid save path exists.");
                return;
            }

            RenderStatus status = vegas.Render(saveas, template);

            if (status == RenderStatus.Complete || status == RenderStatus.Canceled || status == RenderStatus.Quit)
            {
                vegas.Exit();
            }
            else
            {
                vegas.ShowError("Render incomplete. Please try again.");
                return;
            }
        }
Example #3
0
    public void FromVegas(Vegas vegas)
    {
        myVegas = vegas;
        if (AudioBusMode.Surround == myVegas.Project.Audio.MasterBusMode)
        {
            ProjectChannelCount = 6;
        }
        else if (AudioBusMode.Stereo == myVegas.Project.Audio.MasterBusMode)
        {
            ProjectChannelCount = 2;
        }

        CanUseSelection = (1 < myVegas.Transport.LoopRegionLength.Nanos);

        if (DialogResult.OK != DoDialog())
        {
            return;
        }

        RenderArgs args = new RenderArgs();

        if (null == SelectedTemplate)
        {
            throw new ApplicationException("render template not selected.");
        }

        args.RenderTemplate = SelectedTemplate;
        args.UseSelection   = CanUseSelection && UseSelection;
        foreach (Track track in myVegas.Project.Tracks)
        {
            if (track.IsAudio())
            {
                AudioTrack audioTrack = (AudioTrack)track;
                String     trackName  = String.Format("track {0:D2}", audioTrack.DisplayIndex);
                if (!String.IsNullOrEmpty(audioTrack.Name))
                {
                    trackName = String.Format("{0} ({1})", trackName, track.Name);
                }
                trackName      += args.RenderTemplate.FileExtensions[0].Substring(1);
                args.OutputFile = Path.Combine(OutputDir, trackName);
                audioTrack.Solo = true;
                myVegas.Render(args);
                audioTrack.Solo = false;
            }
        }
    }
        public bool RenderFile(FileInfo fiVeg, FileInfo fiRendered, RenderTemplate renderTemplate, RenderStatusManager rsm, object dr)
        {
            DateTime renderStart = DateTime.Now;
            DateTime renderEnd;
            TimeSpan renderTime;

            rsm.Dialog.Hide(); // Temporarily hide because during load the UX kills it.
            rsm.UpdateField(dr, RenderStatusManager.Fields.Names.RenderStart, renderStart);
            if (myVegas.Project != null)
            {
                // No close method so create a clean new project without the ability to prompt for save of existing
                // and then open after that.
                myVegas.NewProject(false, false);
            }
            myVegas.UpdateUI();
            rsm.UpdateField(dr, RenderStatusManager.Fields.Names.RenderStatus, "Loading");
            myVegas.OpenFile(fiVeg.FullName);
            myVegas.UpdateUI();
            myVegas.WaitForIdle();
            rsm.Dialog.Show();

            // Render
            RenderArgs ra = new RenderArgs();

            ra.OutputFile     = fiRendered.FullName;
            ra.RenderTemplate = renderTemplate;
            Timecode projectLength = GetProjectLength();

            rsm.UpdateField(dr, RenderStatusManager.Fields.Names.ProjectLength, projectLength);
            ra.Length     = projectLength;
            ra.StartNanos = 0;

            rsm.UpdateField(dr, RenderStatusManager.Fields.Names.RenderStatus, "Rendering");
            RenderStatus status = myVegas.Render(ra);

            renderEnd  = DateTime.Now;
            renderTime = renderEnd - renderStart;
            rsm.UpdateField(dr, RenderStatusManager.Fields.Names.RenderEnd, renderEnd);
            rsm.UpdateField(dr, RenderStatusManager.Fields.Names.RenderTime, renderTime);
            rsm.UpdateField(dr, RenderStatusManager.Fields.Names.RenderStatus, status.ToString());
            return(status == RenderStatus.Complete);
        }
Example #5
0
        public RenderStatus DoRender(RenderArgs args)
        {
            RenderStatus status = vegas.Render(args);

            switch (status)
            {
            case RenderStatus.Complete:
            case RenderStatus.Canceled:
                break;

            case RenderStatus.Failed:
            default:
                ShowError("Render failed:\n"
                          + "\n    File name: "
                          + args.OutputFile
                          + "\n    Template: "
                          + args.RenderTemplate.Name);
                break;
            }
            return(status);
        }
Example #6
0
        public bool renderProject(
            Vegas myVegas,
            string projectFilePath,
            string rendererName,
            string templateName,
            string outputFilePath
            )
        {
            if (myVegas.OpenProject(projectFilePath))
            {
                RenderArgs renderArgs = new RenderArgs(myVegas.Project);
                renderArgs.RenderTemplate = findTemplate(rendererName, templateName, myVegas.Renderers);
                renderArgs.OutputFile     = outputFilePath;
                RenderStatus renderStatus = myVegas.Render(renderArgs);
                if (renderStatus == RenderStatus.Complete)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #7
0
        private void Encode(Vegas vegas, string scriptDirectory, RenderArgs renderArgs, string pathEncoded)
        {
            var status = vegas.Render(renderArgs);

            if (status != RenderStatus.Complete)
            {
                MessageBox.Show("Unexpected render status: " + status);
                return;
            }

            var encode = new Process {
                StartInfo =
                {
                    UseShellExecute  = false,
                    FileName         = Path.Combine(scriptDirectory, "_internal",  "ffmpeg", "ffmpeg.exe"),
                    WorkingDirectory = Path.Combine(scriptDirectory, "_internal"),
                    Arguments        = "-y -hide_banner -nostdin -i \"" + renderArgs.OutputFile +
                                       "\" -c:v libxvid -q:v 1 -g 1M -flags +mv4+qpel -mpeg_quant 1 -c:a copy \"" + pathEncoded +
                                       "\"",
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true
                }
            };

            encode.Start();
            var error  = encode.StandardError.ReadToEnd();
            var output = encode.StandardOutput.ReadToEnd();

            Debug.WriteLine(output);
            Debug.WriteLine("---------------------");
            Debug.WriteLine(error);
            encode.WaitForExit();

            File.Delete(renderArgs.OutputFile);
            File.Delete(renderArgs.OutputFile + ".sfl");
        }
Example #8
0
        public void FromVegas(Vegas vegas)
        {
            var start  = vegas.Transport.LoopRegionStart;
            var length = vegas.Transport.LoopRegionLength;

            try {
                var frameRate    = vegas.Project.Video.FrameRate;
                var frameRateInt = (int)Math.Round(frameRate * 1000);

                var scriptDirectory = Path.GetDirectoryName(Script.File);
                if (scriptDirectory == null)
                {
                    MessageBox.Show("Couldn't get script directory path!");
                    return;
                }

                var xvidPath = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
                if (string.IsNullOrEmpty(xvidPath))
                {
                    xvidPath = Environment.GetEnvironmentVariable("ProgramFiles");
                }
                if (string.IsNullOrEmpty(xvidPath))
                {
                    MessageBox.Show("Couldn't get Xvid install path!");
                    return;
                }
                xvidPath += @"\Xvid\uninstall.exe";
                if (!File.Exists(xvidPath))
                {
                    MessageBox.Show(
                        "Xvid codec not installed. The script will install it now and may ask for admin access to install it.");
                    var xvid = new Process {
                        StartInfo =
                        {
                            UseShellExecute  = true,
                            FileName         = Path.Combine(scriptDirectory, "_internal",  "xvid", "xvid.exe"),
                            WorkingDirectory = Path.Combine(scriptDirectory,"_internal"),
                            Arguments        =
                                "--unattendedmodeui none  --mode unattended  --AutoUpdater no --decode_divx DIVX  --decode_3ivx 3IVX --decode_divx DIVX --decode_other MPEG-4",
                            CreateNoWindow = true,
                            Verb           = "runas"
                        }
                    };
                    try {
                        xvid.Start();
                    }
                    catch (Win32Exception e) {
                        if (e.NativeErrorCode == 1223)
                        {
                            MessageBox.Show("Admin privilege for Xvid installation refused.");
                            return;
                        }

                        throw;
                    }

                    xvid.WaitForExit();
                    GetStandardTemplates(vegas);
                    GetTemplate(vegas, frameRateInt);
                    MessageBox.Show(
                        "Xvid installed and render template generated for the current frame rate. Please restart Sony Vegas and run the script again.");
                    return;
                }

                var template = GetTemplate(vegas, frameRateInt);
                if (template == null)
                {
                    GetStandardTemplates(vegas);
                    GetTemplate(vegas, frameRateInt);
                    MessageBox.Show(
                        "Render template generated for the current frame rate. Please restart Sony Vegas and run the script again.");
                    return;
                }

                var frameCount = (string)Registry.GetValue(
                    "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                    "FrameCount", "");
                var defaultCount = 1;
                if (frameCount != "")
                {
                    try {
                        var value = int.Parse(frameCount);
                        if (value > 0)
                        {
                            defaultCount = value;
                        }
                    }
                    catch (Exception) {
                        // ignore
                    }
                }

                var prompt = new Form {
                    Width  = 500,
                    Height = 140,
                    Text   = "Datamoshing Parameters"
                };
                var textLabel = new Label {
                    Left = 10, Top = 10, Text = "Frame count"
                };
                var inputBox =
                    new NumericUpDown {
                    Left = 200, Top = 10, Width = 200, Minimum = 1, Maximum = 1000000000, Value = defaultCount
                };
                var textLabel2 = new Label {
                    Left = 10, Top = 40, Text = "Frames repeats"
                };
                var inputBox2 = new NumericUpDown {
                    Left    = 200,
                    Top     = 40,
                    Width   = 200,
                    Value   = 1,
                    Minimum = 1,
                    Maximum = 1000000000,
                    Text    = ""
                };
                var confirmation = new Button {
                    Text = "OK", Left = 200, Width = 100, Top = 70
                };
                confirmation.Click += (sender, e) => { prompt.DialogResult = DialogResult.OK; prompt.Close(); };
                prompt.Controls.Add(confirmation);
                prompt.Controls.Add(textLabel);
                prompt.Controls.Add(inputBox);
                prompt.Controls.Add(textLabel2);
                prompt.Controls.Add(inputBox2);
                inputBox2.Select();
                prompt.AcceptButton = confirmation;
                if (prompt.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                var size   = (int)inputBox.Value;
                var repeat = (int)inputBox2.Value;

                if (repeat <= 0)
                {
                    MessageBox.Show("Frames repeats must be > 0!");
                    return;
                }

                if (length.FrameCount < size)
                {
                    MessageBox.Show("The selection must be as long as the frame count!");
                    return;
                }

                if (start.FrameCount < 1)
                {
                    MessageBox.Show("The selection mustn't start on the first frame of the project!");
                    return;
                }

                if (defaultCount != size)
                {
                    Registry.SetValue(
                        "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                        "FrameCount", size.ToString(), RegistryValueKind.String);
                }

                VideoTrack videoTrack = null;
                for (var i = vegas.Project.Tracks.Count - 1; i >= 0; i--)
                {
                    videoTrack = vegas.Project.Tracks[i] as VideoTrack;
                    if (videoTrack != null)
                    {
                        break;
                    }
                }

                AudioTrack audioTrack = null;
                for (var i = 0; i < vegas.Project.Tracks.Count; i++)
                {
                    audioTrack = vegas.Project.Tracks[i] as AudioTrack;
                    if (audioTrack != null)
                    {
                        break;
                    }
                }

                if (videoTrack == null && audioTrack == null)
                {
                    MessageBox.Show("No tracks found!");
                    return;
                }

                var changed     = false;
                var finalFolder = (string)Registry.GetValue(
                    "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                    "ClipFolder", "");
                while (string.IsNullOrEmpty(finalFolder) || !Directory.Exists(finalFolder))
                {
                    MessageBox.Show("Select the folder to put generated datamoshed clips into.");
                    changed = true;
                    var dialog = new CommonOpenFileDialog {
                        IsFolderPicker          = true,
                        EnsurePathExists        = true,
                        EnsureFileExists        = false,
                        AllowNonFileSystemItems = false,
                        DefaultFileName         = "Select Folder",
                        Title = "Select the folder to put generated datamoshed clips into"
                    };

                    if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                    {
                        MessageBox.Show("No folder selected");
                        return;
                    }

                    finalFolder = dialog.FileName;
                }

                if (changed)
                {
                    Registry.SetValue(
                        "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                        "ClipFolder", finalFolder, RegistryValueKind.String);
                }

                var path = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) +
                                        "-" +
                                        Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) +
                                        ".avi");
                var pathEncoded = Path.Combine(vegas.TemporaryFilesPath,
                                               Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                               Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi");
                var pathDatamoshedBase = Path.Combine(finalFolder,
                                                      Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                                      Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8));
                var pathDatamoshed       = pathDatamoshedBase + ".avi";
                var pathEncodedEscape    = pathEncoded.Replace("\\", "/");
                var pathDatamoshedEscape = pathDatamoshed.Replace("\\", "/");

                var renderArgs = new RenderArgs {
                    OutputFile     = path,
                    Start          = Timecode.FromFrames(start.FrameCount - 1),
                    Length         = Timecode.FromFrames(length.FrameCount + 1),
                    RenderTemplate = template
                };
                var status = vegas.Render(renderArgs);
                if (status != RenderStatus.Complete)
                {
                    MessageBox.Show("Unexpected render status: " + status);
                    return;
                }

                string[] datamoshConfig =
                {
                    "var input=\"" + pathEncodedEscape + "\";",
                    "var output=\"" + pathDatamoshedEscape + "\";",
                    "var size=" + size + ";",
                    "var repeat=" + repeat + ";"
                };

                File.WriteAllLines(Path.Combine(scriptDirectory, "_internal", "config_datamosh.js"), datamoshConfig);

                var encode = new Process {
                    StartInfo =
                    {
                        UseShellExecute  = false,
                        FileName         = Path.Combine(scriptDirectory, "_internal",  "ffmpeg", "ffmpeg.exe"),
                        WorkingDirectory = Path.Combine(scriptDirectory, "_internal"),
                        Arguments        = "-y -hide_banner -nostdin -i \"" + path +
                                           "\" -c:v libxvid -q:v 1 -g 1M -flags +mv4+qpel -mpeg_quant 1 -c:a copy \"" + pathEncoded +
                                           "\"",
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        CreateNoWindow         = true
                    }
                };
                encode.Start();
                var output = encode.StandardOutput.ReadToEnd();
                var error  = encode.StandardError.ReadToEnd();
                Debug.WriteLine(output);
                Debug.WriteLine("---------------------");
                Debug.WriteLine(error);
                encode.WaitForExit();

                File.Delete(path);
                File.Delete(path + ".sfl");

                var datamosh = new Process {
                    StartInfo =
                    {
                        UseShellExecute        = false,
                        FileName               = Path.Combine(scriptDirectory,        "_internal",   "avidemux", "avidemux2_cli.exe"),
                        WorkingDirectory       = Path.Combine(scriptDirectory,        "_internal"),
                        Arguments              = "--nogui --run avidemux_datamosh.js",
                        RedirectStandardInput  = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        CreateNoWindow         = true
                    }
                };
                datamosh.Start();
                datamosh.StandardInput.WriteLine("n");
                output = datamosh.StandardOutput.ReadToEnd();
                error  = datamosh.StandardError.ReadToEnd();
                Debug.WriteLine(output);
                Debug.WriteLine("---------------------");
                Debug.WriteLine(error);
                datamosh.WaitForExit();

                File.Delete(pathEncoded);
                File.Delete(pathEncoded + ".sfl");

                var media = vegas.Project.MediaPool.AddMedia(pathDatamoshed);
                media.TimecodeIn = Timecode.FromFrames(1);

                VideoEvent videoEvent = null;
                if (videoTrack != null)
                {
                    videoEvent =
                        videoTrack.AddVideoEvent(start, Timecode.FromFrames(1 + length.FrameCount + (repeat - 1) * size));
                    videoEvent.AddTake(media.GetVideoStreamByIndex(0));
                }

                AudioEvent audioEvent = null;
                if (audioTrack != null)
                {
                    audioEvent =
                        audioTrack.AddAudioEvent(start, Timecode.FromFrames(1 + length.FrameCount + (repeat - 1) * size));
                    audioEvent.AddTake(media.GetAudioStreamByIndex(0));
                }

                if (videoTrack != null && audioTrack != null)
                {
                    var group = new TrackEventGroup();
                    vegas.Project.Groups.Add(group);
                    group.Add(videoEvent);
                    group.Add(audioEvent);
                }
            }
            catch (Exception e) {
                MessageBox.Show("Unexpected exception: " + e.Message);
                Debug.WriteLine(e);
            }
        }
Example #9
0
        public void FromVegas(Vegas vegas)
        {
            var start  = vegas.Transport.LoopRegionStart;
            var length = vegas.Transport.LoopRegionLength;

            try {
                var frameRate    = vegas.Project.Video.FrameRate;
                var frameRateInt = (int)Math.Round(frameRate * 1000);

                var scriptDirectory = Path.GetDirectoryName(Script.File);
                if (scriptDirectory == null)
                {
                    MessageBox.Show("Couldn't get script directory path!");
                    return;
                }

                var template = GetTemplate(vegas, frameRateInt);
                if (template == null)
                {
                    GetStandardTemplates(vegas);
                    GetTemplate(vegas, frameRateInt);
                    MessageBox.Show(
                        "Render template generated for the current frame rate. Please restart Sony Vegas and run the script again.");
                    return;
                }

                VideoTrack videoTrack = null;
                for (var i = vegas.Project.Tracks.Count - 1; i >= 0; i--)
                {
                    videoTrack = vegas.Project.Tracks[i] as VideoTrack;
                    if (videoTrack != null)
                    {
                        break;
                    }
                }

                AudioTrack audioTrack = null;
                for (var i = 0; i < vegas.Project.Tracks.Count; i++)
                {
                    audioTrack = vegas.Project.Tracks[i] as AudioTrack;
                    if (audioTrack != null)
                    {
                        break;
                    }
                }

                if (videoTrack == null && audioTrack == null)
                {
                    MessageBox.Show("No tracks found!");
                    return;
                }

                var changed     = false;
                var finalFolder = (string)Registry.GetValue(
                    "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                    "RenderClipFolder", "");
                while (string.IsNullOrEmpty(finalFolder) || !Directory.Exists(finalFolder))
                {
                    MessageBox.Show("Select the folder to put generated rendered clips into.\n" +
                                    "(As they are stored uncompressed with alpha, they can take a lot of space (think 1 GB/minute). " +
                                    "Choose a location with a lot of available space and go remove some clips there if you need space.)");
                    changed = true;
                    var dialog = new CommonOpenFileDialog {
                        IsFolderPicker          = true,
                        EnsurePathExists        = true,
                        EnsureFileExists        = false,
                        AllowNonFileSystemItems = false,
                        DefaultFileName         = "Select Folder",
                        Title = "Select the folder to put generated rendered clips into"
                    };

                    if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                    {
                        MessageBox.Show("No folder selected");
                        return;
                    }
                    finalFolder = dialog.FileName;
                }

                if (changed)
                {
                    Registry.SetValue(
                        "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                        "RenderClipFolder", finalFolder, RegistryValueKind.String);
                }

                var path = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) +
                                        "-" +
                                        Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) +
                                        ".avi");
                var pathEncoded = Path.Combine(vegas.TemporaryFilesPath,
                                               Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                               Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi");

                var renderArgs = new RenderArgs {
                    OutputFile     = path,
                    Start          = Timecode.FromFrames(start.FrameCount),
                    Length         = Timecode.FromFrames(length.FrameCount),
                    RenderTemplate = template
                };
                var status = vegas.Render(renderArgs);
                if (status != RenderStatus.Complete)
                {
                    MessageBox.Show("Unexpected render status: " + status);
                    return;
                }

                File.Delete(pathEncoded + ".sfl");

                var media = vegas.Project.MediaPool.AddMedia(path);

                VideoEvent videoEvent = null;
                if (videoTrack != null)
                {
                    videoEvent =
                        videoTrack.AddVideoEvent(start, length);
                    ((VideoStream)videoEvent.AddTake(media.GetVideoStreamByIndex(0)).MediaStream).AlphaChannel =
                        VideoAlphaType.Straight;
                }

                AudioEvent audioEvent = null;
                if (audioTrack != null)
                {
                    audioEvent =
                        audioTrack.AddAudioEvent(start, length);
                    audioEvent.AddTake(media.GetAudioStreamByIndex(0));
                }

                if (videoTrack != null && audioTrack != null)
                {
                    var group = new TrackEventGroup();
                    vegas.Project.Groups.Add(group);
                    group.Add(videoEvent);
                    group.Add(audioEvent);
                }
            }
            catch (Exception e) {
                MessageBox.Show("Unexpected exception: " + e.Message);
                Debug.WriteLine(e);
            }
        }
Example #10
0
    public void FromVegas(Vegas vegas)
    {
        if (vegas.Project.Length.ToMilliseconds() == 0)
        {
            return;
        }
        SetDllDirectory(VegasDir + "\\Script Depends");
        string RegKey = "HKEY_CURRENT_USER\\Software\\Sony Creative Software\\Vegas Pro\\frameserver";
        int    AddBuffer = 1; int RenderLoop = 1; string outputDirectory = "";

        try {
            AddBuffer       = (int)Registry.GetValue(RegKey, "AddBuffer", 1);
            RenderLoop      = (int)Registry.GetValue(RegKey, "RenderLoopRegion", 1);
            outputDirectory = (string)Registry.GetValue(RegKey, "TempDir", "");
        } catch {}
        string outDirDefualt = Environment.GetEnvironmentVariable("TEMP") + "\\frameserver";

        if (outputDirectory == "")
        {
            outputDirectory = outDirDefualt;
        }
        if (!Directory.Exists(outputDirectory))
        {
            try {
                Directory.CreateDirectory(outputDirectory);
            } catch {
                outputDirectory = outDirDefualt;
                Directory.CreateDirectory(outputDirectory);
            }
        }

        // Start virtual file system, AviSynth and HandBrake
        ahktextdll(Unzip(Convert.FromBase64String(StartScriptData)), "", "");
        while (!ahkReady())
        {
            Thread.Sleep(100);
        }
        ahkassign("TempFileDir", outputDirectory);
        ahkassign("AddBuffer", AddBuffer.ToString());
        ahkassign("RegKey", RegKey);
        ahkassign("VegasDir", VegasDir);
        ahkPause("Off");

        Regex videoRendererRegexp = new Regex(@"DebugMode FrameServer", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        Regex videoTemplateRegexp = new Regex(@"Project Default", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        try
        {
            //Add an empty event to first video track to solve frameserver audio bug
            if (AddBuffer > 0)
            {
                foreach (Track CurTrack in vegas.Project.Tracks)
                {
                    if (CurTrack.IsVideo())
                    {
                        TargetTrack = CurTrack;
                        emptyEvent  = new VideoEvent(vegas.Project, vegas.Project.Length, Timecode.FromMilliseconds(1000), null);
                        CurTrack.Events.Add(emptyEvent);
                        break;
                    }
                }
            }
            // Check timeline's loop-region
            Timecode renderStart  = new Timecode();
            Timecode renderLength = vegas.Project.Length;
            if (RenderLoop > 0)
            {
                renderStart = vegas.SelectionStart;
                if (AddBuffer > 0)
                {
                    renderLength = vegas.SelectionLength + Timecode.FromMilliseconds(1000);
                }
                else
                {
                    renderLength = vegas.SelectionLength;
                }
            }

            //Define export path and file name
            string projDir, projName, videoOutputFile;
            string projFile = vegas.Project.FilePath;
            if ((null == projFile) || (0 == projFile.Length))
            {
                projDir  = "";
                projName = "Untitled";
            }
            else
            {
                projDir  = Path.GetDirectoryName(projFile) + Path.DirectorySeparatorChar;
                projName = Path.GetFileNameWithoutExtension(projFile);
            }
            videoOutputFile = outputDirectory + "\\" + OutFileName + ".avi";
            if (null == videoOutputFile)
            {
                throw new Exception("Process terminated");
            }
            Renderer aviRenderer = FindRenderer(videoRendererRegexp, vegas);
            if (null == aviRenderer)
            {
                throw new Exception("Could not find DebugMode FrameServer");
            }

            // Start export
            RenderTemplate videoTemplate = FindRenderTemplate(aviRenderer, videoTemplateRegexp, vegas);
            if (null == videoTemplate)
            {
                throw new Exception("Could not find the render preset defined by the script");
            }
            RenderStatus renderStatus = vegas.Render(videoOutputFile, videoTemplate, renderStart, renderLength);
            if (AddBuffer > 0)
            {
                TargetTrack.Events.Remove(emptyEvent);
            }
        } catch (Exception ex) {
            if (AddBuffer > 0)
            {
                TargetTrack.Events.Remove(emptyEvent);
            }
            MessageBox.Show(ex.ToString());
        }
    }
Example #11
0
        public void FromVegas(Vegas vegas)
        {
            var        videoTrackIndex = -1;
            VideoTrack videoTrackStart = null;
            VideoEvent videoEvent      = null;

            for (var i = 0; i < vegas.Project.Tracks.Count; i++)
            {
                var track = vegas.Project.Tracks[i];
                if (!track.IsVideo())
                {
                    continue;
                }
                foreach (var trackEvent in track.Events)
                {
                    if (!trackEvent.Selected)
                    {
                        continue;
                    }
                    if (videoEvent != null)
                    {
                        MessageBox.Show("Only a single video event can be selected!");
                        return;
                    }

                    videoTrackIndex = i;
                    videoTrackStart = (VideoTrack)track;
                    videoEvent      = (VideoEvent)trackEvent;
                }
            }

            if (videoEvent == null)
            {
                MessageBox.Show("Select a video event to be layered!");
                return;
            }

            try {
                var frameRate    = vegas.Project.Video.FrameRate;
                var frameRateInt = (int)Math.Round(frameRate * 1000);

                var scriptDirectory = Path.GetDirectoryName(Script.File);
                if (scriptDirectory == null)
                {
                    MessageBox.Show("Couldn't get script directory path!");
                    return;
                }

                var template = GetTemplate(vegas, frameRateInt);
                if (template == null)
                {
                    GetStandardTemplates(vegas);
                    GetTemplate(vegas, frameRateInt);
                    MessageBox.Show(
                        "Render template generated for the current frame rate. Please restart Sony Vegas and run the script again.");
                    return;
                }

                var layeringCount = (string)Registry.GetValue(
                    "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                    "LayerCount", "");
                var defaultCount = 1;
                if (layeringCount != "")
                {
                    try {
                        var value = int.Parse(layeringCount);
                        if (value > 0)
                        {
                            defaultCount = value;
                        }
                    }
                    catch (Exception) {
                        // ignore
                    }
                }

                var renderChecked = (string)Registry.GetValue(
                    "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                    "RenderLayer", "");
                var defaultCheck = renderChecked == "True";
                var prompt       = new Form {
                    Width      = 500,
                    Height     = 170,
                    Text       = "Layering Parameters",
                    KeyPreview = true
                };
                var textLabel = new Label {
                    Left = 10, Top = 10, Text = "Layer count"
                };
                var inputBox = new NumericUpDown {
                    Left    = 200,
                    Top     = 10,
                    Width   = 200,
                    Minimum = 1,
                    Maximum = 1000000000,
                    Value   = defaultCount
                };
                var textLabel2 = new Label {
                    Left = 10, Top = 40, Text = "Layering offset"
                };
                var inputBox2 =
                    new NumericUpDown {
                    Left = 200, Top = 40, Width = 200, Minimum = -1000000000, Maximum = 1000000000, Text = ""
                };
                var textLabel3 = new Label {
                    Left = 10, Top = 70, Text = "Render"
                };
                var inputBox3 = new CheckBox {
                    Left    = 200,
                    Top     = 70,
                    Width   = 200,
                    Checked = defaultCheck
                };
                var confirmation = new Button {
                    Text = "OK", Left = 200, Width = 100, Top = 100
                };
                confirmation.Click += (sender, e) => {
                    prompt.DialogResult = DialogResult.OK;
                    prompt.Close();
                };
                prompt.KeyPress += (sender, args) => {
                    if (args.KeyChar != ' ')
                    {
                        return;
                    }
                    inputBox3.Checked = !inputBox3.Checked;
                    args.Handled      = true;
                };
                prompt.Controls.Add(confirmation);
                prompt.Controls.Add(textLabel);
                prompt.Controls.Add(inputBox);
                prompt.Controls.Add(textLabel2);
                prompt.Controls.Add(inputBox2);
                prompt.Controls.Add(textLabel3);
                prompt.Controls.Add(inputBox3);
                inputBox2.Select();
                prompt.AcceptButton = confirmation;
                if (prompt.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var count  = (int)inputBox.Value;
                var offset = (int)inputBox2.Value;
                var render = inputBox3.Checked;

                if (offset == 0)
                {
                    MessageBox.Show("Layering offset must not be 0!");
                    return;
                }

                if (count <= 0)
                {
                    MessageBox.Show("Layer count must be > 0!");
                    return;
                }

                if (defaultCount != count)
                {
                    Registry.SetValue(
                        "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                        "LayerCount", count.ToString(), RegistryValueKind.String);
                }

                if (defaultCheck != render)
                {
                    Registry.SetValue(
                        "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                        "RenderLayer", render.ToString(), RegistryValueKind.String);
                }

                var newTracks  = new List <VideoTrack>();
                var newEvents  = new List <VideoEvent>();
                var current    = 0;
                var baseOffset = offset > 0 ? 0 : -count * offset;

                for (var i = videoTrackIndex - 1; i >= 0 && current < count; i--)
                {
                    var videoTrack = vegas.Project.Tracks[i] as VideoTrack;
                    if (videoTrack == null)
                    {
                        continue;
                    }
                    newEvents.Add((VideoEvent)videoEvent.Copy(videoTrack,
                                                              Timecode.FromFrames(videoEvent.Start.FrameCount + baseOffset + (++current) * offset)));
                }

                for (; current < count;)
                {
                    var videoTrack = vegas.Project.AddVideoTrack();
                    newTracks.Add(videoTrack);
                    newEvents.Add((VideoEvent)videoEvent.Copy(videoTrack,
                                                              Timecode.FromFrames(videoEvent.Start.FrameCount + baseOffset + (++current) * offset)));
                }

                var start = videoEvent.Start;
                if (offset < 0)
                {
                    videoEvent.Start = Timecode.FromFrames(videoEvent.Start.FrameCount + baseOffset);
                }

                if (!render)
                {
                    return;
                }
                var changed     = false;
                var finalFolder = (string)Registry.GetValue(
                    "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                    "LayerClipFolder", "");
                while (string.IsNullOrEmpty(finalFolder) || !Directory.Exists(finalFolder))
                {
                    MessageBox.Show("Select the folder to put generated layered clips into.\n" +
                                    "(As they are stored uncompressed with alpha, they can take a lot of space (think 1 GB/minute). " +
                                    "Choose a location with a lot of available space and go remove some clips there if you need space.)");
                    changed = true;
                    var dialog = new CommonOpenFileDialog {
                        IsFolderPicker          = true,
                        EnsurePathExists        = true,
                        EnsureFileExists        = false,
                        AllowNonFileSystemItems = false,
                        DefaultFileName         = "Select Folder",
                        Title = "Select the folder to put generated layered clips into"
                    };

                    if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                    {
                        MessageBox.Show("No folder selected");
                        return;
                    }

                    finalFolder = dialog.FileName;
                }

                if (changed)
                {
                    Registry.SetValue(
                        "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets",
                        "LayerClipFolder", finalFolder, RegistryValueKind.String);
                }

                var path = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) +
                                        "-" +
                                        Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) +
                                        ".avi");
                var pathEncoded = Path.Combine(vegas.TemporaryFilesPath,
                                               Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                               Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi");

                var renderArgs = new RenderArgs {
                    OutputFile     = path,
                    Start          = Timecode.FromFrames(start.FrameCount),
                    Length         = Timecode.FromFrames(videoEvent.Length.FrameCount + count * Math.Abs(offset)),
                    RenderTemplate = template
                };
                var status = vegas.Render(renderArgs);
                if (status != RenderStatus.Complete)
                {
                    MessageBox.Show("Unexpected render status: " + status);
                    return;
                }

                File.Delete(pathEncoded + ".sfl");

                var media         = vegas.Project.MediaPool.AddMedia(path);
                var newVideoEvent = videoTrackStart.AddVideoEvent(start,
                                                                  Timecode.FromFrames(videoEvent.Length.FrameCount + count * Math.Abs(offset)));
                ((VideoStream)newVideoEvent.AddTake(media.GetVideoStreamByIndex(0)).MediaStream).AlphaChannel =
                    VideoAlphaType.Straight;
                videoEvent.Track.Events.Remove(videoEvent);

                foreach (var newEvent in newEvents)
                {
                    newEvent.Track.Events.Remove(newEvent);
                }

                foreach (var newTrack in newTracks)
                {
                    vegas.Project.Tracks.Remove(newTrack);
                }
            }
            catch (Exception e) {
                MessageBox.Show("Unexpected exception: " + e.Message);
                Debug.WriteLine(e);
            }
        }