Exemplo n.º 1
0
    void ProcessMidi()
    {
        VideoTrack destVideoTrack = new VideoTrack(0, "destVideoTrack");
        AudioTrack destAudioTrack = new AudioTrack(0, "destAudioTrack");

        vegas.Project.Tracks.Add(destAudioTrack);
        vegas.Project.Tracks.Add(destVideoTrack);

        MidiFile midi = new MidiFile(midiFilePath);
        Dictionary <string, double> onNotes = new Dictionary <string, double>();

        TempoEvent lastTempoEvent     = new TempoEvent(0, 0);
        double     lastTempoEventTime = 0;

        for (int i = 0; i < midi.Events.Count(); i++)
        {
            foreach (MidiEvent midiEvent in midi.Events[i])
            {
                if (midiEvent is TempoEvent)
                {
                    lastTempoEvent     = (midiEvent as TempoEvent);
                    lastTempoEventTime = ((double)(midiEvent.AbsoluteTime - lastTempoEvent.AbsoluteTime) / midi.DeltaTicksPerQuarterNote) * lastTempoEvent.MicrosecondsPerQuarterNote + lastTempoEventTime;
                }
                else if (midiEvent is NoteEvent && midiEvent.Channel == midiReadLayer)
                {
                    NoteEvent noteEvent = midiEvent as NoteEvent;
                    double    usTime    = ((double)(noteEvent.AbsoluteTime - lastTempoEvent.AbsoluteTime) / midi.DeltaTicksPerQuarterNote) * lastTempoEvent.MicrosecondsPerQuarterNote + lastTempoEventTime;
                    double    msTime    = usTime / 1000;
                    int       velocity  = noteEvent.Velocity;

                    if (noteEvent.CommandCode == MidiCommandCode.NoteOn)
                    {
                        onNotes[noteEvent.NoteName] = msTime;
                    }
                    else if (noteEvent.CommandCode == MidiCommandCode.NoteOff)
                    {
                        if (onNotes.ContainsKey(noteEvent.NoteName))
                        {
                            double noteStartTime = onNotes[noteEvent.NoteName];
                            double noteEndTime   = msTime;
                            int    blipNum       = GetBlipFromPitch(noteEvent.NoteName);

                            if (blipNum == -1)
                            {
                                //note not found in pitchBlipMap
                                continue;
                            }

                            onNotes.Remove(noteEvent.NoteName);

                            //Map the MIDI note to a video/audio event
                            VideoEvent videoEvent = selectedVideoEvent.Copy(destVideoTrack, selectedVideoEvent.Start) as VideoEvent;
                            AudioEvent audioEvent = selectedAudioEvent.Copy(destAudioTrack, selectedAudioEvent.Start) as AudioEvent;

                            Timecode clipDurationMillis      = new Timecode(noteEndTime - noteStartTime + noteEndOffset);
                            Timecode globalClipStartLocation = new Timecode(selectedVideoEvent.Start.ToMilliseconds() + (blips[blipNum].locationInMicroseconds / 1000) + blipStartOffset);

                            TrackEvent tmpTrackEvent = videoEvent;
                            util.TrimEvent(ref tmpTrackEvent, globalClipStartLocation, clipDurationMillis);
                            videoEvent = tmpTrackEvent as VideoEvent;

                            tmpTrackEvent = audioEvent;
                            util.TrimEvent(ref tmpTrackEvent, globalClipStartLocation, clipDurationMillis);
                            audioEvent = tmpTrackEvent as AudioEvent;
                            audioEvent.FadeIn.Length  = new Timecode(fadeInLength);
                            audioEvent.FadeOut.Length = new Timecode(fadeOutLength);

                            videoEvent.Start = new Timecode(noteStartTime);
                            audioEvent.Start = new Timecode(noteStartTime);
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 2
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);
            }
        }