SCRIPT HELP Envelope Point Creation and Opacity Issues

andy-0 wrote on 4/18/2024, 6:45 PM

 

Could someone help me fix this script? It was working fine until a few days ago, but after a change, it started to exhibit some instabilities. Previously, the script would analyze the audio track using the script to remove silent areas developed by JetDV and adapted. Then, it would create envelope points at the 51% level on the event above the video track associated with the selected audio track. The opacity of the image would change and react to the sound, depending on the decibel level inserted in the script. For example, the image opacity would only increase to 100% if the sound in the audio track was greater than -40 dB, and it would stay at 51% opacity if the sound was below that value. Recently, I made some changes and the script stopped working correctly. Now, it's creating the same envelope points in all videos, regardless of the volume analysis process, and it also started creating envelope points below the 51% level, which shouldn't happen. Could someone please help me fix this issue? I don't know how to correct it

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ScriptPortal.Vegas;

namespace Test_Script
{
    public class Class1
    {
        public Vegas myVegas;
        Renderer myRenderer = null;
        RenderTemplate rndrTemplate = null;
        double QuietLimit = -40;
        Timecode logOffset = Timecode.FromFrames(10);
        Timecode minLength = Timecode.FromSeconds(1.5);
        bool[,] trackStatus = new bool[1000, 2];
        Effect addedEffect = null; // Variável para manter o controle do efeito adicionado

        public void Main(Vegas vegas)
        {
            myVegas = vegas;

            FindRenderers();

            string tempFile = myVegas.TemporaryFilesPath + Path.DirectorySeparatorChar + "temp.mp3";
            string tempLog = myVegas.TemporaryFilesPath + Path.DirectorySeparatorChar + "temp_loud.txt";

            SaveTrackStatus();

            // Executa o script1 para adicionar o efeito à track de áudio antes da renderização
            RunScript1();

            foreach (Track myTrack in myVegas.Project.Tracks)
            {
                if (myTrack.IsAudio() && myTrack.Selected)
                {
                    myTrack.Mute = false;

                    RenderTempFile(tempFile);
                    ProcessLog(tempLog, myTrack);

                    File.Delete(tempFile);
                    File.Delete(tempLog);

                    myTrack.Mute = true;

                    // Remove o efeito da track de áudio após a renderização
                    RemoveEffectFromAudioTrack(myTrack);
                }
            }

            // Restaura o estado das tracks de áudio
            RecallTrackStatus();
        }

        public void FindRenderers()
        {
            try
            {
                foreach (Renderer renderer in myVegas.Renderers)
                {
                    // MP3
                    if ("adfa6a4b-a99b-42e3-ae1f-081123ada04b" == renderer.ClassID.ToString())
                    {
                        myRenderer = renderer;
                        try
                        {
                            foreach (RenderTemplate renderTemplate in renderer.Templates)
                            {
                                if (renderTemplate.IsValid())
                                {
                                    // 192 Kbps, CD Transparent Audio
                                    if ("8ab64a16-81f5-46e6-8155-1611d592088c" == renderTemplate.TemplateGuid.ToString())
                                    {
                                        rndrTemplate = renderTemplate;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            catch
            {
            }
        }

        public void SaveTrackStatus()
        {
            foreach (Track myTrack in myVegas.Project.Tracks)
            {
                if (myTrack.IsAudio())
                {
                    int myIndex = myTrack.Index;
                    trackStatus[myIndex, 0] = myTrack.Mute;
                    trackStatus[myIndex, 1] = myTrack.Solo;

                    myTrack.Mute = true;
                    myTrack.Solo = false;
                }
            }
        }

        public void RecallTrackStatus()
        {
            foreach (Track myTrack in myVegas.Project.Tracks)
            {
                if (myTrack.IsAudio())
                {
                    int myIndex = myTrack.Index;
                    myTrack.Mute = trackStatus[myIndex, 0];
                    myTrack.Solo = trackStatus[myIndex, 1];
                }
            }
        }

        public void RenderTempFile(string tempFile)
        {
            RenderArgs args = new RenderArgs();
            args.OutputFile = tempFile;
            args.RenderTemplate = rndrTemplate;
            args.Start = Timecode.FromFrames(0);
            args.Length = myVegas.Project.Length;
            args.IncludeMarkers = false;
            args.StretchToFill = false;
            args.GenerateLoudnessLog = true;

            RenderStatus status = myVegas.Render(args);
        }

        public void ProcessLog(string path, Track myTrack)
        {
            Envelope compEnv = new Envelope(EnvelopeType.Composite);
            myVegas.Project.Tracks[0].Envelopes.Add(compEnv);
            compEnv.Points[0].Y = 0.0;

            var lines = File.ReadLines(path);

            bool foundfirst = false;
            bool FoundQuiet = false;
            Timecode QuietStart = Timecode.FromFrames(0);
            Timecode QuietEnd = Timecode.FromFrames(0);
            Timecode PreviousTC = Timecode.FromFrames(0);

            foreach (string line in lines)
            {
                if (line.StartsWith("------------"))
                {
                    if (FoundQuiet)
                    {
                        QuietEnd = PreviousTC;
                        ProcessSegment(QuietStart, myVegas.Project.Length + logOffset, myTrack);
                    }
                    break;
                }
                if (line.StartsWith("              Pos."))
                {
                    foundfirst = true;
                }
                else
                {
                    if (foundfirst)
                    {
                        if (line.Length > 5)
                        {
                            string[] pieces = line.Split('\t');
                            Timecode trackTime = Timecode.FromString(pieces[1]);
                            double trackVolume = 0;
                            if (pieces[2].Contains("Inf"))
                            {
                                trackVolume = -100;
                            }
                            else
                            {
                                trackVolume = Convert.ToDouble(pieces[2]);
                            }

                            EnvelopePoint a = compEnv.Points.GetPointAtX(trackTime);
                            if (a == null)
                            {
                                a = new EnvelopePoint(trackTime, 1.0 + (trackVolume / 100));
                                // Verifica se a opacidade está abaixo de 0.5 e, se estiver, define-a como 0.51 (acima de 50%)
                                if (a.Y < 0.5)
                                {
                                    a.Y = 0.51;
                                }
                                compEnv.Points.Add(a);
                            }
                            else
                            {
                                // Ajusta a opacidade mínima para 51% (0.51).
                                if (a.Y < 0.51)
                                {
                                    a.Y = 0.51;
                                }
                                else
                                {
                                    a.Y = 1.0 + (trackVolume / 100);
                                }
                            }

                            if (trackVolume < QuietLimit)
                            {
                                if (!FoundQuiet)
                                {
                                    FoundQuiet = true;
                                    QuietStart = trackTime;
                                }
                            }
                            else
                            {
                                if (FoundQuiet)
                                {
                                    FoundQuiet = false;
                                    QuietEnd = PreviousTC;

                                    ProcessSegment(QuietStart, QuietEnd, myTrack);
                                }
                            }
                            PreviousTC = trackTime;
                        }
                    }
                }
            }
        }

        private void ProcessSegment(Timecode QuietStart, Timecode QuietEnd, Track myTrack)
        {
            Timecode startTC = QuietStart - logOffset;
            if (startTC < Timecode.FromFrames(0))
            {
                startTC = Timecode.FromFrames(0);
            }

            Timecode endTC = QuietEnd - logOffset;
            Timecode regionLen = endTC - startTC;

            if (regionLen > minLength)
            {
                // Não faz nada com a faixa de áudio, pois a função de deletar partes do áudio foi removida.
            }
        }

        // Função para adicionar o efeito à track de áudio
        public void RunScript1()
        {
            // Verifica se há pelo menos uma faixa de áudio no projeto
            if (myVegas.Project.Tracks.Count > 0)
            {
                Track audioTrack = null;

                // Encontra a primeira faixa de áudio no projeto
                foreach (Track track in myVegas.Project.Tracks)
                {
                    if (track.IsAudio())
                    {
                        audioTrack = track;
                        break;
                    }
                }

                // Verifica se uma faixa de áudio foi encontrada
                if (audioTrack != null)
                {
                    // Substitua o GUID do "Track Compressor" effect
                    Guid effGUID = new Guid("23c9f225-40ec-11d2-9d36-00c04f8edc1e"); // GUID do "Track Compressor" effect

                    // Verifica se o efeito já está presente na faixa de áudio
                    if (!EffectExists(audioTrack, effGUID))
                    {
                        // Adiciona o efeito à faixa de áudio
                        AddEffectToAudioTrack(audioTrack, effGUID, "o preset para o script funcionar");
                    }
                }
                else
                {
                    // Lidar com o caso em que nenhuma faixa de áudio foi encontrada.
                }
            }
            else
            {
                // Lidar com o caso em que não há faixas no projeto.
            }
        }

        // Função para remover o efeito da track de áudio após a renderização
        public void RemoveEffectFromAudioTrack(Track track)
        {
            if (addedEffect != null)
            {
                // Remove o efeito da coleção de efeitos da faixa de áudio
                track.Effects.Remove(addedEffect);
                addedEffect = null; // Define a referência do efeito como nula
            }
        }

        // Verifica se um efeito com um determinado GUID já existe em uma faixa de áudio
        private bool EffectExists(Track track, Guid effGUID)
        {
            foreach (Effect effect in track.Effects)
            {
                if (effect.PlugIn.ClassID == effGUID)
                {
                    addedEffect = effect; // Mantém uma referência ao efeito adicionado
                    return true;
                }
            }
            return false;
        }

        // Adiciona um efeito a uma faixa de áudio
        private void AddEffectToAudioTrack(Track track, Guid effGUID, string presetName)
        {
            PlugInNode effNode = myVegas.PlugIns.GetChildByClassID(effGUID);
            if (effNode != null)
            {
                Effect effect = track.Effects.AddEffect(effNode);
                effect.Preset = presetName;
                addedEffect = effect; // Mantém uma referência ao efeito adicionado
            }
            else
            {
                // Lidar com o caso em que o plugin não foi encontrado.
            }
        }
    }

    public class EntryPoint
    {
        public void FromVegas(Vegas vegas)
        {
            Test_Script.Class1 test = new Test_Script.Class1();
            test.Main(vegas);
        }
    }
}

 

Could someone help me fix this script? It was working fine until a few days ago, but after a change, it started to exhibit some instabilities. Previously, the script would analyze the audio track using the script to remove silent areas developed by JetDV and adapted. Then, it would create envelope points at the 51% level on the event above the video track associated with the selected audio track. The opacity of the image would change and react to the sound, depending on the decibel level inserted in the script. For example, the image opacity would only increase to 100% if the sound in the audio track was greater than -40 dB, and it would stay at 51% opacity if the sound was below that value. Recently, I made some changes and the script stopped working correctly. Now, it's creating the same envelope points in all videos, regardless of the volume analysis process, and it also started creating envelope points below the 51% level, which shouldn't happen. Could someone please help me fix this issue? I don't know how to correct it

Comments

jetdv wrote on 4/19/2024, 9:08 AM

If you're getting the same results every time, it must be reading the same file every time. I would go into the temporary files folder and make sure you don't have either temp.mp3 or temp_loud.txt existing there. Perhaps they are still there but are not being overwritten by the new render.

andy-0 wrote on 4/19/2024, 10:57 AM

If you're getting the same results every time, it must be reading the same file every time. I would go into the temporary files folder and make sure you don't have either temp.mp3 or temp_loud.txt existing there. Perhaps they are still there but are not being overwritten by the new render.

I did this when I realized that the script was doing something wrong but none of the temporary files were in the temp folder. I even deleted all the files from it and restarted the computer but the script continued to show the same error. Could it be that something in the script is incorrect and is making it act like this @jetdv ?

andy-0 wrote on 4/19/2024, 11:17 AM

If you're getting the same results every time, it must be reading the same file every time. I would go into the temporary files folder and make sure you don't have either temp.mp3 or temp_loud.txt existing there. Perhaps they are still there but are not being overwritten by the new render.

hey jetdv I "managed" to solve the problem I found the old script that didn't have the changes made to the current one and it worked correctly I don't know what caused the one I showed to stop working but at least the old script is working normally as it should

jetdv wrote on 4/19/2024, 12:00 PM

Glad you found the old one. I always try to go back to a "known good one" when I hit something that doesn't work. Carefully compare the one that does work with the one that does not to see exactly what's different and that might tell you why.

Jack S wrote on 4/20/2024, 7:59 AM

@andy-0 If you use Visual Studio to develop your scripts, you can take advantage of its Git project management feature. After creating a Git repository, you declare your current script as the Master. You can then create a branch off that master which allows you to develop it further without destroying the master. When you're satisfied that your branch development is complete and tested, you can then merge the branch into the master.
For comparison purposes, you can view the same code from different stages of development so you can see what's changed.
My son's a programmer for a large company and it's the tool they use to manage their software development. He convinced me to use it so that I didn't have to manually save different versions of the same project. I haven't looked back since.

My system
Genshin Infinity Gaming PC
Motherboard Gigabyte H610M H: m-ATX w/, USB 3.2, 1 x M.2
Power Supply Corsair RM750X
Intel Core i7-13700K - 16-Core [8P @ 3.4GHz-5.4GHz / 8E @ 2.50GHz-4.20GHz]
30MB Cache + UHD Graphics, Ultimate OC Compatible
Case Fan 4 x CyberPowerPC Hyperloop 120mm ARGB & PWM Fan Kit
CPU Fan CyberPowerPC Master Liquid LITE 360 ARGB AIO Liquid Cooler, Ultimate OC Compatible
Memory 32GB (2 x 16GB) DDR5/5200MHz Corsair Vengeance RGB
MSI GeForce RTX 4060 Ti 8GB - Ray Tracing Technology, DX12, VR Ready, HDMI, DP
System drive 1TB WD Black SN770 M.2 NVMe PCIe SSD - 5150MB/s Read & 4900MB/s Write
Storage 2 x 2TB Seagate BarraCuda SATA-III 6.0Gb/s 7200RPM
Windows 11 Home (x64)
Monitors
Generic Monitor (PHL 222V8) connected to GeForce RTX 4060 Ti
Generic Monitor (SAMSUNG) connected to iGPU

Camcorder
SONY Handycam HDR-XR550VE

andy-0 wrote on 3/28/2025, 11:46 AM

 

@jetdv @zzzzzz9125 ( i need help figuring out what's causing this bug in the script.)

this post is old but I discovered something quite interesting about this script a few days ago and I never figured out the source of the problem or how to fix it. In my words a simple example of this bug is that for some reason the script only works on a single specific Veg file and no others even if the settings are 100% the same in both. I ran some tests and realized that when used the original veg file the script worked normally and when I used the same script on the other veg project 100% the same as the original the script was unable to determine where to insert the envelope points and did not even come close to reaching the locations they were supposed to be inserted.

Have you ever encountered a bug like this and do you have any idea what might be causing it?

jetdv wrote on 3/28/2025, 12:26 PM

@andy-0, I have not specifically seen that. If the "loud" file is not being regenerated for some reason, that could definitely cause an issue. However, the script is supposed to delete those files once completed. You could go check to see if the files are being deleted and, if not, remove them before running on the second VEG file.

andy-0 wrote on 3/28/2025, 12:30 PM

@jetdv I have analyzed and confirmed that it is deleting the indicated files when completed