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();
        }
Esempio n. 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);
            }
        }
Esempio n. 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));
    }
Esempio n. 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);
            }
        }
Esempio n. 7
0
        public static void AddElement(ElementStep elementStep)
        {
            if (!elementStep.Selector.IsValid() || elementStep.Selector.ElementType == ElementType.None)
            {
                return;
            }

            if (elementStep.Selector.ElementType == ElementType.Event)
            {
                Track track      = SelectorService.GetTrack(elementStep.Selector);
                var   trackRegEx = new Regex(elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                Media media      = MainContainer.Vegas.Project.MediaPool.Cast <Media>().FirstOrDefault(x =>
                                                                                                       trackRegEx.IsMatch(Path.GetFileName(x.FilePath)));
                if (elementStep.Selector.IsAudio() && media.Streams.Any(x => x.MediaType == MediaType.Audio))
                {
                    TrackEvent trackEvent = new AudioEvent(
                        Timecode.FromString(elementStep.DataPropertyList[DataPropertyHolder.TIMECODE].Value),
                        media.Length,
                        elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                    track.Events.Add(trackEvent);
                    trackEvent.AddTake(media.Streams[0], true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                }
                if (elementStep.Selector.IsVideo() && media.Streams.Any(x => x.MediaType == MediaType.Video))
                {
                    TrackEvent trackEvent = new VideoEvent(Timecode.FromString(elementStep.DataPropertyList[DataPropertyHolder.TIMECODE].Value),
                                                           media.Length,
                                                           elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                    if (media.Streams.Any(x => x.MediaType == MediaType.Audio))
                    {
                        elementStep.Selector.ElementMediaType = ElementMediaType.Audio;
                        AudioTrack  syncAudioTrack = SelectorService.GetTrack(elementStep.Selector) as AudioTrack;
                        MediaStream audioStream    = media.Streams.FirstOrDefault(x => x.MediaType == MediaType.Audio);
                        MediaStream videoStream    = media.Streams.FirstOrDefault(x => x.MediaType == MediaType.Video);
                        var         audioEvent     = new AudioEvent(
                            Timecode.FromString(elementStep.DataPropertyList[DataPropertyHolder.TIMECODE].Value),
                            media.Length,
                            elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                        track.Events.Add(trackEvent);
                        trackEvent.AddTake(videoStream, true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                        syncAudioTrack.Events.Add(audioEvent);
                        audioEvent.AddTake(audioStream, true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                    }
                    else
                    {
                        track.Events.Add(trackEvent);
                        trackEvent.AddTake(media.Streams[0], true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value);
                    }
                }
            }
            if (elementStep.Selector.ElementType == ElementType.Track)
            {
                if (elementStep.Selector.IsAudio())
                {
                    MainContainer.Vegas.Project.AddAudioTrack().Name = elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value;
                }
                if (elementStep.Selector.IsVideo())
                {
                    MainContainer.Vegas.Project.AddVideoTrack().Name = elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value;
                }
            }
        }
Esempio n. 8
0
    public void FromVegas(Vegas vegas)
    {
        // select a midi file
        MessageBox.Show("请选择一个MIDI文件。");
        OpenFileDialog openFileDialog = new OpenFileDialog();

        openFileDialog.Filter           = "*.mid|*.mid|所有文件|*.*";
        openFileDialog.RestoreDirectory = true;
        openFileDialog.FilterIndex      = 1;
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            midiName = openFileDialog.FileName;
        }
        else
        {
            return;
        }

        MidiFile midi = new MidiFile(midiName);

        // generate statistics of each midi track
        String[] trackInfo       = new String[midi.Events.Tracks];
        int      ticksPerQuarter = midi.DeltaTicksPerQuarterNote;
        double   msPerQuarter    = 0;

        for (int i = 0; i < midi.Events.Tracks; i++)
        {
            String info1      = "轨道 " + i.ToString() + ": ";
            String info2      = "";
            int    notesCount = 0;
            String info3      = "起音 ";

            foreach (MidiEvent midiEvent in midi.Events[i])
            {
                if ((midiEvent is NoteEvent) && !(midiEvent is NoteOnEvent))
                {
                    NoteEvent noteEvent = midiEvent as NoteEvent;
                    if (notesCount == 0)
                    {
                        info3 = info3 + noteEvent.NoteName;
                    }
                    notesCount++;
                }
                if ((midiEvent is PatchChangeEvent) && info2.Length == 0)
                {
                    PatchChangeEvent patchEvent = midiEvent as PatchChangeEvent;
                    for (int j = 4; j < patchEvent.ToString().Split(' ').Length; j++)
                    {
                        info2 += patchEvent.ToString().Split(' ')[j];
                    }
                }
                if ((midiEvent is TempoEvent) && msPerQuarter == 0)
                {
                    TempoEvent tempoEvent = midiEvent as TempoEvent;
                    msPerQuarter = Convert.ToDouble(tempoEvent.MicrosecondsPerQuarterNote) / 1000;
                }
            }

            trackInfo[i] = info1 + info2 + "; 音符数: " + notesCount.ToString() + "; " + info3;
        }

        // select a video clip
        MessageBox.Show("请选择一个视频或音频素材片段。");
        openFileDialog.Filter           = "所有文件|*.*";
        openFileDialog.RestoreDirectory = true;
        openFileDialog.FilterIndex      = 1;
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            clipName = openFileDialog.FileName;
        }
        else
        {
            return;
        }
        Media  media       = new Media(clipName);
        double mediaLength = media.Length.ToMilliseconds();

        // start configuration
        ConfigForm configForm = new ConfigForm();

        for (int i = 0; i < midi.Events.Tracks; i++)
        {
            configForm.comboBoxTrack.Items.Add(trackInfo[i]);
        }
        configForm.comboBoxTrack.SelectedIndex = 0;
        Application.Run(configForm);

        // apply configuration
        aconfig          = configForm.checkBoxA.Checked;
        aconfigNoTune    = configForm.checkBoxNoTune.Checked;
        vconfig          = configForm.checkBoxV.Checked;
        vconfigAutoFlip  = configForm.checkBoxFlip.Checked;
        vconfigStartSize = configForm.hScrollBar1.Value;
        vconfigEndSize   = configForm.hScrollBar2.Value;
        vconfigFadein    = configForm.hScrollBar4.Value;
        vconfigFadeout   = configForm.hScrollBar3.Value;
        aconfigBasePitch = pitchMap[configForm.comboBoxA1.SelectedItem.ToString() + configForm.comboBoxA2.SelectedItem.ToString()];
        for (int i = 0; i < midi.Events.Tracks; i++)
        {
            if (trackInfo[i] == configForm.comboBoxTrack.SelectedItem.ToString())
            {
                aconfigTrack = i;
            }
        }
        configStartTime = Convert.ToDouble(configForm.startT) * 1000;
        configEndTime   = Convert.ToDouble(configForm.endT) * 1000;

        // start processing MIDI
        VideoTrack vTrack = vegas.Project.AddVideoTrack();

        AudioTrack[] aTracks         = new AudioTrack[20];
        double       vTrackPosition  = 0;
        int          vTrackDirection = 1;

        double[] aTrackPositions = new double[20];
        aTracks[0]         = vegas.Project.AddAudioTrack();
        aTrackPositions[0] = 0;
        int aTrackCount = 1;

        foreach (MidiEvent midiEvent in midi.Events[aconfigTrack])
        {
            if (midiEvent is NoteOnEvent)
            {
                NoteEvent   noteEvent   = midiEvent as NoteEvent;
                NoteOnEvent noteOnEvent = midiEvent as NoteOnEvent;
                double      startTime   = midiEvent.AbsoluteTime * msPerQuarter / ticksPerQuarter;
                double      duration    = noteOnEvent.NoteLength * msPerQuarter / ticksPerQuarter;
                int         pitch       = noteEvent.NoteNumber;
                int         trackIndex  = 0;

                if (startTime < configStartTime)
                {
                    continue;
                }
                if (startTime > configEndTime)
                {
                    break;
                }

                // generate audio events
                if (aconfig == true)
                {
                    while (startTime < aTrackPositions[trackIndex])
                    {
                        trackIndex++;
                        if (trackIndex == aTrackCount)
                        {
                            aTrackCount++;
                            aTracks[trackIndex] = vegas.Project.AddAudioTrack();
                        }
                    }
                    AudioEvent audioEvent = aTracks[trackIndex].AddAudioEvent(Timecode.FromMilliseconds(startTime), Timecode.FromMilliseconds(duration));
                    Take       take       = audioEvent.AddTake(media.GetAudioStreamByIndex(0));
                    aTrackPositions[trackIndex] = startTime + duration;
                    TrackEvent trackEvent = audioEvent as TrackEvent;
                    trackEvent.PlaybackRate = mediaLength / duration;
                    trackEvent.Loop         = false;

                    // apply pitch shifting

                    if (aconfigNoTune == false)
                    {
                        int pitchDelta = pitch - aconfigBasePitch;
                        if (pitchDelta > 0)
                        {
                            while (pitchDelta > 12)
                            {
                                PlugInNode plugIn0 = vegas.AudioFX.FindChildByName("Pitch Shift");
                                Effect     effect0 = new Effect(plugIn0);
                                audioEvent.Effects.Add(effect0);
                                effect0.Preset = "12";
                                pitchDelta    -= 12;
                            }
                            PlugInNode plugIn = vegas.AudioFX.FindChildByName("Pitch Shift");
                            Effect     effect = new Effect(plugIn);
                            audioEvent.Effects.Add(effect);
                            effect.Preset = pitchDelta.ToString();
                        }
                        else
                        {
                            while (pitchDelta < -12)
                            {
                                PlugInNode plugIn0 = vegas.AudioFX.FindChildByName("Pitch Shift");
                                Effect     effect0 = new Effect(plugIn0);
                                audioEvent.Effects.Add(effect0);
                                effect0.Preset = "-12";
                                pitchDelta    += 12;
                            }
                            PlugInNode plugIn = vegas.AudioFX.FindChildByName("Pitch Shift");
                            Effect     effect = new Effect(plugIn);
                            audioEvent.Effects.Add(effect);
                            effect.Preset = pitchDelta.ToString();
                        }
                    }
                }

                // generate video events
                if (vconfig == true)
                {
                    vTrackPosition = startTime + duration;
                    VideoEvent videoEvent = vTrack.AddVideoEvent(Timecode.FromMilliseconds(startTime), Timecode.FromMilliseconds(duration));
                    Take       take       = videoEvent.AddTake(media.GetVideoStreamByIndex(0));
                    TrackEvent trackEvent = videoEvent as TrackEvent;
                    trackEvent.PlaybackRate = mediaLength / duration;
                    trackEvent.Loop         = false;

                    videoEvent.FadeIn.Length  = Timecode.FromMilliseconds(duration * vconfigFadein / 100);
                    videoEvent.FadeOut.Length = Timecode.FromMilliseconds(duration * vconfigFadeout / 100);

                    VideoMotionKeyframe key0 = videoEvent.VideoMotion.Keyframes[0];
                    VideoMotionKeyframe key1 = new VideoMotionKeyframe(Timecode.FromMilliseconds(duration));
                    videoEvent.VideoMotion.Keyframes.Add(key1);
                    key0.ScaleBy(new VideoMotionVertex((vconfigStartSize / 100) * vTrackDirection, (vconfigStartSize / 100)));
                    key1.ScaleBy(new VideoMotionVertex((vconfigEndSize / 100) * vTrackDirection, (vconfigEndSize / 100)));

                    if (vconfigAutoFlip == true)
                    {
                        vTrackDirection *= -1;
                    }
                }
            }
        }
    }