NEED HELP !! Scripting || Trim Events At Timecodes.

iEmby wrote on 11/5/2024, 12:08 AM

@jetdv

hi sir how r you..

i need your help in this code..

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using ScriptPortal.Vegas;

public class EntryPoint
{
    public void FromVegas(Vegas vegas)
    {
        // Open form for user input
        string userInput = PromptForTimecodes(vegas);
        if (string.IsNullOrEmpty(userInput))
        {
            MessageBox.Show("Operation cancelled or no input provided.");
            return;
        }
    }

    private string PromptForTimecodes(Vegas vegas)
    {
        using (Form form = new Form())
        {
            form.Text = "Enter Timecodes (e.g. HH:MM:SS - HH:MM:SS or HH:MM:SS to HH:MM:SS)";
            form.StartPosition = FormStartPosition.CenterScreen;
            form.Size = new System.Drawing.Size(400, 300);

            TextBox textBox = new TextBox
            {
                Multiline = true,
                Width = 360,
                Height = 200,
                ScrollBars = ScrollBars.Vertical
            };

            Button keepButton = new Button
            {
                Text = "Keep",
                DialogResult = DialogResult.OK,
                Location = new System.Drawing.Point(50, 220)
            };

            Button cutButton = new Button
            {
                Text = "Cut",
                DialogResult = DialogResult.OK,
                Location = new System.Drawing.Point(150, 220)
            };

            Button cancelButton = new Button
            {
                Text = "Cancel",
                DialogResult = DialogResult.Cancel,
                Location = new System.Drawing.Point(250, 220)
            };

            keepButton.Click += (sender, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    MessageBox.Show("Please enter valid timecodes.");
                }
                else
                {
                    ProcessUserSelection(vegas, textBox.Text, true);
                    form.Close();
                }
            };

            cutButton.Click += (sender, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    MessageBox.Show("Please enter valid timecodes.");
                }
                else
                {
                    ProcessUserSelection(vegas, textBox.Text, false);
                    form.Close();
                }
            };

            form.Controls.Add(textBox);
            form.Controls.Add(keepButton);
            form.Controls.Add(cutButton);
            form.Controls.Add(cancelButton);
            form.CancelButton = cancelButton;

            // Show dialog and return user input or an empty string
            return form.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
        }
    }

    private void ProcessUserSelection(Vegas vegas, string userInput, bool keepOddEvents)
    {
        // Process each line of input
        foreach (string line in userInput.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            ProcessLine(vegas, line.Trim());
        }

        // Run the conversion from regions to markers
        RegionsToMarkers(vegas);
        // Split events at markers
        SplitAtMarkers(vegas);
        // Remove markers and regions after processing
        RemoveMarkers(vegas);
        RemoveRegions(vegas);
        // Select and delete either odd or even events
        if (keepOddEvents)
        {
            SelectOddEvents(vegas);
        }
        else
        {
            SelectEvenEvents(vegas);
        }
        DeleteSelectedEvents(vegas);
    }

    void ProcessLine(Vegas vegas, string line)
    {
        try
        {
            // Split the line into start and end timecodes using '-' or 'to' as delimiters
            string[] pieces = line.Split(new string[] { "-", "to" }, StringSplitOptions.RemoveEmptyEntries);
            if (pieces.Length != 2)
            {
                MessageBox.Show("Line format is incorrect: " + line + "\nExpected format: HH:MM:SS - HH:MM:SS or HH:MM:SS to HH:MM:SS");
                return;
            }

            // Normalize timecodes
            string startCode = EnsureFourPairs(pieces[0].Trim());
            string endCode = EnsureFourPairs(pieces[1].Trim());

            // Check for empty string after ensuring proper format
            if (string.IsNullOrEmpty(startCode) || string.IsNullOrEmpty(endCode))
            {
                MessageBox.Show("Invalid timecode format: " + line);
                return;
            }

            // Convert to Timecode objects
            Timecode regionStart = Timecode.FromString(startCode);
            Timecode regionEnd = Timecode.FromString(endCode);

            // Ensure end time is greater than start time
            if (regionEnd < regionStart)
            {
                MessageBox.Show("End time must be greater than start time: " + line);
                return;
            }

            // Create and add the region
            ScriptPortal.Vegas.Region myRegion = new ScriptPortal.Vegas.Region(regionStart, regionEnd - regionStart);
            vegas.Project.Regions.Add(myRegion);
        }
        catch (FormatException ex)
        {
            MessageBox.Show("Error processing line: " + line + " - " + ex.Message);
        }
    }

    private void RegionsToMarkers(Vegas vegas)
    {
        try
        {
            // Iterate through all regions and convert both start and end marks into markers
            foreach (ScriptPortal.Vegas.Region region in vegas.Project.Regions)
            {
                try
                {
                    // Create markers for the start and end of the region
                    Marker startMarker = new Marker(region.Position, region.Label + " (Start)");
                    vegas.Project.Markers.Add(startMarker);

                    Marker endMarker = new Marker(region.Position + region.Length, region.Label + " (End)");
                    vegas.Project.Markers.Add(endMarker);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while adding markers for region '" + region.Label + "': " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    // Continue with the next region even if there's an error with the current one
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("An unexpected error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void SplitAtMarkers(Vegas vegas)
    {
        try
        {
            List<TrackEvent> selectedEvents = GetSelectedEvents(vegas);
            int totalMarkers = vegas.Project.Markers.Count;

            if (totalMarkers == 0)
            {
                MessageBox.Show("No markers found in the project.", "No Markers", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (selectedEvents == null || selectedEvents.Count == 0)
            {
                MessageBox.Show("No events selected.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            foreach (Track track in vegas.Project.Tracks)
            {
                foreach (TrackEvent trackEvent in track.Events)
                {
                    if (trackEvent.Selected)
                    {
                        Timecode eventStart = trackEvent.Start;

                        // Iterate over markers to split events
                        foreach (Marker marker in vegas.Project.Markers)
                        {
                            if (marker.Position >= trackEvent.Start && marker.Position <= trackEvent.End)
                            {
                                Timecode markerPosition = marker.Position;

                                // Calculate the offset relative to the event start
                                Timecode offset = markerPosition - eventStart;

                                // Split the event at the marker
                                trackEvent.Split(offset);

                                eventStart = markerPosition; // Update event start time
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private List<TrackEvent> GetSelectedEvents(Vegas vegas)
    {
        List<TrackEvent> selectedEvents = new List<TrackEvent>();

        try
        {
            foreach (Track track in vegas.Project.Tracks)
            {
                foreach (TrackEvent trackEvent in track.Events)
                {
                    try
                    {
                        if (trackEvent.Selected)
                        {
                            selectedEvents.Add(trackEvent);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error processing TrackEvent: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error while retrieving selected events: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        return selectedEvents;
    }

    private void RemoveMarkers(Vegas vegas)
    {
        try
        {
            vegas.Project.Markers.Clear();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error while removing markers: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void RemoveRegions(Vegas vegas)
    {
        try
        {
            vegas.Project.Regions.Clear();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error while removing regions: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void SelectOddEvents(Vegas vegas)
    {
        foreach (Track track in vegas.Project.Tracks)
        {
            if (track.Selected)
            {
                int eventIndex = 0;
                foreach (TrackEvent trackEvent in track.Events)
                {
                    trackEvent.Selected = eventIndex % 2 == 0; // Keep odd events
                    eventIndex++;
                }
            }
        }
    }

    private void SelectEvenEvents(Vegas vegas)
    {
        foreach (Track track in vegas.Project.Tracks)
        {
            if (track.Selected)
            {
                int eventIndex = 0;
                foreach (TrackEvent trackEvent in track.Events)
                {
                    trackEvent.Selected = eventIndex % 2 != 0; // Keep even events
                    eventIndex++;
                }
            }
        }
    }

    private void DeleteSelectedEvents(Vegas vegas)
    {
        foreach (Track track in vegas.Project.Tracks)
        {
            List<TrackEvent> eventsToDelete = new List<TrackEvent>();

            foreach (TrackEvent trackEvent in track.Events)
            {
                if (trackEvent.Selected)
                {
                    eventsToDelete.Add(trackEvent);
                }
            }

            foreach (TrackEvent eventToDelete in eventsToDelete)
            {
                track.Events.Remove(eventToDelete);
            }
        }
    }

    private string EnsureFourPairs(string timecode)
    {
        // Replace periods with colons to handle different separators
        timecode = timecode.Replace('.', ':').Trim();

        // Split the timecode by colons
        string[] parts = timecode.Split(':');

        switch (parts.Length)
        {
            case 1: // SS
                return "00:00:" + parts[0].PadLeft(2, '0') + ":00"; // Format: 00:00:SS:00

            case 2: // MM:SS
                return "00:" + parts[0].PadLeft(2, '0') + ":" + parts[1].PadLeft(2, '0') + ":00"; // Format: 00:MM:SS:00

            case 3: // HH:MM:SS
                return parts[0].PadLeft(2, '0') + ":" + parts[1].PadLeft(2, '0') + ":" + parts[2].PadLeft(2, '0') + ":00"; // Format: HH:MM:SS:00

            case 4: // HH:MM:SS:FF (Already valid format)
                return parts[0].PadLeft(2, '0') + ":" + parts[1].PadLeft(2, '0') + ":" + parts[2].PadLeft(2, '0') + ":" + parts[3]; // Format: HH:MM:SS:FF

            default:
                MessageBox.Show("Invalid timecode format: " + timecode, "Error");
                return string.Empty; // Returning empty string to avoid null reference warning
        }
    }
}

actually, it is working good for me.

but it is removing corresponding audio streams too if I select only video event and also after trim process it is also grouping all events, but I need them to stay in their original stream's groups.

please take a look at this clip for more understanding sir..

thanks in advance.. sir..

PROCESSOR
     

Operating System: Windows 11 Pro 64-bit (Always Updated)
System Manufacturer: ASUS
12th Gen Intel(R) Core(TM) i7-12700 (20 CPUs), ~2.1GHz - 4.90GHz
Memory: 32GB RAM
Page File: 11134MB used, 7934MB Available
DirectX Version: DirectX 12

-----------------------------------------------

MOTHERBOARD

 

ASUS PRIME H610-CS D4
Intel® H610 (LGA 1700)
Ready for 12th Gen Intel® Processors
Micro-ATX Motherboard with DDR4
Realtek 1 Gb Ethernet
PCH Heatsink
PCIe 4.0 | M.2 slot (32Gbps) 
HDMI® | D-Sub | USB 3.2 Gen 1 ports
SATA 6 Gbps | COM header
LPT header | TPM header
Luminous Anti-Moisture Coating
5X Protection III
(Multiple Hardware Safeguards
For all-round protection)

-----------------------------------------------
EXTERNAL GRAPHIC CARD

-----------------------------------------------

INTERNAL GRAPHIC CARD (iGPU)

------------------------------------------------

LED - MONITOR

Monitor Name: Generic PnP Monitor
Monitor Model: HP 22es
Monitor Id: HWP331B
Native Mode: 1920 x 1080(p) (60.000Hz)
Output Type: HDMI

-----------------------------------------------

STORAGE DRIVE

Drive: C:
Free Space: 182.3 GB
Total Space: 253.9 GB
File System: NTFS
Model: WD Blue SN570 1TB (NVMe)

---------------O----------------

My System Info (PDF File).

https://drive.google.com/open?id=1-eoLmuXzshTRH_8RunAYAuNocKpiLoiV&usp=drive_fs

 

Also Check

Some useful creations by me including VEGAS Scripts

https://getopensofts.blogspot.com/

 

My YouTube Channel Dedicated to Only VEGAS Pro Tutorials

EDITROOM : My YouTube Channel (For VEGAS Tutorials)

Comments

jetdv wrote on 11/5/2024, 1:41 PM

You're processing SELECTED events:

if (trackEvent.Selected)

So you must also select the audio events for them to be processed.

Splitting does not "remove grouping":

trackEvent.Split(offset);

That splits the event but now both are part of the original grouping.

iEmby wrote on 11/5/2024, 9:03 PM

@jetdv thankyou sir...

PROCESSOR
     

Operating System: Windows 11 Pro 64-bit (Always Updated)
System Manufacturer: ASUS
12th Gen Intel(R) Core(TM) i7-12700 (20 CPUs), ~2.1GHz - 4.90GHz
Memory: 32GB RAM
Page File: 11134MB used, 7934MB Available
DirectX Version: DirectX 12

-----------------------------------------------

MOTHERBOARD

 

ASUS PRIME H610-CS D4
Intel® H610 (LGA 1700)
Ready for 12th Gen Intel® Processors
Micro-ATX Motherboard with DDR4
Realtek 1 Gb Ethernet
PCH Heatsink
PCIe 4.0 | M.2 slot (32Gbps) 
HDMI® | D-Sub | USB 3.2 Gen 1 ports
SATA 6 Gbps | COM header
LPT header | TPM header
Luminous Anti-Moisture Coating
5X Protection III
(Multiple Hardware Safeguards
For all-round protection)

-----------------------------------------------
EXTERNAL GRAPHIC CARD

-----------------------------------------------

INTERNAL GRAPHIC CARD (iGPU)

------------------------------------------------

LED - MONITOR

Monitor Name: Generic PnP Monitor
Monitor Model: HP 22es
Monitor Id: HWP331B
Native Mode: 1920 x 1080(p) (60.000Hz)
Output Type: HDMI

-----------------------------------------------

STORAGE DRIVE

Drive: C:
Free Space: 182.3 GB
Total Space: 253.9 GB
File System: NTFS
Model: WD Blue SN570 1TB (NVMe)

---------------O----------------

My System Info (PDF File).

https://drive.google.com/open?id=1-eoLmuXzshTRH_8RunAYAuNocKpiLoiV&usp=drive_fs

 

Also Check

Some useful creations by me including VEGAS Scripts

https://getopensofts.blogspot.com/

 

My YouTube Channel Dedicated to Only VEGAS Pro Tutorials

EDITROOM : My YouTube Channel (For VEGAS Tutorials)