예제 #1
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;
    }
예제 #2
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";
    }
    void MatchOutputAspect(VideoMotionKeyframe keyframe, double dMediaPixelAspect, double dAspectOut)
    {
        VideoMotionKeyframe keyframeSave = keyframe;

        try
        {
            double rotation = keyframe.Rotation;

            // undo rotation so that we can get at correct aspect ratio.
            //
            keyframe.RotateBy(-rotation);

            double dWidth         = Math.Abs(keyframe.TopRight.X - keyframe.TopLeft.X);
            double dHeight        = Math.Abs(keyframe.BottomLeft.Y - keyframe.TopLeft.Y);
            double dCurrentAspect = dMediaPixelAspect * dWidth / dHeight;
            double centerY        = keyframe.Center.Y;
            double centerX        = keyframe.Center.X;

            double dFactor;

            VideoMotionBounds bounds = new VideoMotionBounds(keyframe.TopLeft, keyframe.TopRight, keyframe.BottomRight, keyframe.BottomLeft);

            if (dCurrentAspect < dAspectOut)
            {
                // alter y coords
                dFactor = dCurrentAspect / dAspectOut;

                bounds.TopLeft.Y     = (float)((bounds.TopLeft.Y - centerY) * dFactor + centerY);
                bounds.TopRight.Y    = (float)((bounds.TopRight.Y - centerY) * dFactor + centerY);
                bounds.BottomLeft.Y  = (float)((bounds.BottomLeft.Y - centerY) * dFactor + centerY);
                bounds.BottomRight.Y = (float)((bounds.BottomRight.Y - centerY) * dFactor + centerY);
            }
            else
            {
                // alter x coords
                dFactor = dAspectOut / dCurrentAspect;

                bounds.TopLeft.X     = (float)((bounds.TopLeft.X - centerX) * dFactor + centerX);
                bounds.TopRight.X    = (float)((bounds.TopRight.X - centerX) * dFactor + centerX);
                bounds.BottomLeft.X  = (float)((bounds.BottomLeft.X - centerX) * dFactor + centerX);
                bounds.BottomRight.X = (float)((bounds.BottomRight.X - centerX) * dFactor + centerX);
            }

            // set it to new bounds
            keyframe.Bounds = bounds;

            // restore rotation.
            keyframe.RotateBy(rotation);
        }
        catch (Exception e)
        {
            // restore original settings on error
            keyframe = keyframeSave;
        }
    }
 public static void PanFromCenterToLeft(Vegas vegas, VideoEvent videoEvent)
 {
     using (UndoBlock undo = new UndoBlock("Add pan/crop"))
     {
         VideoMotionKeyframe key0 = videoEvent.VideoMotion.Keyframes[0];
         int videoWidth           = vegas.Project.Video.Width;
         VideoMotionKeyframe key1 = new VideoMotionKeyframe(Timecode.FromMilliseconds(Config.splitOffset));
         videoEvent.VideoMotion.Keyframes.Add(key1);
         key1.MoveBy(new VideoMotionVertex(videoWidth, 0));
     }
 }
예제 #5
0
    void ExportVideoMotionKeyframe(XmlElement parent, VideoMotionKeyframe keyframe)
    {
        XmlElement elt = AddChild(parent, "VideoMotionKeyframe");

        ChildObject(elt, "Type", keyframe.Type);
        ChildTimecode(elt, "Position", keyframe.Position);
        ChildSingle(elt, "Smoothness", keyframe.Smoothness);
        ChildDouble(elt, "Rotation", keyframe.Rotation);
        ExportVideoMotionBounds(elt, keyframe.Bounds, "Bounds");
        ExportVideoMotionVertex(elt, keyframe.Center, "Center");
    }
예제 #6
0
    void ImportVideoMotionKeyframe(XmlElement parent, VideoMotionKeyframes keyframes)
    {
        Timecode            position = ChildTimecode(parent, "Position");
        VideoMotionKeyframe keyframe;

        if (position.Nanos == 0)
        {
            keyframe = (VideoMotionKeyframe)keyframes[0];
        }
        else
        {
            keyframe = new VideoMotionKeyframe(position);
            keyframes.Add(keyframe);
        }
        try { keyframe.Type = ChildVideoKeyframeType(parent, "Type"); } catch {}
        try { keyframe.Smoothness = ChildSingle(parent, "Smoothness"); } catch {}
        try { keyframe.Center = ChildVideoMotionVertex(parent, "Center"); } catch {}
        try { keyframe.Rotation = ChildDouble(parent, "Rotation"); } catch {}
        keyframe.Bounds = ChildVideoMotionBounds(parent, "Bounds");
    }
    public class EntryPoint {   //The usual stuff for a Vegas script, I'll explain it later (no)
        public void FromVegas(Vegas myVegas)
        {
            PlugInNode pipeffect = myVegas.VideoFX.GetChildByName("VEGAS Picture In Picture"); //Getting the PiP effetc

            if (pipeffect == null)                                                             //if the effect doesn't exists we exit the script with an error message
            {
                MessageBox.Show("You don't have the VEGAS Picture In Picture effect. \n Please install it and try again!");
                return;
            }
            List <VideoEvent> videvents = new List <VideoEvent>();         //A list for the selected events

            foreach (Track myTrack in myVegas.Project.Tracks)              //going through every track and every event, adding the selected video events to the list
            {
                foreach (TrackEvent myEvent in myTrack.Events)
                {
                    if ((myEvent.MediaType == MediaType.Video) && (myEvent.Selected == true))
                    {
                        videvents.Add((VideoEvent)myEvent);
                    }
                }
            }
            double            proWidth  = myVegas.Project.Video.Width;                           //the project's width
            double            proHeight = myVegas.Project.Video.Height;                          //the project's height
            VideoMotionBounds newBound;                                                          //variable for the crop's size
            VideoMotionBounds newerBound;                                                        //variable for crop size if the first one doesn't fit the whole picture

            foreach (VideoEvent pipevent in videvents)                                           // for each video event in the list
            {
                Take                piptake   = pipevent.ActiveTake;                             //getting the width and height of the event's source
                VideoStream         pipstream = piptake.MediaStream as VideoStream;
                int                 myWidth   = pipstream.Width;                                 //the event's width
                int                 myHeight  = pipstream.Height;                                //the event"s height
                double              proAspect = myWidth / (myHeight * (proWidth / proHeight));   //calculating the correct number to multiply later the width/height later
                VideoMotionKeyframe reframe   = new VideoMotionKeyframe(Timecode.FromFrames(0)); //creating a new Pan/Crop keyframe at the beginning of the event
                pipevent.VideoMotion.Keyframes.Add(reframe);
                if (myWidth > myHeight)                                                          //calculating the size of the pan/crop keyframe with the help of the previously calculated value (proAspect) (EXTREMLY COMPLEX AND DANGEROUS, handle with care)
                {
                    newBound = new VideoMotionBounds(new VideoMotionVertex((float)(reframe.Center.X - (double)(myWidth / 2)), (float)(reframe.Center.Y - (double)(myHeight / 2) * proAspect)), new VideoMotionVertex((float)(reframe.Center.X + (double)(myWidth / 2)), (float)(reframe.Center.Y - (double)(myHeight / 2) * proAspect)), new VideoMotionVertex((float)(reframe.Center.X + (double)(myWidth / 2)), (float)(reframe.Center.Y + (double)(myHeight / 2) * proAspect)), new VideoMotionVertex((float)(reframe.Center.X - (double)(myWidth / 2)), (float)(reframe.Center.Y + (double)(myHeight / 2) * proAspect)));
                    if (Math.Abs(newBound.TopLeft.Y - newBound.BottomLeft.Y) < myHeight)                   //if the crop is the correct aspect ration, but it still cuts out part of the image, this code will run and make a cropize, which covers the whole picture with the correct ratio (MORE MATH)
                    {
                        float multiply = myHeight / Math.Abs(newBound.TopLeft.Y - newBound.BottomLeft.Y);
                        float actWidth = Math.Abs(newBound.TopRight.X - newBound.TopLeft.X) / 2;
                        float toHeight = myHeight / 2;
                        newerBound = new VideoMotionBounds(new VideoMotionVertex(reframe.Center.X - actWidth * multiply, reframe.Center.Y - toHeight), new VideoMotionVertex(reframe.Center.X + actWidth * multiply, reframe.Center.Y - toHeight), new VideoMotionVertex(reframe.Center.X + actWidth * multiply, reframe.Center.Y + toHeight), new VideoMotionVertex(reframe.Center.X - actWidth * multiply, reframe.Center.Y + toHeight));
                        newBound   = newerBound;
                    }
                }
                else                 //almost same as above, casual math
                {
                    newBound = new VideoMotionBounds(new VideoMotionVertex((float)(reframe.Center.X - (double)(myWidth / 2) / proAspect), (float)(reframe.Center.Y - (double)(myHeight / 2))), new VideoMotionVertex((float)(reframe.Center.X + (double)(myWidth / 2) / proAspect), (float)(reframe.Center.Y - (double)(myHeight / 2))), new VideoMotionVertex((float)(reframe.Center.X + (double)(myWidth / 2) / proAspect), (float)(reframe.Center.Y + (double)(myHeight / 2))), new VideoMotionVertex((float)(reframe.Center.X - (double)(myWidth / 2) / proAspect), (float)(reframe.Center.Y + (double)(myHeight / 2))));
                    if (Math.Abs(newBound.TopRight.X - newBound.TopLeft.X) < myWidth)
                    {
                        float multiply  = myHeight / Math.Abs(newBound.TopRight.X - newBound.TopLeft.X);
                        float toWidth   = myWidth / 2;
                        float actHeight = Math.Abs(newBound.TopLeft.Y - newBound.BottomLeft.Y / 2);
                        newerBound = new VideoMotionBounds(new VideoMotionVertex(reframe.Center.X - toWidth, reframe.Center.Y - actHeight * multiply), new VideoMotionVertex(reframe.Center.X + toWidth, reframe.Center.Y - actHeight * multiply), new VideoMotionVertex(reframe.Center.X + toWidth, reframe.Center.Y + actHeight * multiply), new VideoMotionVertex(reframe.Center.X - toWidth, reframe.Center.Y + actHeight * multiply));
                        newBound   = newerBound;
                    }
                }
                reframe.Bounds = newBound;                //setting the keyframe's size
                pipevent.Effects.AddEffect(pipeffect);    //adding the PiP effect to the event
            }
        }
        private void buttonOk_Click(object sender, EventArgs e)
        {
            foreach (Track Track in MyVegas.Project.Tracks)
            {
                if (Track.IsAudio())
                    continue;

                foreach (VideoEvent Event in Track.Events)
                {
                    if (Event.Selected)
                    {
                        VideoMotionKeyframes kf = Event.VideoMotion.Keyframes; Event.VideoMotion.ScaleToFill = true;
                        Random r = new Random();
                        long count = Event.Length.FrameCount;
                        long d = (long) numericUpDownFrames.Value;
                        long iterations = count / d;

                        kf.Clear();
                        kf[0].Position = new Timecode();

                        for (int i = 1; i < iterations; i++)
                        {
                            VideoMotionKeyframe k = new VideoMotionKeyframe(Timecode.FromFrames(i * d));
                            kf.Add(k);
                        }

                        for (int i = 0; i < iterations; i++)
                        {
                            if (checkBoxVar.Checked)
                                Inicial.RandomizeRelative(kf[i], r, i / (float) iterations, Final);
                            else
                                Inicial.Randomize(kf[i], r);
                        }

                        Close();
                        return;
                    }
                }
                MessageBox.Show("Nenhum evento de vídeo foi selecionado");
                Close();
            }
        }
 public void RandomizeRelative(VideoMotionKeyframe k, Random r, float step, WigglerKeyFrame f)
 {
     WigglerKeyFrame tmp = Lerp(step, f);
     tmp.Randomize(k, r);
 }
        public void Randomize(VideoMotionKeyframe k, Random r)
        {
            k.MoveBy(new VideoMotionVertex(RandomHelper(r, _MinX, _MaxX), RandomHelper(r, _MinY, _MaxY)));

            float d = RandomHelper(r, _MinScale, _MaxScale);
            k.ScaleBy(new VideoMotionVertex(d, d));

            k.RotateBy(Math.PI * RandomHelper(r, _MinRotation, _MaxRotation) / 180d);
        }
예제 #11
0
 public void ResetKeyframeCenter(VideoMotionKeyframe k)
 {
     k.MoveBy(new VideoMotionVertex(MyVegas.Project.Video.Width / 2 - k.Center.X, MyVegas.Project.Video.Height / 2 - k.Center.Y));
 }
예제 #12
0
    public void FromVegas(Vegas vegas)
    {
        Project currProject = vegas.Project;
        Int32   videoWidth  = currProject.Video.Width;
        Int32   videoHeight = currProject.Video.Height;

        TrackEvent[] tes = FindSelectedEvents(currProject);
        VideoEvent[] ves = GetVideoEvents(tes);

        if (ves.Length != 1)
        {
            MessageBox.Show("You have to select exactly 1 video events in order for this script to work.\nThe events must contain the \"" + MOTION_TRACKING_FX_NAME + "\" effect with at least one mask enabled. You then zoom in, using pan and crop options. Then after clicking on this script, the pan and crop option will be reset and the point moved, so that it stays on the pixel you selected.\n\nTerminating...", "Wrong selection", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        // foreach (VideoEvent ev in ves)
        // {
        //     foreach (Effect ef in ev.Effects)
        //     {
        //         MessageBox.Show(ef.Description);
        //     }
        // }

        VideoEvent ve = GetEventContainingEffect(ves, MOTION_TRACKING_FX_NAME);

        if (ve == null)
        {
            MessageBox.Show("No selected event with the \"" + MOTION_TRACKING_FX_NAME + "\" plugin found which holds the motion tracking data!\n\nTerminating...", "Wrong selection", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        OFXEffect fx = GetOFXFromEvent(ve, MOTION_TRACKING_FX_NAME);

        if (fx == null)
        {
            MessageBox.Show("Can't seem to grab the \"" + MOTION_TRACKING_FX_NAME + "\" effect!\n\nTerminating...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            return;
        }

        PopulateMaskBitmask(fx);

        // show_fx_parameters(fx);

        int mask_to_use = PromptForMaskNumber();

        if (mask_to_use == -1)
        {
            return;
        }

        Timecode cursorTime = null;

        Double motionStart = ve.Start.ToMilliseconds();
        Double motionEnd   = ve.End.ToMilliseconds();

        Double cursorStart = vegas.Transport.CursorPosition.ToMilliseconds();

        Double max = Math.Max(motionStart, cursorStart);
        Double min = Math.Min(motionEnd, cursorStart);

        if (max != cursorStart || min != cursorStart)
        {
            MessageBox.Show("The cursor must be placed within the event borders!\n\nTerminating...", "Invalid cursor position", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        cursorTime = new Timecode(cursorStart);

        OFXDouble2DParameter motionParam = fx.FindParameterByName("Location_" + mask_to_use.ToString()) as OFXDouble2DParameter;

        if (cursorTime == null)
        {
            MessageBox.Show("Something went wrong as the script tried to determine the cursor position...\n\nTerminating...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            return;
        }

        VideoMotion vevm = ve.VideoMotion;

        VideoMotionKeyframe currKeyframe = new VideoMotionKeyframe(currProject, (cursorTime - ve.Start));

        vevm.Keyframes.Add(currKeyframe);

        Single cutoutWidth  = currKeyframe.TopRight.X - currKeyframe.TopLeft.X;
        Single cutoutHeight = currKeyframe.BottomLeft.Y - currKeyframe.TopLeft.Y;
        Single originX      = currKeyframe.TopLeft.X;
        Single originY      = currKeyframe.BottomLeft.Y;

        OFXDouble2D cursorValue = motionParam.GetValueAtTime(cursorTime - ve.Start);

        Double newCoordX = originX + (cutoutWidth * cursorValue.X);
        Double newCoordY = originY - (cutoutHeight * cursorValue.Y);

        cursorValue.X = newCoordX / videoWidth;
        cursorValue.Y = 1 - (newCoordY / videoHeight);
        motionParam.SetValueAtTime((cursorTime - ve.Start), cursorValue);

        DialogResult dialogResult = MessageBox.Show("If you choose to also adapt the mask scale, this would mean that the mask will be shrunk together with the video frame.\nIf you have zoomed in alot, it sometimes makes sense to not do this as the control handles would get so small that you can't grab them.\nIf you choose to also adjust the size, you can also later on change the width/height from the mask settings.\n\nWould you like to also adapt the mask scale?", "Also adjust mask scale?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        if (dialogResult == DialogResult.Yes)
        {
            OFXDoubleParameter widthParam     = fx.FindParameterByName("Width_" + mask_to_use.ToString()) as OFXDoubleParameter;
            OFXDoubleParameter heightParam    = fx.FindParameterByName("Height_" + mask_to_use.ToString()) as OFXDoubleParameter;
            Double             maskWidth      = widthParam.GetValueAtTime(cursorTime - ve.Start);
            Double             maskHeight     = heightParam.GetValueAtTime(cursorTime - ve.Start);
            Double             widthRelation  = videoWidth / cutoutWidth;
            Double             heightRelation = videoHeight / cutoutHeight;

            widthParam.SetValueAtTime((cursorTime - ve.Start), (maskWidth / widthRelation));
            heightParam.SetValueAtTime((cursorTime - ve.Start), (maskHeight / heightRelation));
        }

        VideoMotionBounds restoreBounds = new VideoMotionBounds(
            new VideoMotionVertex(0, 0),
            new VideoMotionVertex(videoWidth, 0),
            new VideoMotionVertex(videoWidth, videoHeight),
            new VideoMotionVertex(0, videoHeight)
            );

        currKeyframe.Bounds = restoreBounds;
        currKeyframe.Center = new VideoMotionVertex((videoWidth / 2), (videoHeight / 2));

        MessageBox.Show("Please select a different effect, or move the cursor to a differen event, in order to update the control handles of the mask", "Refresh control handles", MessageBoxButtons.OK, MessageBoxIcon.Information);

        fx.AllParametersChanged();
    }
예제 #13
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;
                    }
                }
            }
        }
    }
예제 #14
0
    public void FromVegas(Vegas vegas)
    {
        Project currProject = vegas.Project;
        Int32   videoWidth  = currProject.Video.Width;
        Int32   videoHeight = currProject.Video.Height;

        TrackEvent[] tes = FindSelectedEvents(currProject);
        VideoEvent[] ves = GetVideoEvents(tes);

        if (ves.Length != 2)
        {
            MessageBox.Show("You have to select exactly 2 video events (in no particular order) in order for this script to work.\nOne of the events must contain the \"" + MOTION_TRACKING_FX_NAME + "\" effect with at least one mask enabled and populated with motion tracking data, the second event is the target event, where the pan and crop center will be populated with the motion track data. Then after clicking on this script you can select the mask to use. The script will copy the location values of the mask to the location values of the pan and crop setting (beginning from the cursor position till the end of the motion tracked clip, or within the selection range).\n\nTerminating...", "Not enough selections", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        // foreach (VideoEvent ev in ves)
        // {
        //     foreach (Effect ef in ev.Effects)
        //     {
        //         MessageBox.Show(ef.Description);
        //     }
        // }

        VideoEvent ve = GetEventContainingEffect(ves, MOTION_TRACKING_FX_NAME);

        if (ve == null)
        {
            MessageBox.Show("No selected event with the \"" + MOTION_TRACKING_FX_NAME + "\" plugin found which holds the motion tracking data!\n\nTerminating...", "Not enough selections", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        OFXEffect fx = GetOFXFromEvent(ve, MOTION_TRACKING_FX_NAME);

        if (fx == null)
        {
            MessageBox.Show("Can't seem to grab the \"" + MOTION_TRACKING_FX_NAME + "\" effect!\n\nTerminating...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            return;
        }

        PopulateMaskBitmask(fx);

        // show_fx_parameters(fx);

        int mask_to_use = PromptForMaskNumber();

        if (mask_to_use == -1)
        {
            return;
        }

        VideoEvent ve2 = GetEventDifferentFrom(ves, ve);

        if (ve2 == null)
        {
            MessageBox.Show("No selected event different from the motion capture event found, which is the target for the motion tracking data!\n\nTerminating...", "Not enough selections", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        Timecode startingTime = null;
        Timecode endingTime   = null;

        DialogResult dialogResult = MessageBox.Show("You have two methods to copy the keyframes:\nOne option is to copy from the current cursor position onwards, till the script runs into the ending of one of the events (yes).\nThe other option is to use the current selection. Note however that this produces unexpected behaviour, if no selection is currently active! (no).\n\nCopy from the cursor onwards?", "Processing Method", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

        if (dialogResult == DialogResult.Cancel)
        {
            return;
        }
        else
        {
            Double motionStart = ve.Start.ToMilliseconds();
            Double motionEnd   = ve.End.ToMilliseconds();

            Double cornerStart = ve2.Start.ToMilliseconds();
            Double cornerEnd   = ve2.End.ToMilliseconds();

            if (dialogResult == DialogResult.Yes)
            {
                Double cursorStart = vegas.Transport.CursorPosition.ToMilliseconds();

                Double max = Math.Max(motionStart, Math.Max(cornerStart, cursorStart));
                Double min = Math.Min(motionEnd, Math.Min(cornerEnd, cursorStart));

                if (max != cursorStart || min != cursorStart)
                {
                    MessageBox.Show("The cursor must be placed at a position where it covers both selected events!\n\nTerminating...", "Invalid cursor position", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                startingTime = new Timecode(cursorStart);
                endingTime   = new Timecode(Math.Min(motionEnd, cornerEnd));
            }
            else if (dialogResult == DialogResult.No)
            {
                Double selectionStart = vegas.Transport.SelectionStart.ToMilliseconds();
                Double selectionEnd   = selectionStart + vegas.Transport.SelectionLength.ToMilliseconds();

                Double max = Math.Max(motionStart, Math.Max(cornerStart, selectionStart));
                Double min = Math.Min(motionEnd, Math.Min(cornerEnd, selectionEnd));

                if (max != selectionStart || min != selectionEnd)
                {
                    MessageBox.Show("The selection must be placed in a range where it covers both selected events!\n\nTerminating...", "Invalid selection", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                startingTime = new Timecode(selectionStart);
                endingTime   = new Timecode(selectionEnd);
            }
        }

        // MessageBox.Show("Current time: " + fx2.CurrentTime.ToString() + "\nCursor pos: " + vegas.Transport.CursorPosition.ToString() + "\nCalculated current time: " + (fx2.CurrentTime + ve2.Start).ToString());

        OFXDouble2DParameter motionParam = fx.FindParameterByName("Location_" + mask_to_use.ToString()) as OFXDouble2DParameter;

        if (startingTime == null || endingTime == null)
        {
            MessageBox.Show("Something went wrong as the script tried to use the method you decided...\n\nTerminating...", "Not enough selections", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            return;
        }

        double deltaX         = 0;
        double deltaY         = 0;
        double lastX          = 0;
        double lastY          = 0;
        bool   deltaPopulated = false;

        VideoMotion ve2vm = ve2.VideoMotion;

        VideoMotionKeyframe prevKeyframe = new VideoMotionKeyframe(currProject, (startingTime - ve2.Start));

        ve2vm.Keyframes.Add(prevKeyframe);

        foreach (OFXDouble2DKeyframe motionKeyframe in motionParam.Keyframes)
        {
            Timecode keyframeTime = motionKeyframe.Time + ve.Start;

            if (startingTime <= keyframeTime && keyframeTime <= endingTime)
            {
                if (!deltaPopulated)
                {
                    lastX = motionKeyframe.Value.X;
                    lastY = motionKeyframe.Value.Y;

                    deltaPopulated = true;
                }
                else
                {
                    deltaX = motionKeyframe.Value.X - lastX;
                    deltaY = motionKeyframe.Value.Y - lastY;

                    lastX = motionKeyframe.Value.X;
                    lastY = motionKeyframe.Value.Y;

                    // TODO: Delete
                    // MessageBox.Show("Delta X: " + deltaX.ToString()
                    //         + "\nDelta Y: " + deltaY.ToString()
                    //         + "\nLast X: " + lastX.ToString()
                    //         + "\nLast Y: " + lastY.ToString());

                    VideoMotionKeyframe vmKeyframe = new VideoMotionKeyframe(currProject, keyframeTime - ve2.Start);
                    ve2vm.Keyframes.Add(vmKeyframe);

                    // TODO: Delete
                    // MessageBox.Show("Current Bounds: " + vmKeyframe.Bounds.ToString()
                    //         + "\nCurrent Rotation: " + vmKeyframe.Rotation.ToString()
                    //         + "\nCurrent Type: " + vmKeyframe.Type.ToString()
                    //         + "\nCurrent Smoothness: " + vmKeyframe.Smoothness.ToString()
                    //         + "\n\nPrevious Bounds: " + prevKeyframe.Bounds.ToString()
                    //         + "\nPrevious Rotation: " + prevKeyframe.Rotation.ToString()
                    //         + "\nPrevious Type: " + prevKeyframe.Type.ToString()
                    //         + "\nPrevious Smoothness: " + prevKeyframe.Smoothness.ToString());

                    // Duplicate previous keyframe values
                    // vmKeyframe.Bounds = prevKeyframe.Bounds;
                    // vmKeyframe.Rotation = prevKeyframe.Rotation;
                    // vmKeyframe.Type = prevKeyframe.Type;
                    // vmKeyframe.Smoothness = prevKeyframe.Smoothness;

                    // bool kfGrabbed = false;
                    // foreach (VideoMotionKeyframe kf in ve2vm.Keyframes)
                    // {
                    //     if (kf.Position.Equals(vmKeyframe.Position))
                    //     {
                    //         vmKeyframe = kf;
                    //         kfGrabbed = true;
                    //         break;
                    //     }
                    // }

                    // if (!kfGrabbed)
                    // {
                    //     MessageBox.Show("Something went wrong as the script tried to regrab a created keyframe with the Timecode " + vmKeyframe.Position.ToString() + " ...\n\nTerminating...", "Error regrabbing keyframe", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    //     return;
                    // }

                    double convertedX = deltaX * videoWidth;
                    double convertedY = -1 * (deltaY * videoHeight);

                    vmKeyframe.MoveBy(new VideoMotionVertex(Convert.ToSingle(convertedX), Convert.ToSingle(convertedY)));

                    // MessageBox.Show("Next Bounds: " + vmKeyframe.Bounds.ToString()
                    //         + "\nNext Rotation: " + vmKeyframe.Rotation.ToString()
                    //         + "\nNext Type: " + vmKeyframe.Type.ToString()
                    //         + "\nNext Smoothness: " + vmKeyframe.Smoothness.ToString());

                    prevKeyframe = vmKeyframe;
                }
            }
        }

        // TODO: Bother with interpolation shit?
        // dialogResult = MessageBox.Show("Do you also want to copy the interpolation data?", "Copy interpolation data?", MessageBoxButtons.YesNo);

        // if (dialogResult == DialogResult.Yes)
        // {
        //     int curr = 0;
        //     int end = cornerParam.Keyframes.Count;

        //     foreach (OFXDouble2DKeyframe motionKeyframe in motionParam.Keyframes)
        //     {
        //         Timecode keyframeTime = motionKeyframe.Time + ve.Start;
        //         if (curr < end && startingTime <= keyframeTime && keyframeTime <= endingTime)
        //         {
        //             Timecode calculatedTime = (keyframeTime - ve2.Start);

        //             OFXDouble2DKeyframe cornerKeyframe = cornerParam.Keyframes[curr] as OFXDouble2DKeyframe;
        //             if (cornerKeyframe.Time == calculatedTime)
        //             {
        //                 cornerKeyframe.Interpolation = motionKeyframe.Interpolation;
        //             }
        //             else if (cornerKeyframe.Time < calculatedTime)
        //             {
        //                 ++curr;
        //             }
        //         }
        //     }
        // }

        // cornerParam.ParameterChanged();
    }