Пример #1
0
        private VideoEvent createText(Media media, VideoTrack track, TrackEvent eventBelow)
        {
            VideoEvent txtEvent = track.AddVideoEvent(eventBelow.Start, eventBelow.End - eventBelow.Start);
            Take       take     = txtEvent.AddTake(media.GetVideoStreamByIndex(0));

            return(txtEvent);
        }
Пример #2
0
        // 画像トラックの作り方
        // https://www.youtube.com/watch?v=GdrXo_HiNZM
        TrackEvent AddMedia(Project project, string mediaPath, int trackIndex, Timecode start, Timecode length)
        {
#if false
            Media media = Media.CreateInstance(project, mediaPath);
            Track track = project.Tracks[trackIndex];
            if (track.MediaType == MediaType.Video)
            {
                VideoTrack videoTrack = (VideoTrack)track;
                VideoEvent videoEvent = videoTrack.AddVideoEvent(start, length);
                Take       take       = videoEvent.AddTake(media.GetVideoStreamByIndex(0));
                return(videoEvent);
            }

            // サンプル:画像はこれで追加できる
            //AddMediaImage(vegas.Project, @"C:\Users\Administrator\Desktop\mouse.png", 0, );
            {
                Media media = Media.CreateInstance(vegas.Project, @"C:\Users\Administrator\Desktop\mouse.png");
                Track track = vegas.Project.Tracks[0];
                if (track.MediaType == MediaType.Video)
                {
                    VideoTrack videoTrack = (VideoTrack)track;
                    VideoEvent videoEvent = videoTrack.AddVideoEvent(Timecode.FromSeconds(1), Timecode.FromSeconds(5));
                    Take       take       = videoEvent.AddTake(media.GetVideoStreamByIndex(0));
                    return(videoEvent);
                }
            }
#endif
            return(null);
        }
Пример #3
0
//
// Adds a given media fileName to the current track at the specified cursorPosition
//
    void InsertFileAt(Vegas vegas, string fileName, Timecode cursorPosition)
    {
        VideoEvent videoEvent = null;

        Media      media      = new Media(fileName);
        VideoTrack videoTrack = FindSelectedVideoTrack(vegas.Project);

        videoEvent = videoTrack.AddVideoEvent(cursorPosition, Timecode.FromSeconds(stillLength));
        Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0));

        videoEvent.MaintainAspectRatio = false;

        VideoMotionKeyframe key1 = new VideoMotionKeyframe(Timecode.FromSeconds(stillLength));

        videoEvent.VideoMotion.Keyframes.Add(key1);
        VideoMotionKeyframe key0 = videoEvent.VideoMotion.Keyframes[0];

        key0.ScaleBy(new VideoMotionVertex(initialScale, initialScale));
        key0.RotateBy(initialRotationRadians * (double)rnd.Next(-1, 1));
        key0.MoveBy(new VideoMotionVertex((float)rnd.Next(-15, 15), (float)rnd.Next(-20, 20)));

        PlugInNode plugIn = vegas.Transitions.FindChildByName(desiredTransitions[rnd.Next(0, desiredTransitions.Length - 1)]);

        Effect fx = new Effect(plugIn);

        videoEvent.FadeIn.Transition = fx;
    }
Пример #4
0
//
// Adds a given media fileName to the current track at the specified cursorPosition
//
    void InsertFileAt(Vegas vegas, string fileName, Timecode cursorPosition)
    {
        PlugInNode plugIn = vegas.Transitions.FindChildByName("VEGAS Linear Wipe");

        VideoEvent videoEvent = null;

        Media      media      = new Media(fileName);
        VideoTrack videoTrack = FindSelectedVideoTrack(vegas.Project);

        videoEvent = videoTrack.AddVideoEvent(cursorPosition, Timecode.FromSeconds(stillLength));
        Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0));

        videoEvent.MaintainAspectRatio = false;

        VideoMotionKeyframe key1 = new VideoMotionKeyframe(Timecode.FromSeconds(stillLength));

        videoEvent.VideoMotion.Keyframes.Add(key1);
        VideoMotionKeyframe key0 = videoEvent.VideoMotion.Keyframes[0];

        key0.ScaleBy(new VideoMotionVertex(initialScale, initialScale));
        key0.RotateBy(initialRotationRadians);


        Effect fx = new Effect(plugIn);

        videoEvent.FadeIn.Transition = fx;
        fx.Preset = "Top-Down, Soft Edge";
    }
Пример #5
0
    // --------------------------------------------------------------------
    // パーツを連結
    // --------------------------------------------------------------------
    private void ConcatParts(List <VideoPart> oVideoParts, Double oAudioLen, Double oInterval)
    {
        // トラック作成
        VideoTrack aVideoTrack = new VideoTrack(mVegas.Project, 0, TRACK_NAME);

        mVegas.Project.Tracks.Add(aVideoTrack);

        // パーツ使用数
        Int32        aUseNum = (Int32)Math.Ceiling(oAudioLen / oInterval);
        PartsUseMode aPartsUseMode;

        if (oVideoParts.Count >= aUseNum * 3)
        {
            aPartsUseMode = PartsUseMode.OnceGroup;
        }
        else if (oVideoParts.Count >= aUseNum)
        {
            aPartsUseMode = PartsUseMode.Once;
        }
        else
        {
            aPartsUseMode = PartsUseMode.Reuse;
        }

        // パーツ追加
        Random aRandom = new Random();

        for (Int32 i = 0; i < aUseNum; i++)
        {
            // パーツ番号
            Int32 aPartsIndex = aRandom.Next(0, oVideoParts.Count);

            // パーツ
            VideoEvent aVideoEvent = aVideoTrack.AddVideoEvent(new Timecode(i * oInterval), new Timecode(oInterval));
            Take       aTake       = aVideoEvent.AddTake(oVideoParts[aPartsIndex].VideoStream);
            aTake.Offset = oVideoParts[aPartsIndex].Offset;

            // パーツ廃棄
            switch (aPartsUseMode)
            {
            case PartsUseMode.Once:
                oVideoParts.RemoveAt(aPartsIndex);
                break;

            case PartsUseMode.OnceGroup:
                for (Int32 j = aPartsIndex + 1; j >= aPartsIndex - 1; j--)
                {
                    if (0 <= j && j < oVideoParts.Count)
                    {
                        oVideoParts.RemoveAt(j);
                    }
                }
                break;
            }
        }
    }
        // Adds media event to track at specified start
        TrackEvent AddMedia(Project project, string mediaPath, int trackIndex, Timecode start, Timecode length)
        {
            Media      media             = Media.CreateInstance(project, mediaPath);
            Track      track             = project.Tracks[trackIndex];
            TrackEvent currentTrackEvent = null;

            if (track.MediaType == MediaType.Video)
            {
                // If cursor isn't over an event on the track, simply add it to track
                if ((currentTrackEvent = FindTrack(project, start, trackIndex)) is null)
                {
                    ;
                }
                // If cursor is over an event on the track, remove the portion of that event from where
                // the cursor is to where the next event starts
                else
                {
                    // When an event is split, the left half is the original event, the right split is a new event
                    TrackEvent rightSplit = currentTrackEvent.Split(start - currentTrackEvent.Start); // offset from start
                    // rightSplit is null when you try the split right where a track begins, this if
                    // statement handles that
                    if (rightSplit is null)
                    {
                        length = currentTrackEvent.Length;
                        track.Events.Remove(currentTrackEvent);
                    }
                    else
                    {
                        length = rightSplit.Length; // set new length so new video track will fill in old tracks place
                        track.Events.Remove(rightSplit);
                    }
                }
                VideoTrack videoTrack = (VideoTrack)track;
                VideoEvent videoEvent = videoTrack.AddVideoEvent(start, length);
                Take       take       = videoEvent.AddTake(media.GetVideoStreamByIndex(0));
                return(videoEvent);
            }
            else
            {
                return(null);
            }
        }
        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();
        }
Пример #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);
            }
        }
        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);
            }
        }
Пример #10
0
        private void importCallback(object sender, EventArgs e)
        {
            LogWriter.LogWrite("Callback");

            var importOptions = e as ImportEventArgs;

            using (var undo = new UndoBlock(moduleName))
            {
                try
                {
                    var frameOffsetInMs = (1000 / vegas.Project.Video.FrameRate) * importOptions.FrameOffset;

                    var beatLengthInS = 60 / selectedFlp.Tempo;
                    var ppqLengthInS  = beatLengthInS / selectedFlp.Ppq;


                    PlugInNode solidColor = vegas.Generators.GetChildByUniqueID("{Svfx:com.sonycreativesoftware:solidcolor}");

                    vegas.Project.Markers.Clear();

                    List <List <FullTrackTimes> > fullTrackTimesList = new List <List <FullTrackTimes> >();

                    foreach (int i in importOptions.SelectedIndices)
                    {
                        List <FullTrackTimes> fullTrackTimes = new List <FullTrackTimes>();

                        foreach (var j in selectedFlp.Tracks[i].Items)
                        {
                            if (j is PatternPlaylistItem)
                            {
                                var patternItem = j as PatternPlaylistItem;

                                foreach (Channel channel in patternItem.Pattern.Notes.Keys)
                                {
                                    foreach (Note note in patternItem.Pattern.Notes[channel])
                                    {
                                        if (note.Position < patternItem.StartOffset)
                                        {
                                            continue;
                                        }
                                        if (note.Position > patternItem.Length)
                                        {
                                            continue;
                                        }

                                        var noteStartPpq = patternItem.Position + (note.Position - patternItem.StartOffset);
                                        var startInMs    = noteStartPpq * ppqLengthInS * 1000;

                                        var noteEndInMs = note.Length * ppqLengthInS * 1000;

                                        startInMs =
                                            (frameOffsetInMs + startInMs < 0) ?
                                            (int)(frameOffsetInMs + startInMs) :
                                            (int)startInMs;

                                        noteEndInMs =
                                            (frameOffsetInMs + noteEndInMs < 0) ?
                                            (int)(frameOffsetInMs + noteEndInMs) :
                                            (int)noteEndInMs;

                                        fullTrackTimes.Add(new FullTrackTimes(startInMs, noteEndInMs));
                                    }
                                }
                            }
                            //if(j is ChannelPlaylistItem)
                            //{
                            //    var channelItem = j as ChannelPlaylistItem;

                            //    if(channelItem.Channel.Data is GeneratorData)
                            //    {
                            //        var audioStartPpq = channelItem.Position;
                            //        var startInMs = audioStartPpq * ppqLengthInS * 1000;

                            //        var audioEndPpq = audioStartPpq + channelItem.Length;
                            //        var noteEndInMs = audioEndPpq * ppqLengthInS * 1000;

                            //        fullTrackTimes.Add();
                            //    }
                            //}
                        }

                        fullTrackTimesList.Add(fullTrackTimes);
                    }
                    foreach (var trackTimes in fullTrackTimesList)
                    {
                        if (importOptions.ImportType == "Solid color")
                        {
                            Media      solidColorMedia = Media.CreateInstance(vegas.Project, solidColor);
                            VideoTrack v = vegas.Project.AddVideoTrack();

                            foreach (var fullTrackTimes in trackTimes)
                            {
                                if (importOptions.ImportType == "Solid color")
                                {
                                    VideoEvent ve = v.AddVideoEvent(new Timecode(fullTrackTimes.start), new Timecode(fullTrackTimes.end));
                                    //ve.
                                    ve.AddTake(solidColorMedia.Streams[0]);
                                }
                            }
                        }
                        else if (importOptions.ImportType == "Marker")
                        {
                            foreach (var fullTrackTimes in trackTimes)
                            {
                                if (importOptions.ImportType == "Marker")
                                {
                                    vegas.Project.Markers.Add(new Marker(new Timecode(fullTrackTimes.start)));
                                }
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    LogWriter.LogWrite(err.ToString());
                    throw err;
                }
            }
        }
Пример #11
0
        public void FromVegas(Vegas vegas)
        {
            var start  = vegas.Transport.LoopRegionStart;
            var length = vegas.Transport.LoopRegionLength;

            if (start.FrameCount == 0)
            {
                MessageBox.Show("Selection must start at frame >= 1!");
                return;
            }
            if (length.FrameCount <= 1)
            {
                MessageBox.Show("Selection length must be > 1 frame!");
                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 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;
                }

                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;
                    }
                }

                if (videoTrack == null)
                {
                    MessageBox.Show("No track 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 pathSrc = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                           Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi");
                var pathEncodedSrc = Path.Combine(vegas.TemporaryFilesPath,
                                                  Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                                  Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi");
                Encode(vegas, scriptDirectory, new RenderArgs {
                    OutputFile     = pathSrc,
                    Start          = Timecode.FromFrames(start.FrameCount - 1),
                    Length         = Timecode.FromFrames(1),
                    RenderTemplate = template
                }, pathEncodedSrc);

                var pathClip = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                            Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi");
                var pathEncodedClip = Path.Combine(vegas.TemporaryFilesPath,
                                                   Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" +
                                                   Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi");
                Encode(vegas, scriptDirectory, new RenderArgs {
                    OutputFile     = pathClip,
                    Start          = start,
                    Length         = length,
                    RenderTemplate = template
                }, pathEncodedClip);

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

                string[] datamoshConfig =
                {
                    "var input0=\"" + pathEncodedSrc.Replace("\\",  "/") + "\";",
                    "var input1=\"" + pathEncodedClip.Replace("\\", "/") + "\";",
                    "var output=\"" + pathDatamixed.Replace("\\",   "/") + "\";"
                };

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

                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_datamix.js",
                        RedirectStandardInput  = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        CreateNoWindow         = true
                    }
                };
                datamosh.Start();
                datamosh.StandardInput.WriteLine("n");
                var output = datamosh.StandardOutput.ReadToEnd();
                var error  = datamosh.StandardError.ReadToEnd();
                Debug.WriteLine(output);
                Debug.WriteLine("---------------------");
                Debug.WriteLine(error);
                datamosh.WaitForExit();

                File.Delete(pathEncodedSrc);
                File.Delete(pathEncodedSrc + ".sfl");
                File.Delete(pathEncodedClip);
                File.Delete(pathEncodedClip + ".sfl");

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

                var videoEvent = videoTrack.AddVideoEvent(start, Timecode.FromFrames(length.FrameCount - 1));
                videoEvent.AddTake(media.GetVideoStreamByIndex(0));
            }
            catch (Exception e) {
                MessageBox.Show("Unexpected exception: " + e.Message);
                Debug.WriteLine(e);
            }
        }
Пример #12
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));
    }
Пример #13
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);
            }
        }
    public void FromVegas(Vegas vegas)
    {
        myVegas = vegas;

        System.Collections.Generic.List <OFXDouble2DKeyframe> locations = new System.Collections.Generic.List <OFXDouble2DKeyframe>();
        Tuple <Timecode, Timecode> durationTrackEvent;

        VideoEvent trackEvent = (VideoEvent)FindFirstSelectedEventUnderCursor();

        if (trackEvent == null)
        {
            MessageBox.Show("Please select the video event on which VEGAS Bezier Masking has been applied.", "No selected event", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        else
        {
            durationTrackEvent = new Tuple <Timecode, Timecode>(trackEvent.Start, trackEvent.End);
            Effects fxs            = trackEvent.Effects;
            bool    bezierWasFound = false;
            foreach (Effect fx in fxs)
            {
                bezierWasFound = fx.PlugIn.UniqueID == "{Svfx:com.sonycreativesoftware:bzmasking}";
                if (bezierWasFound)
                {
                    OFXParameters parameter = fx.OFXEffect.Parameters;
                    foreach (OFXParameter param in parameter)
                    {
                        if (param.Name == "Location_0")
                        {
                            OFXDouble2DParameter locationTracking = (OFXDouble2DParameter)param;
                            locations = new List <OFXDouble2DKeyframe>(locationTracking.Keyframes);
                            break;
                        }
                    }

                    break;
                }
            }
            if (!bezierWasFound)
            {
                MessageBox.Show("Please apply VEGAS Bezier Masking to the video event", "VEGAS Bezier Masking not applied", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        if (locations.Count == 0)
        {
            MessageBox.Show("Please add Motion Tracking to the VEGAS Bezier Masking FX", "No tracking data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        else
        {
            using (OffsetDialog offsetPrompt = new OffsetDialog())
            {
                DialogResult result = offsetPrompt.ShowDialog();
                if (result == DialogResult.OK)
                {
                    VideoTrack titleTrack    = myVegas.Project.AddVideoTrack();
                    PlugInNode textAndTitles = myVegas.Generators.GetChildByUniqueID("{Svfx:com.sonycreativesoftware:titlesandtext}"); // GetChildByName("VEGAS Titles & Text");//
                    Timecode   lengthEvent   = durationTrackEvent.Item2 - durationTrackEvent.Item1;
                    Media      media         = new Media(textAndTitles, "Placeholder");
                    media.Length = lengthEvent;
                    VideoEvent vEvent = titleTrack.AddVideoEvent(durationTrackEvent.Item1, lengthEvent);
                    Take       take   = new Take(media.Streams[0]);
                    vEvent.Takes.Add(take);

                    Effect        fxText    = media.Generator;
                    OFXParameters parameter = fxText.OFXEffect.Parameters;
                    foreach (OFXParameter param in parameter)
                    {
                        if (param.Name == "Location")
                        {
                            OFXDouble2DParameter locationText = (OFXDouble2DParameter)param;
                            locationText.Keyframes.Clear();
                            foreach (OFXDouble2DKeyframe location in locations)
                            {
                                OFXDouble2D tmpValue = location.Value;
                                tmpValue.X += offsetPrompt.X;
                                tmpValue.Y += offsetPrompt.Y;
                                locationText.SetValueAtTime(location.Time, tmpValue);
                            }

                            break;
                        }
                    }
                }
            }
        }
    }
Пример #15
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;
                    }
                }
            }
        }
    }
Пример #16
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);
            }
        }