void InsertFileAt(Vegas vegas, String fileName, int trackIndex, Timecode cursorPosition)
    {
        Media      media      = new Media(fileName);
        AudioTrack track      = (AudioTrack)vegas.Project.Tracks[trackIndex];
        AudioEvent audioEvent = track.AddAudioEvent(cursorPosition, media.Length);

        audioEvent.AddTake(media.GetAudioStreamByIndex(0));
    }
        public void FromVegas(Vegas vegas)
        {
            Media media = vegas.Project.MediaPool.AddMedia(Script.Args.ValueOf("media"));

            foreach (MediaStream stream in media.Streams)
            {
                if (stream is VideoStream)
                {
                    VideoTrack t = vegas.Project.AddVideoTrack();
                    VideoEvent e = t.AddVideoEvent(new Timecode(), media.Length);
                    e.ResampleMode = VideoResampleMode.Disable;
                    e.AddTake(stream);
                }
                else if (stream is AudioStream)
                {
                    AudioTrack t = vegas.Project.AddAudioTrack();
                    AudioEvent e = t.AddAudioEvent(new Timecode(), media.Length);
                    e.AddTake(stream);
                }
            }

            vegas.SaveProject(Script.Args.ValueOf("output"));
            vegas.Exit();
        }
Beispiel #3
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);
            }
        }
        public void FromVegas(Vegas vegas)
        {
            try
            {
                _vegas = vegas;

                ScriptArgs args = Script.Args;
                if (args.Count > 0)
                {
                    _closeonfinish = System.Convert.ToBoolean(args.ValueOf("closeonfinish") ?? "false");
                    _savewhendone  = System.Convert.ToBoolean(args.ValueOf("savewhendone") ?? "false");
                    _makeveg       = System.Convert.ToBoolean(args.ValueOf("makeveg") ?? "false");
                    _file          = args.ValueOf("file");
                }
                else
                {
                    var dialog = new OpenFileDialog {
                        Filter = ".srt files (*.srt)|*.srt", CheckPathExists = true, InitialDirectory = vegas.Project.FilePath
                    };
                    DialogResult result = dialog.ShowDialog();
                    vegas.UpdateUI();

                    if (result == DialogResult.OK)
                    {
                        _file = Path.GetFullPath(dialog.FileName);
                    }
                    else
                    {
                        return;
                    }
                }

                if (_makeveg)
                {
                    Media media = vegas.Project.MediaPool.AddMedia(Script.Args.ValueOf("media"));

                    foreach (MediaStream stream in media.Streams)
                    {
                        if (stream is VideoStream)
                        {
                            VideoTrack t = vegas.Project.AddVideoTrack();
                            VideoEvent e = t.AddVideoEvent(new Timecode(), media.Length);
                            e.ResampleMode = VideoResampleMode.Disable;
                            e.AddTake(stream);
                        }
                        else if (stream is AudioStream)
                        {
                            AudioTrack t = vegas.Project.AddAudioTrack();
                            AudioEvent e = t.AddAudioEvent(new Timecode(), media.Length);
                            e.AddTake(stream);
                        }
                    }

                    vegas.SaveProject(Script.Args.ValueOf("output"));
                }

                using (FileStream fs = new FileStream(_file, FileMode.Open, FileAccess.Read))
                    using (StreamReader stream = new StreamReader(fs))
                    {
                        while (!stream.EndOfStream)
                        {
                            string line = stream.ReadLine();

                            if (Regex.IsMatch(line, "^[0-9]+$"))
                            {
                                line = stream.ReadLine();

                                if (Regex.IsMatch(line, "^" + SRT_TIME_PATTERN + " --> " + SRT_TIME_PATTERN + "$"))
                                {
                                    MatchCollection stamps = Regex.Matches(line, SRT_TIME_PATTERN);

                                    TimeSpan s = TimeSpan.ParseExact(stamps[0].Value, SRT_TIME_FORMAT, null);
                                    TimeSpan e = TimeSpan.ParseExact(stamps[1].Value, SRT_TIME_FORMAT, null);
                                    string   t = string.Empty;

                                    while (!stream.EndOfStream)
                                    {
                                        line = stream.ReadLine();
                                        if (!string.IsNullOrEmpty(line))
                                        {
                                            if (!string.IsNullOrEmpty(t))
                                            {
                                                t += "[br]";
                                            }

                                            t += line;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }

                                    Region r = Convert(s, e, t);
                                    if (r != null)
                                    {
                                        vegas.Project.Regions.Add(r);
                                    }
                                }
                            }
                        }
                    }

                if (_savewhendone)
                {
                    vegas.SaveProject();
                }
                if (_closeonfinish)
                {
                    vegas.Exit();
                }
            }
            catch (VegasException e)
            {
                Vegas.COM.ShowError(e.Title, e.Message);
            }
        }
Beispiel #5
0
    private void Import(Config config, Vegas vegas)
    {
        // Load XML file
        if (!File.Exists(config.XmlFile))
        {
            throw new Exception("XML file does not exist.");
        }
        XmlDocument xmlDocument = new XmlDocument();

        xmlDocument.Load(config.XmlFile);

        // Determine image file names
        XmlNodeList   mouthCueElements = xmlDocument.SelectNodes("//mouthCue");
        List <string> shapeNames       = new List <string>();

        foreach (XmlElement mouthCueElement in mouthCueElements)
        {
            if (!shapeNames.Contains(mouthCueElement.InnerText))
            {
                shapeNames.Add(mouthCueElement.InnerText);
            }
        }
        Dictionary <string, string> imageFileNames = GetImageFileNames(config.OneImageFile, shapeNames.ToArray());

        // Create new project
        bool    promptSave = !config.DiscardChanges;
        bool    showDialog = false;
        Project project    = new Project(promptSave, showDialog);

        // Set frame size
        Bitmap testImage = new Bitmap(config.OneImageFile);

        project.Video.Width  = testImage.Width;
        project.Video.Height = testImage.Height;

        // Set frame rate
        if (config.FrameRate < 0.1 || config.FrameRate > 100)
        {
            throw new Exception("Invalid frame rate.");
        }
        project.Video.FrameRate = config.FrameRate;

        // Set other video settings
        project.Video.FieldOrder       = VideoFieldOrder.ProgressiveScan;
        project.Video.PixelAspectRatio = 1;

        // Add video track with images
        VideoTrack videoTrack = vegas.Project.AddVideoTrack();

        foreach (XmlElement mouthCueElement in mouthCueElements)
        {
            Timecode   start      = GetTimecode(mouthCueElement.Attributes["start"]);
            Timecode   length     = GetTimecode(mouthCueElement.Attributes["end"]) - start;
            VideoEvent videoEvent = videoTrack.AddVideoEvent(start, length);
            Media      imageMedia = new Media(imageFileNames[mouthCueElement.InnerText]);
            videoEvent.AddTake(imageMedia.GetVideoStreamByIndex(0));
        }

        // Add audio track with original sound file
        AudioTrack audioTrack = vegas.Project.AddAudioTrack();
        Media      audioMedia = new Media(xmlDocument.SelectSingleNode("//soundFile").InnerText);
        AudioEvent audioEvent = audioTrack.AddAudioEvent(new Timecode(0), audioMedia.Length);

        audioEvent.AddTake(audioMedia.GetAudioStreamByIndex(0));
    }
Beispiel #6
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);
            }
        }