Esempio n. 1
0
    bool HandleGroup(TrackEventGroup group)
    {
        DateTime?groupTimeNul = null;

        foreach (TrackEvent trackEvent in group)
        {
            DateTime?tempTime = GetGlobalTime(trackEvent);
            if (null != tempTime && null == groupTimeNul)
            {
                groupTimeNul = tempTime;
            }
        }

        if (null == groupTimeNul)
        {
            return(false);
        }

        DateTime groupTime = (DateTime)groupTimeNul;

        TimeSpan timeSpan = new TimeSpan(groupTime.Ticks - m_minGlobalTime.Ticks);
        double   dOffset  = timeSpan.TotalMilliseconds;

        foreach (TrackEvent trackEvent in group)
        {
            trackEvent.Start = new Timecode(dOffset);
        }

        return(true);
    }
 // skip audio events that are grouped with a selected video event
 // that uses the same media because they usually contain the same
 // captioning data
 private bool IsPairedAudioEvent(TrackEvent trackEvent, Media media)
 {
     if (trackEvent.IsAudio() && trackEvent.IsGrouped)
     {
         TrackEventGroup group = trackEvent.Group;
         if (null != group)
         {
             foreach (TrackEvent groupedEvent in group)
             {
                 if (groupedEvent != trackEvent)
                 {
                     if (groupedEvent.IsVideo() && groupedEvent.Selected)
                     {
                         Take take = groupedEvent.ActiveTake;
                         if (null != take)
                         {
                             Media groupedMedia = take.Media;
                             if (null != media)
                             {
                                 if (groupedMedia == media)
                                 {
                                     return(true);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return(false);
 }
    public void FromVegas(Vegas vegas)
    {
        this.vegas = vegas;
        util       = new Util(vegas);

        Dictionary <Track, List <TrackEvent> > selectedTrackEventMap;
        Dictionary <Track, List <TrackEvent> > nonSelectedtrackEventMap;

        util.GetSelectedTrackEvents(out selectedTrackEventMap, out nonSelectedtrackEventMap);

        if (selectedTrackEventMap.Count != 1)
        {
            util.ShowError("Requires: 1 selected track with selected events");
            return;
        }

        //Assuming there's only 1 selected track, then get the selected track like this:
        IEnumerator selectedTrackEnum = selectedTrackEventMap.Keys.GetEnumerator();

        selectedTrackEnum.MoveNext();
        Track selectedTrack = (Track)selectedTrackEnum.Current;

        if (selectedTrack == null)
        {
            util.ShowError(selectedTrackEventMap.Count + "");
            return;
        }

        //Create a group for each selected track event in selected track
        Dictionary <TrackEvent, TrackEventGroup> selectedTrackEventGroups = new Dictionary <TrackEvent, TrackEventGroup>();

        foreach (TrackEvent trackEvent in selectedTrackEventMap[selectedTrack])
        {
            //Create new group to hold track event
            TrackEventGroup trackEventGroup = new TrackEventGroup();
            vegas.Project.Groups.Add(trackEventGroup);
            trackEventGroup.Add(trackEvent);
            selectedTrackEventGroups.Add(trackEvent, trackEventGroup);
        }

        //Go through every selected track event in non selected tracks and put them in the right groups (if possible)
        foreach (KeyValuePair <Track, List <TrackEvent> > nonSelectedtrackEventMapEntry in nonSelectedtrackEventMap)
        {
            foreach (TrackEvent trackEvent in nonSelectedtrackEventMapEntry.Value)
            {
                TrackEvent overlappingTrackEvent = util.GetOverlappingTrackEvent(trackEvent, new List <TrackEvent>(selectedTrackEventGroups.Keys));
                if (overlappingTrackEvent != null)
                {
                    selectedTrackEventGroups[overlappingTrackEvent].Add(trackEvent);
                }
            }
        }
    }
Esempio n. 4
0
    void ProcessBlips()
    {
        selectedVideoEvent = util.GetFirstSelectedVideoEvent();

        if (selectedVideoEvent == null)
        {
            util.ShowError("No video event selected");
            return;
        }

        TrackEventGroup selectedVideoEventGroup = selectedVideoEvent.Group;

        //take the first audio track in the selected video's group
        foreach (TrackEvent trackEventInGroup in selectedVideoEventGroup)
        {
            if (trackEventInGroup is AudioEvent)
            {
                selectedAudioEvent = trackEventInGroup as AudioEvent;
                break;
            }
        }

        if (selectedAudioEvent == null)
        {
            util.ShowError("Selected video event has no audio event in its group");
            return;
        }

        //Create a temporary WAV file, and export the audio span of selected video event
        string wavePath = wavUtil.CreateVideoEventWAV(selectedVideoEvent);

        if (wavePath == null)
        {
            util.ShowError("Unable to export temporary WAV");
            return;
        }

        short[] leftChannel, rightChannel;
        bool    wavReadStatus = wavUtil.ReadWav(wavePath, out leftChannel, out rightChannel);

        if (wavReadStatus == false)
        {
            util.ShowError("Unable to read WAV export file.");
            return;
        }

        //Delete the temporary file
        File.Delete(wavePath);

        //Find all blips in the left channel and split tracks at blips
        blips = wavUtil.FindBlips(rightChannel);
    }
Esempio n. 5
0
        public PushBlur(List <TrackEvent> SelectedMedias, Vegas vegas, TransitionMode TransitionMode)
        {
            selectedMedias = SelectedMedias;
            myVegas        = vegas;
            transitionMode = TransitionMode;

            group1 = selectedMedias[0].Group;
            group2 = selectedMedias[1].Group;

            if (Config.DebugMode)
            {
                MessageBox.Show($"group1 events = {group1.Count}");
                MessageBox.Show($"group2 events = {group2.Count}");
            }
        }
Esempio n. 6
0
        //Split a track event at a global location, and creating new groups if splitGroups = true
        public TrackEvent Split(TrackEvent trackEvent, Timecode splitLocation, bool splitGroups)
        {
            TrackEventGroup trackEventGroup = trackEvent.Group;

            //If not splitting groups or not in a group, then perform split on event and return
            if (!splitGroups || trackEventGroup == null)
            {
                return(trackEvent.Split(splitLocation - trackEvent.Start));
            }

            //Create new group to hold split events
            TrackEventGroup splitGroup = new TrackEventGroup();

            vegas.Project.Groups.Add(splitGroup);

            //Reference to splitEvent of trackEvent
            TrackEvent returnSplitEvent = null;

            //Split every track event in the group
            foreach (TrackEvent trackEventInGroup in trackEventGroup)
            {
                //If splitLocation splits the track, then split it
                if (IsTimecodeInTrackEvent(trackEventInGroup, splitLocation))
                {
                    TrackEvent splitEvent = trackEventInGroup.Split(splitLocation - trackEventInGroup.Start);

                    //remove the splitEvent from group, and add it to splitGroup
                    trackEventGroup.Remove(splitEvent);
                    splitGroup.Add(splitEvent);

                    //if this track is the trackEvent in the parameter, then return it's split event
                    if (trackEventInGroup == trackEvent)
                    {
                        returnSplitEvent = splitEvent;
                    }
                }
                //If splitLocation comes before the track, then move the track to splitGroup
                else if (IsTimecodeBeforeTrackEvent(trackEventInGroup, splitLocation))
                {
                    //remove the trackEventInGroup from group, and add it to splitGroup
                    trackEventGroup.Remove(trackEventInGroup);
                    splitGroup.Add(trackEventInGroup);
                }
            }

            return(returnSplitEvent);
        }
Esempio n. 7
0
        private bool isTrackUnique(Track initialTrack, Track comparisonTrack, TrackEventGroup trackEventsGroup)
        {
            if (comparisonTrack == initialTrack)
            {
                return(false);
            }

            foreach (TrackEvent trackEvent in trackEventsGroup)
            {
                if (trackEvent.Track == comparisonTrack)
                {
                    return(false);
                }
            }

            return(true);
        }
        public static bool isPickedEventsInTheSameGroup(List <TrackEvent> selectedMedias)
        {
            TrackEventGroup group = null;

            foreach (TrackEvent trackEvent in selectedMedias)
            {
                if (group == null)
                {
                    group = trackEvent.Group;
                }
                else
                {
                    if (group == trackEvent.Group)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 9
0
    public void FromVegas(Vegas vegas)
    {
        myVegas = vegas;
        List <WorkItem>   workItems = new List <WorkItem>();
        List <AudioEvent> events    = new List <AudioEvent>();

        AddSelectedAudioEvents(events);
        if (0 == events.Count)
        {
            AddAllAudioEvents(events);
        }

        foreach (AudioEvent audioEvent in events)
        {
            if (audioEvent.Channels == ChannelRemapping.None)
            {
                Track destTrack = FindDestTrack(audioEvent.Track);
                if (null == destTrack)
                {
                    destTrack = CreateDestTrack(audioEvent.Track);
                }
                workItems.Add(new WorkItem(audioEvent, destTrack));
            }
        }

        foreach (WorkItem workItem in workItems)
        {
            AudioEvent destEvent = (AudioEvent)workItem.SrcEvent.Copy(workItem.DstTrack, workItem.SrcEvent.Start);
            workItem.SrcEvent.Channels = ChannelRemapping.DisableRight;
            destEvent.Channels         = ChannelRemapping.DisableLeft;
            TrackEventGroup sourceGroup = workItem.SrcEvent.Group;
            if (null == sourceGroup)
            {
                sourceGroup = new TrackEventGroup();
                myVegas.Project.Groups.Add(sourceGroup);
                sourceGroup.Add(workItem.SrcEvent);
            }
            sourceGroup.Add(destEvent);
        }
    }
Esempio n. 10
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);
            }
        }
Esempio n. 11
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)
    {
        // Collect lists of the audio of media with video
        // and video events of media with audio

        List <TrackEvent> evtListAudio = new List <TrackEvent>();
        List <TrackEvent> evtListVideo = new List <TrackEvent>();

        foreach (Track trkItem in vegas.Project.Tracks)
        {
            foreach (TrackEvent evtItem in trkItem.Events)
            {
                if ((evtItem.MediaType == MediaType.Audio) && (evtItem.ActiveTake.Media.HasVideo()))
                {
                    evtListAudio.Add(evtItem);
                }
                else if ((evtItem.MediaType == MediaType.Video) && (evtItem.ActiveTake.Media.HasAudio()))
                {
                    evtListVideo.Add(evtItem);
                }
            }
        }

        // For all of the listed video events, group together any
        // audio events sharing the same start/end, and sharing the same media

        int numVidEvents = evtListVideo.Count;

        for (int ixVidEvt = 0; ixVidEvt < numVidEvents; ++ixVidEvt)
        {
            TrackEvent evtVid = evtListVideo[ixVidEvt];

            TrackEventGroup grpTmp     = null;
            bool            matchFound = false;  // defer creating a group, or adding the events to the group until a match is found

            // Walk the audio-event list in reverse order so matched items can be safetly removed from the list
            int numAudEvents = evtListAudio.Count;
            for (int ixAudEvt = numAudEvents - 1; ixAudEvt >= 0; --ixAudEvt)
            {
                TrackEvent evtAud = evtListAudio[ixAudEvt];

                // For a match the event must;
                // have the same start and end points and reference the same media
                bool test1 = evtVid.Start == evtAud.Start;
                bool test2 = evtVid.End == evtAud.End;
                bool test3 = evtVid.ActiveTake.Media == evtAud.ActiveTake.Media;

                if (test1 && test2 && test3)
                {
                    if (!matchFound)
                    {
                        // On the first match, create the group and add the video event
                        matchFound = true;
                        grpTmp     = new TrackEventGroup();
                        vegas.Project.TrackEventGroups.Add(grpTmp);
                        grpTmp.Add(evtVid);
                    }

                    // Add the matching audio event and remove it from the list leaving only unmatched events
                    grpTmp.Add(evtAud);
                    evtListAudio.RemoveAt(ixAudEvt);
                }
            }
        }
    }
        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (listViewTracks.SelectedItems.Count == 2)
            {
                Track t1 = listViewTracks.SelectedItems[0].Tag as Track;
                Track t2 = listViewTracks.SelectedItems[1].Tag as Track;

                if (t1.Events.Count != t2.Events.Count)
                {
                    MessageBox.Show("Você selecionou duas faixas com quantidades de eventos diferentes.\nOs eventos serão agrupados apenas até a contagem de eventos da menor faixa.");
                }
                try
                {
                    for (int i = 0; i < t1.Events.Count; i++)
                    {
                        TrackEventGroup g = new TrackEventGroup();
                        MyVegas.Project.TrackEventGroups.Add(g);
                        g.Add(t1.Events[i]);
                        g.Add(t2.Events[i]);
                    }
                }
                catch { }
                finally
                {
                    Close();
                }
            }
            else
                MessageBox.Show("Selecione somente duas faixas na lista");
        }