public void Evaluate(int SpreadMax) { if (FInTimeZone.IsChanged || FInYear.IsChanged || FInMonth.IsChanged || FInDay.IsChanged || FInHours.IsChanged || FInMinutes.IsChanged || FInSeconds.IsChanged || FInFrame.IsChanged) { FOutTimeCode.SliceCount = SpreadMax; for (int i = 0; i < SpreadMax; i++) { FOutTimeCode[i] = new Timecode( FInTimeZone[i], FInYear[i], FInMonth[i], FInDay[i], FInHours[i], FInMinutes[i], FInSeconds[i], FInFrame[i]); } } }
private void PlayRegion(Timecode pos, Timecode len) { myVegas.Transport.CursorPosition = pos; myVegas.Transport.SelectionStart = pos; myVegas.Transport.SelectionLength = len; myVegas.Transport.ViewCursor(true); myVegas.Transport.Play(); }
public void MoveBy(Timecode Time) { foreach (TrackEvent Event in _Events) { Event.Start += Time; } _Region.Position += Time; }
protected override void FillBuffer(float[] buffer, int offset, int count) { if (InputSignal.Value != null) { InputSignal.Read(buffer, offset, count); FDecoder.Write(buffer, count, 0); if (FDecoder.GetQueueLength() > 0) Timecode = FDecoder.Read().getTimecode(); } }
public SamplerComponent() { Manufacturer = 0; Product = 0; SamplePeriod = 0; UnityNote = 0; PitchFraction = 0; _timecode = Timecode.Zero; LoopCount = 0; ExtraDataSize = 0; }
internal static bool RegionsBetween(this Project Project, Timecode A, Timecode B) { Timecode start = A; Timecode end = B; if (A > B) { start = B; end = A; } return Project.Regions.Any(region => region.End <= end && region.End >= start); }
public void FromVegas(Vegas vegas) { var start = vegas.Transport.LoopRegionStart; var length = vegas.Transport.LoopRegionLength; if (start.FrameCount == 0) { MessageBox.Show("Selection must start at frame >= 1!"); return; } if (length.FrameCount <= 1) { MessageBox.Show("Selection length must be > 1 frame!"); 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 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; } 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; } } if (videoTrack == null) { MessageBox.Show("No track 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 pathSrc = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); var pathEncodedSrc = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); Encode(vegas, scriptDirectory, new RenderArgs { OutputFile = pathSrc, Start = Timecode.FromFrames(start.FrameCount - 1), Length = Timecode.FromFrames(1), RenderTemplate = template }, pathEncodedSrc); var pathClip = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); var pathEncodedClip = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); Encode(vegas, scriptDirectory, new RenderArgs { OutputFile = pathClip, Start = start, Length = length, RenderTemplate = template }, pathEncodedClip); var pathDatamixed = Path.Combine(finalFolder, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8)) + ".avi"; string[] datamoshConfig = { "var input0=\"" + pathEncodedSrc.Replace("\\", "/") + "\";", "var input1=\"" + pathEncodedClip.Replace("\\", "/") + "\";", "var output=\"" + pathDatamixed.Replace("\\", "/") + "\";" }; File.WriteAllLines(Path.Combine(scriptDirectory, "_internal", "config_datamix.js"), datamoshConfig); 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_datamix.js", RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; datamosh.Start(); datamosh.StandardInput.WriteLine("n"); var output = datamosh.StandardOutput.ReadToEnd(); var error = datamosh.StandardError.ReadToEnd(); Debug.WriteLine(output); Debug.WriteLine("---------------------"); Debug.WriteLine(error); datamosh.WaitForExit(); File.Delete(pathEncodedSrc); File.Delete(pathEncodedSrc + ".sfl"); File.Delete(pathEncodedClip); File.Delete(pathEncodedClip + ".sfl"); var media = vegas.Project.MediaPool.AddMedia(pathDatamixed); media.TimecodeIn = Timecode.FromFrames(1); var videoEvent = videoTrack.AddVideoEvent(start, Timecode.FromFrames(length.FrameCount - 1)); videoEvent.AddTake(media.GetVideoStreamByIndex(0)); } catch (Exception e) { MessageBox.Show("Unexpected exception: " + e.Message); Debug.WriteLine(e); } }
public static bool IsCameraTime(this Timecode timecode) { return(timecode.Type == TimecodeType.CameraTime); }
private void Import(Config config, Vegas vegas) { // Load XML file if (!File.Exists(config.XmlFile)) { throw new Exception("XML file does not exist."); } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(config.XmlFile); // Determine image file names XmlNodeList mouthCueElements = xmlDocument.SelectNodes("//mouthCue"); List <string> shapeNames = new List <string>(); foreach (XmlElement mouthCueElement in mouthCueElements) { if (!shapeNames.Contains(mouthCueElement.InnerText)) { shapeNames.Add(mouthCueElement.InnerText); } } Dictionary <string, string> imageFileNames = GetImageFileNames(config.OneImageFile, shapeNames.ToArray()); // Create new project bool promptSave = !config.DiscardChanges; bool showDialog = false; Project project = new Project(promptSave, showDialog); // Set frame size Bitmap testImage = new Bitmap(config.OneImageFile); project.Video.Width = testImage.Width; project.Video.Height = testImage.Height; // Set frame rate if (config.FrameRate < 0.1 || config.FrameRate > 100) { throw new Exception("Invalid frame rate."); } project.Video.FrameRate = config.FrameRate; // Set other video settings project.Video.FieldOrder = VideoFieldOrder.ProgressiveScan; project.Video.PixelAspectRatio = 1; // Add video track with images VideoTrack videoTrack = vegas.Project.AddVideoTrack(); foreach (XmlElement mouthCueElement in mouthCueElements) { Timecode start = GetTimecode(mouthCueElement.Attributes["start"]); Timecode length = GetTimecode(mouthCueElement.Attributes["end"]) - start; VideoEvent videoEvent = videoTrack.AddVideoEvent(start, length); Media imageMedia = new Media(imageFileNames[mouthCueElement.InnerText]); videoEvent.AddTake(imageMedia.GetVideoStreamByIndex(0)); } // Add audio track with original sound file AudioTrack audioTrack = vegas.Project.AddAudioTrack(); Media audioMedia = new Media(xmlDocument.SelectSingleNode("//soundFile").InnerText); AudioEvent audioEvent = audioTrack.AddAudioEvent(new Timecode(0), audioMedia.Length); audioEvent.AddTake(audioMedia.GetAudioStreamByIndex(0)); }
public static bool IsIRIG(this Timecode timecode) { return(timecode.Type == TimecodeType.IRIG); }
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 _updateText() { Text = Timecode.ToSMPTETimecodeString(VideoFormat); }
private void RegionsResize(Timecode Time) { var groups = myVegas.GetRegionGroups(); using (var undo = new UndoBlock("Resize regions by " + Time)) { foreach (RegionGroup Group in groups) { Group.AdjustRegionLength(Group.Region.Length + Time); } } }
/// Implementation /// /// private void RegionsNudge(Timecode Time, bool Cumulative) { Timecode ZeroTime = myVegas.Project.Ruler.StartTime; Timecode Adjustment = Time; if (Cumulative) Adjustment = Timecode.FromSeconds(0); var Groups = myVegas.GetRegionGroups(); using (var undo = new UndoBlock("Nudge regions by " + Time)) { foreach (var group in Groups) { Timecode newTime = group.Region.Position + Adjustment; Timecode localAdjustment = Timecode.FromSeconds(0); // zero time detection if (newTime < ZeroTime) { if (ScriptOptions.GetValue(Strings.ScriptName, "ShowZeroTimeWarning", true)) { myVegas.ShowError("Cannot move beyond start of timeline", "Your operation was aborted to avoid moving events outside the timeline"); } return; } // collision detection foreach (var grp in Groups) { if (!grp.Equals(@group)) { if (newTime <= grp.Region.End && newTime >= grp.Region.Position) { localAdjustment = newTime - grp.Region.End; break; } } } group.MoveTo(newTime - localAdjustment); if (Cumulative) Adjustment += Time; } } }
private void RegionsAutoSize(Timecode Headroom) { var Groups = myVegas.GetRegionGroups(); // check overlapping groups var Overlaps = new List<RegionGroup>(); Timecode LastEnd = null; foreach (RegionGroup Grp in Groups) { if (LastEnd != null && Grp.Region.Position < LastEnd) { Overlaps.Add(Grp); } LastEnd = Grp.Region.End; } if (Overlaps.Count != 0) { if (MessageBox.Show( "This project contains overlapping / duplicate regions. Autosize would likely screw everything up. Continue anyway?", "Overlaps detected", MessageBoxButtons.YesNo) != DialogResult.Yes) { return; } } using (var undo = new UndoBlock("Fit regions to events")) { foreach (RegionGroup Grp in Groups) { if (Grp.Events.Count == 0) continue; Grp.Region.Position = Grp.Start - Headroom; Grp.Region.End = Grp.End + Headroom; } } }
public static void GetNormalizedTimeSelection(this TransportControl Transport, out Timecode Start, out Timecode End) { if (Transport.SelectionLength < Timecode.FromNanos(0)) { End = Transport.SelectionStart; Start = End + Transport.SelectionLength; } else { Start = Transport.SelectionStart; End = Start = Transport.SelectionLength; } }
public static Region FindRegion(this Sony.Vegas.Project Project, string RegionName, Timecode After) { var matchingRegions = new List<Region>(); foreach (Region r in Project.Regions) { if (r.Label.ToLower().Contains(RegionName.ToLower())) { matchingRegions.Add(r); if (r.Position > After) return r; // assumes sorted list of regions. } } if (matchingRegions.Any()) return matchingRegions[0]; return null; }
internal static Region NextRegion(this Project Project, Timecode timecode) { return Project.Regions.FirstOrDefault(r => r.Position > timecode); }
public static Region FindRegion(this ScriptPortal.Vegas.Project Project, string RegionName, Timecode After) { var matchingRegions = new List <Region>(); foreach (Region r in Project.Regions) { if (r.Label.ToLower().Contains(RegionName.ToLower())) { matchingRegions.Add(r); if (r.Position > After) { return(r); // assumes sorted list of regions. } } } if (matchingRegions.Any()) { return(matchingRegions[0]); } return(null); }
void socket_NewPacket(object sender, Acn.Sockets.NewPacketEventArgs<DJTapPacket> e) { if(e.Packet is Timecode) TimecodePacket = (Timecode) e.Packet; }
public void FromVegas(Vegas vegas) { Settings = new Settings(); // ********* Change default script paremeters here Settings.CrossFadeLength = 500; // Set default crossfade lenght here Settings.TimeUnit = TimeUnit.Milliseconds; // Set crossfade's time unit: milliseconds or frames Settings.ScriptMode = ScriptMode.CreateNewCrossfades; Settings.ChangeCurveType = false; // Set to true to be able to change curve types Settings.LeftCurveType = CurveType.Slow; // Left curve type: Fast, Linear, Sharp, Slow, Smooth. Vegas's default is Slow for audio and Smooth for video Settings.RightCurveType = CurveType.Fast; // Right curve type: Fast, Linear, Sharp, Slow, Smooth. Vegas's default is Fast for audio and Smooth for video Settings.TransitionMode = TransitionMode.NoTransition; // Add/Remove transision to video events. Chose NoTransition, AddTransition, RemoveTransition of Scanning for available transition presets for the first time may be slow Settings.AllowLoops = false; // Allow crossfades to expand beyond clip's original length Settings.ShowDialog = true; // Show dialog window or run the script with these settings without user prompt Settings.TransitionAndPresetName = ""; //Put transition and preset names here, e.g. "VEGAS Portals\\Mondrian" if you use the script non-interactively by changing Settings.ShowDialog to true // ********* Do no change anything below unless you know what you're doing Settings.Vegas = vegas; try { if (Settings.ShowDialog) { var form = new CrossFaderForm(Settings); var dialogResult = form.ShowDialog(); if (dialogResult != DialogResult.OK) { return; } } if (Settings.TransitionMode == TransitionMode.AddTransition && Settings.ShowDialog == false && string.IsNullOrEmpty(Settings.TransitionAndPresetName)) { throw new Exception("The script needs to know what transition preset to use. To apply video transitions in silent mode edit TransitionAndPresetName settings property, for example:\n\n" + "Settings.TransitionAndPresetName = \"VEGAS Portals\\\\Mondrian\";"); } if (Settings.TransitionMode == TransitionMode.AddTransition) { FindTransition(); } Timecode CrossFade = null; Timecode HalfCrossFade = null; switch (Settings.TimeUnit) { case TimeUnit.Milliseconds: CrossFade = Timecode.FromMilliseconds(Settings.CrossFadeLength); HalfCrossFade = Timecode.FromMilliseconds(Settings.CrossFadeLength / 2); break; case TimeUnit.Frames: CrossFade = Timecode.FromFrames(Settings.CrossFadeLength); HalfCrossFade = Timecode.FromFrames(Settings.CrossFadeLength / 2); break; } foreach (Track track in vegas.Project.Tracks) { foreach (TrackEvent trackEvent in track.Events) { if (trackEvent.Selected) { switch (Settings.ScriptMode) { case ScriptMode.CreateNewCrossfades: CreateCrossFades(trackEvent, track, HalfCrossFade); break; case ScriptMode.ChangeExistingCrossfades: ChangeExistingCrossFades(trackEvent, track); break; case ScriptMode.RemoveCrossfades: RemoveCrossFades(trackEvent, track); break; } if (trackEvent.IsVideo()) { switch (Settings.TransitionMode) { case TransitionMode.AddTransition: AddTransition(trackEvent); break; case TransitionMode.RemoveTransition: trackEvent.FadeIn.RemoveTransition(); break; } } } } } } catch (Exception ex) { vegas.ShowError(ex); } }
private void _updateText() { SetValue(TextProperty, Timecode.ToSMPTETimecodeString(VideoFormat)); }
public void AdjustRegionLength(Timecode LengthAdjustment) { if (LengthAdjustment < Timecode.FromNanos(0)) LengthAdjustment = Timecode.FromNanos(0); _Region.End = _Region.Position + LengthAdjustment; }
void DoBatchRender(ArrayList selectedTemplates, String basePath, RenderMode renderMode) { String outputDirectory = Path.GetDirectoryName(basePath); String baseFileName = Path.GetFileName(basePath); // make sure templates are selected if ((null == selectedTemplates) || (0 == selectedTemplates.Count)) throw new ApplicationException("No render templates selected."); // make sure the output directory exists if (!Directory.Exists(outputDirectory)) throw new ApplicationException("The output directory does not exist."); RenderStatus status = RenderStatus.Canceled; // enumerate through each selected render template foreach (RenderItem renderItem in selectedTemplates) { // construct the file name (most of it) String filename = Path.Combine(outputDirectory, FixFileName(baseFileName) + FixFileName(renderItem.Renderer.FileTypeName) + "_" + FixFileName(renderItem.Template.Name)); //ShowRenderInfo(renderItem, filename); if (RenderMode.Regions == renderMode) { int regionIndex = 0; foreach (Sony.Vegas.Region region in myVegas.Project.Regions) { String regionFilename = String.Format("{0}[{1}]{2}", filename, regionIndex.ToString(), renderItem.Extension); // Render the region status = DoRender(regionFilename, renderItem, region.Position, region.Length); if (RenderStatus.Canceled == status) break; regionIndex++; } } else { filename += renderItem.Extension; Timecode renderStart, renderLength; if (renderMode == RenderMode.Selection) { renderStart = myVegas.SelectionStart; renderLength = myVegas.SelectionLength; } else { renderStart = new Timecode(); renderLength = myVegas.Project.Length; } status = DoRender(filename, renderItem, renderStart, renderLength); } if (RenderStatus.Canceled == status) break; } }
public void AdjustRegionBounds(Timecode StartTime, Timecode EndTime) { _Region.Position = StartTime; _Region.End = EndTime; }
public void FromVegas(Vegas vegas) { Project proj = vegas.Project; foreach (Track track in proj.Tracks) { foreach (TrackEvent trackEvent in track.Events) { if (!trackEvent.Selected) { continue; } Take activeTake = trackEvent.ActiveTake; if (null == activeTake) { continue; } Media media = activeTake.Media; if (null == media) { continue; } Timecode eventStart = trackEvent.Start; Timecode eventEnd = eventStart + trackEvent.Length; Timecode takeOffset = activeTake.Offset; Timecode position; foreach (MediaMarker mm in media.Markers) { position = mm.Position + eventStart - takeOffset; if (position < eventStart || position > eventEnd) { continue; } Marker marker = new Marker(position, mm.Label); try { proj.Markers.Add(marker); } catch (Exception e) { AddError(e, mm, position); } } foreach (MediaRegion mr in media.Regions) { position = mr.Position + eventStart - takeOffset; if (position < eventStart || position > eventEnd) { continue; } Region region = new Region(position, mr.Length, mr.Label); try { proj.Regions.Add(region); } catch (Exception e) { AddError(e, mr, position); } } } } if (0 < myErrors.Count) { StringBuilder msg = new StringBuilder(); msg.Append("Some problems occured in promoting the selected media markers to the project level:\r\n"); foreach (String err in myErrors) { msg.Append("\r\n"); msg.Append(err); } MessageBox.Show(msg.ToString()); } }
/// Spacing manipulation /// private void EventPosSpaceChange(EventPositionModifyMethod Method) { List<TrackEvent> TargetEvents = myVegas.Project.GetSelectedEvents(true); if (TargetEvents.Count <= 1) { TargetEvents = GetEventsByTimeSelection(); if (TargetEvents.Count <= 1) return; } TrackEvent FirstEvent = TargetEvents[0]; TrackEvent LastEvent = TargetEvents[TargetEvents.Count - 1]; // Auto if (Method == EventPositionModifyMethod.Auto) { int _NumEvents = TargetEvents.Count; var MediaLength = new Timecode(); MediaLength = TargetEvents.Aggregate(MediaLength, (current, CurrentEvent) => current + CurrentEvent.Length); Timecode TotalTime = LastEvent.End - FirstEvent.Start; Timecode Space = TotalTime - MediaLength; Timecode MediumInterval = Timecode.FromNanos((Space.Nanos / (_NumEvents - 1))); using (var undo = new UndoBlock("Spacing: auto")) { TrackEvent prevEvent = null; for (int eventCounter = 1; eventCounter < TargetEvents.Count; eventCounter++) { TrackEvent curEvent = TargetEvents[eventCounter]; if (curEvent != null) { if (prevEvent != null) curEvent.Start = prevEvent.End + MediumInterval; } prevEvent = curEvent; } } return; } // User if (Method == EventPositionModifyMethod.User) { Timecode userInterval = FormTimeEntry.GetUserTime(); if (userInterval == null) return; using (var undo = new UndoBlock("Spacing: user")) { TrackEvent prevEvent = null; for (int eventCounter = 0; eventCounter < TargetEvents.Count; eventCounter++) { TrackEvent curEvent = TargetEvents[eventCounter]; if (curEvent != null) { if (prevEvent != null) curEvent.Start = prevEvent.End + userInterval; } prevEvent = curEvent; } } } }
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(); }
/// /// Implementation /// internal void RegionCreateFromEvents_Invoked(object sender, EventArgs e) { var eventgroups = myVegas.Project.GetEventGroups(); var regions = (myVegas.Project.Regions.Count != 0) ? new List <ScriptPortal.Vegas.Region>(myVegas.Project.Regions) : new List <ScriptPortal.Vegas.Region>(); bool selectionSet = false; if (myVegas.SelectionLength != Timecode.FromMilliseconds(0)) { if (myVegas.Cursor == myVegas.SelectionStart || myVegas.Cursor == myVegas.SelectionStart + myVegas.SelectionLength) { selectionSet = true; } } using (var undo = new UndoBlock("Create regions")) { foreach (var egrp in eventgroups) { Timecode groupStart = null; Timecode groupEnd = null; foreach (var ev in egrp) { if (groupStart == null || ev.Start < groupStart) { groupStart = ev.Start; } if (groupEnd == null || ev.End > groupEnd) { groupEnd = ev.End; } } // skip outside seletion if (selectionSet) { if (groupEnd >= (myVegas.SelectionStart + myVegas.SelectionLength) || groupStart <= myVegas.SelectionStart) { continue; } } // don't write inside existing regions if (regions.Any(reg => reg.ContainsTime(groupStart, (groupEnd - groupStart)))) { continue; } // don't surround existing regions if (regions.HasInside(groupStart, groupEnd)) { continue; } var NewRegion = new ScriptPortal.Vegas.Region(groupStart, (groupEnd - groupStart)); myVegas.Project.Regions.Add(NewRegion); } } }
public static bool HasInside(this Sony.Vegas.Region Region, Timecode Start, Timecode End) { if (Start < Region.Position && End > Region.End) return true; return false; }
private static Timecode GetTimecode(XmlAttribute valueAttribute) { double seconds = Double.Parse(valueAttribute.Value, CultureInfo.InvariantCulture); return(Timecode.FromSeconds(seconds)); }
public static bool HasInside(this IEnumerable<Sony.Vegas.Region> Regions, Timecode Start, Timecode End) { return Regions.Any(reg => reg.HasInside(Start, End)); }
/// <summary> /// Get timecode as camera timestamp /// </summary> public static void GetAsCameraTime(this Timecode timecode, out UInt64 cameratime) { cameratime = ((UInt64)(timecode.High) << 32) | timecode.Low; }
public void CreateByFrameTest(int frames, FrameRate frameRate, bool isDropFrame, string expected) { var actual = Timecode.FromFrames(frames, frameRate, isDropFrame); Assert.Equal(expected, actual.ToString()); }
private void _updateText() { Text = Timecode.ToSmpteFrames(VideoFormat).ToString(); }
public void CreateByStringTest(int expected, FrameRate frameRate, bool isDropFrame, string input) { var actual = Timecode.FromString(input, frameRate, isDropFrame); Assert.Equal(expected, actual.TotalFrames); }
public static Region FindRegion(this ScriptPortal.Vegas.Project Project, string RegionName) { return(FindRegion(Project, RegionName, Timecode.FromSeconds(0))); }
public void Render(ScriptPortal.Vegas.Vegas myVegas) { SetProgressBounds(Count); using (UndoBlock undo = new UndoBlock("Render tracks")) { for (int i = 0; i < Count; i++) { var ri = this[i]; foreach (var trk in myVegas.Project.Tracks) { trk.Mute = !ri.Tracks.Contains(trk); } // padding if (ri.RenderParams.GetParam <bool>(RenderTags.DoPadding)) { if (ri.RenderTemplate.RendererID != myVegas.Renderers.FindByName("Wave (Microsoft)").ID) { ErrorLog( String.Format( "The region {0} could not be padded. Padded rendering can only be performed on .WAV (PCM) files.", ri.Region.Label)); } else { var paddingTime = Timecode.FromSeconds(ri.PaddingSeconds); if (ri.Start - paddingTime < myVegas.Project.Ruler.StartTime) { ErrorLog(String.Format( "The region {0} could not be padded. Move your region further into the project.", ri.Region.Label)); } else { ri.Start -= paddingTime; ri.Length += paddingTime; ri.Length += paddingTime; } } } if (File.Exists(ri.FilePath) && ri.RenderParams.GetParam <bool>(RenderTags.DoReadonly)) { // check readonly var attr = File.GetAttributes(ri.FilePath); if (attr.IsSet(FileAttributes.ReadOnly)) { File.SetAttributes(ri.FilePath, attr & ~FileAttributes.ReadOnly); } } SetProgress(i); SetProgressStatus("Rendering " + ri.FilePath); RenderStatus status = myVegas.Render(ri.FilePath, ri.RenderTemplate, ri.Start, ri.Length); if (status != RenderStatus.Complete) { ErrorLog(String.Format("{0} raised error {1}", ri.FilePath, status.ToString())); } else { // file successfully rendered // strip padding if (ri.RenderParams.GetParam <bool>(RenderTags.DoPadding)) { WaveFile.StripPadding(ri.FilePath, ri.PaddingSeconds); } } } foreach (ScriptPortal.Vegas.Track trk in myVegas.Project.Tracks) { trk.Mute = false; } undo.Cancel = true; // we didn't really do anything useful. } }
public static void GetNormalizedTimeSelection(this TransportControl Transport, out Timecode Start, out Timecode End) { if (Transport.SelectionLength < Timecode.FromNanos(0)) { End = Transport.SelectionStart; Start = End + Transport.SelectionLength; } else { Start = Transport.SelectionStart; End = Start = Transport.SelectionLength; } }
public void FromVegas(Vegas vegas) { var events = vegas.Project.Tracks .SelectMany(track => track.Events) .Where(t => t.Selected) .GroupBy( t => new { StartFrameCount = t.Start.FrameCount, LengthFrameCount = t.Length.FrameCount }) .Select(grp => grp.ToList()) .ToList(); var prompt = new Form { Width = 500, Height = 110, Text = "Scrambling Parameters" }; var textLabel = new Label { Left = 10, Top = 10, Text = "Scramble size" }; var inputBox = new NumericUpDown { Left = 200, Top = 10, Width = 200, Minimum = 1, Maximum = 1000000000, Text = "" }; var confirmation = new Button { Text = "OK", Left = 200, Width = 100, Top = 40 }; confirmation.Click += (sender, e) => { prompt.DialogResult = DialogResult.OK; prompt.Close(); }; prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.Controls.Add(inputBox); inputBox.Select(); prompt.AcceptButton = confirmation; if (prompt.ShowDialog() != DialogResult.OK) { return; } var size = (int)inputBox.Value; if (size <= 0) { MessageBox.Show("Scrambling size must be > 0!"); return; } try { foreach (var e in events) { var order = new List <int>(); var startFrameCount = e[0].Start.FrameCount; var endFrameCount = e[0].End.FrameCount; var n = (int)(endFrameCount - startFrameCount); var l = n / size; if (l == 0) { continue; } if (n % size != 0) { ++l; } for (var i = 0; i < l; i++) { order.Add(i); } for (var i = 0; i < l - 1; i++) { var k = i + 1 + Random.Next(l - i - 1); var v = order[k]; order[k] = order[i]; order[i] = v; } foreach (var evt in e) { int offset; for (var i = l - 1; i > 0; i--) { var other = evt.Split(Timecode.FromFrames(i * size)); offset = order[i] > order[l - 1] ? -(size - n % size) : 0; other.Start = Timecode.FromFrames(startFrameCount + offset + order[i] * size); } offset = order[0] > order[l - 1] ? -(size - n % size) : 0; evt.Start = Timecode.FromFrames(startFrameCount + offset + order[0] * size); } } } catch (Exception e) { MessageBox.Show("Unexpected exception: " + e.Message); Debug.WriteLine(e); } }
public static string ToString(this Timecode tc, string format) { TimeSpan ts = new TimeSpan((long)tc.ToMilliseconds() * TimeSpan.TicksPerMillisecond); return(ts.ToString(format)); }
void DoBatchRender(ArrayList selectedTemplates, String basePath, RenderMode renderMode) { String outputDirectory = Path.GetDirectoryName(basePath); String baseFileName = Path.GetFileName(basePath); // make sure templates are selected if ((null == selectedTemplates) || (0 == selectedTemplates.Count)) { throw new ApplicationException("No render templates selected."); } // make sure the output directory exists if (!Directory.Exists(outputDirectory)) { throw new ApplicationException("The output directory does not exist."); } RenderStatus status = RenderStatus.Canceled; // enumerate through each selected render template foreach (RenderItem renderItem in selectedTemplates) { // construct the file name (most of it) String filename = Path.Combine(outputDirectory, FixFileName(baseFileName) + FixFileName(renderItem.Renderer.FileTypeName) + "_" + FixFileName(renderItem.Template.Name)); if (RenderMode.Regions == renderMode) { int regionIndex = 0; foreach (Sony.Vegas.Region region in myVegas.Project.Regions) { String regionFilename = String.Format("{0}[{1}]{2}", filename, regionIndex.ToString(), renderItem.Extension); // Render the region status = DoRender(regionFilename, renderItem, region.Position, region.Length); if (RenderStatus.Canceled == status) { break; } regionIndex++; } } else { filename += renderItem.Extension; Timecode renderStart, renderLength; if (renderMode == RenderMode.Selection) { renderStart = myVegas.SelectionStart; renderLength = myVegas.SelectionLength; } else { renderStart = new Timecode(); renderLength = myVegas.Project.Length; } status = DoRender(filename, renderItem, renderStart, renderLength); } if (RenderStatus.Canceled == status) { break; } } }
public static void RemoveSelection(this Vegas vegas) { vegas.Cursor += Timecode.FromMilliseconds(1); vegas.Cursor -= Timecode.FromMilliseconds(1); vegas.Project.ForEachEvent((tEvent) => tEvent.Selected = false); }
private void EventEdgeTrim(EventEdgeAdjustMethod edgeAdjustMethod, Timecode Position) { List<TrackEvent> events = myVegas.Project.GetSelectedEvents(); using (var undo = new UndoBlock("Set Event Edge")) { switch (edgeAdjustMethod) { case EventEdgeAdjustMethod.Left: foreach (var ev in events) { if (ev.Loop == false && Position <= ev.Start) // can't wrap non-looping continue; var amount = Position - ev.Start; if (Position <= ev.End) { ev.Start = ev.Start + amount; ev.End -= amount; foreach (var take in ev.Takes) take.Offset += amount; } else // wraparoo { var oldEnd = ev.End; var oldLength = ev.Length; ev.Start = oldEnd; ev.End = Position; foreach (var take in ev.Takes) take.Offset += oldLength; } } break; case EventEdgeAdjustMethod.Right: foreach (var ev in events) { if (ev.Loop == false && Position >= ev.End) continue; var amount = ev.End - Position; if (Position >= ev.Start) { ev.End -= amount; } else // wraparoo { var oldStart = ev.Start; var oldEnd = ev.End; ev.Start = Position; ev.End = oldStart; foreach (var take in ev.Takes) take.Offset -= ev.End - Position; } } break; } } }
public static bool IsSMPTE(this Timecode timecode) { return(timecode.Type == TimecodeType.SMPTE); }
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 Form2 configForm = new Form2(); for (int i = 1; i < midi.Events.Tracks; i++) { configForm.comboBox1.Items.Add(trackInfo[i]); } configForm.comboBox1.SelectedIndex = 0; Application.Run(configForm); // apply condiguration for (int i = 1; i < midi.Events.Tracks; i++) { if (trackInfo[i] == configForm.comboBox1.SelectedItem.ToString()) { midiTrack = i; } } sheetWidth = int.Parse(configForm.width); sheetPosition = int.Parse(configForm.position); sheetGap = int.Parse(configForm.gap); if (configForm.comboBox2.Text == "2/4") { sheetTempo = 2; } if (configForm.comboBox2.Text == "3/4") { sheetTempo = 3; } if (configForm.comboBox3.Text == "低音") { sheetCelf = 1; } // start processing MIDI VideoTrack[] noteTracks = new VideoTrack[100]; int trackCount = -1; int trackPointer = 0; double barStartTime = 0; double barLength = msPerQuarter * sheetTempo; foreach (MidiEvent midiEvent in midi.Events[midiTrack]) { 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; // next page while (startTime >= barStartTime + barLength) { barStartTime = barStartTime + barLength; trackPointer = 0; } // generate video events if (trackPointer > trackCount) { trackCount = trackCount + 1; noteTracks[trackCount] = vegas.Project.AddVideoTrack(); } VideoEvent videoEvent = noteTracks[trackPointer].AddVideoEvent(Timecode.FromMilliseconds(startTime), Timecode.FromMilliseconds(barStartTime + barLength - startTime)); Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0)); TrackEvent trackEvent = videoEvent as TrackEvent; trackEvent.Loop = true; TrackMotionKeyframe keyFrame = noteTracks[trackPointer].TrackMotion.InsertMotionKeyframe(Timecode.FromMilliseconds(startTime)); keyFrame.Type = VideoKeyframeType.Hold; keyFrame.Width = sheetGap * 2 * vegas.Project.Video.Width / vegas.Project.Video.Height; keyFrame.Height = sheetGap * 2; keyFrame.PositionX = -sheetWidth / 2 + sheetWidth / barLength * (startTime - barStartTime); int octave = pitch / 12; int line = pitchMap[pitch % 12]; keyFrame.PositionY = sheetPosition - sheetGap * 3 + (octave - 5) * sheetGap * 3.5 + line * sheetGap * 0.5 + sheetCelf * 12; trackPointer = trackPointer + 1; } } }
public void AdjustRegionToEvents(Timecode Tolerance) { // auto lol _Region.Position = Start - Tolerance; _Region.End = End + Tolerance; }
public void FromVegas(Vegas vegas) { myVegas = vegas; System.Collections.Generic.List <OFXDouble2DKeyframe> locations = new System.Collections.Generic.List <OFXDouble2DKeyframe>(); Tuple <Timecode, Timecode> durationTrackEvent; VideoEvent trackEvent = (VideoEvent)FindFirstSelectedEventUnderCursor(); if (trackEvent == null) { MessageBox.Show("Please select the video event on which VEGAS Bezier Masking has been applied.", "No selected event", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { durationTrackEvent = new Tuple <Timecode, Timecode>(trackEvent.Start, trackEvent.End); Effects fxs = trackEvent.Effects; bool bezierWasFound = false; foreach (Effect fx in fxs) { bezierWasFound = fx.PlugIn.UniqueID == "{Svfx:com.sonycreativesoftware:bzmasking}"; if (bezierWasFound) { OFXParameters parameter = fx.OFXEffect.Parameters; foreach (OFXParameter param in parameter) { if (param.Name == "Location_0") { OFXDouble2DParameter locationTracking = (OFXDouble2DParameter)param; locations = new List <OFXDouble2DKeyframe>(locationTracking.Keyframes); break; } } break; } } if (!bezierWasFound) { MessageBox.Show("Please apply VEGAS Bezier Masking to the video event", "VEGAS Bezier Masking not applied", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } if (locations.Count == 0) { MessageBox.Show("Please add Motion Tracking to the VEGAS Bezier Masking FX", "No tracking data", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { using (OffsetDialog offsetPrompt = new OffsetDialog()) { DialogResult result = offsetPrompt.ShowDialog(); if (result == DialogResult.OK) { VideoTrack titleTrack = myVegas.Project.AddVideoTrack(); PlugInNode textAndTitles = myVegas.Generators.GetChildByUniqueID("{Svfx:com.sonycreativesoftware:titlesandtext}"); // GetChildByName("VEGAS Titles & Text");// Timecode lengthEvent = durationTrackEvent.Item2 - durationTrackEvent.Item1; Media media = new Media(textAndTitles, "Placeholder"); media.Length = lengthEvent; VideoEvent vEvent = titleTrack.AddVideoEvent(durationTrackEvent.Item1, lengthEvent); Take take = new Take(media.Streams[0]); vEvent.Takes.Add(take); Effect fxText = media.Generator; OFXParameters parameter = fxText.OFXEffect.Parameters; foreach (OFXParameter param in parameter) { if (param.Name == "Location") { OFXDouble2DParameter locationText = (OFXDouble2DParameter)param; locationText.Keyframes.Clear(); foreach (OFXDouble2DKeyframe location in locations) { OFXDouble2D tmpValue = location.Value; tmpValue.X += offsetPrompt.X; tmpValue.Y += offsetPrompt.Y; locationText.SetValueAtTime(location.Time, tmpValue); } break; } } } } } }
public void MoveTo(Timecode Time) { foreach (TrackEvent Event in _Events) { Event.Start = Time + (Event.Start - _Region.Position); } _Region.Position = Time; }
public void FromVegas(Vegas vegas) { Project proj = vegas.Project; foreach (Track track in proj.Tracks) { foreach (TrackEvent trackEvent in track.Events) { if (!trackEvent.Selected) { continue; } Take activeTake = trackEvent.ActiveTake; if (null == activeTake) { continue; } Media media = activeTake.Media; if (null == media) { continue; } if (IsPairedAudioEvent(trackEvent, media)) { continue; } Timecode eventStart = trackEvent.Start; Timecode eventEnd = eventStart + trackEvent.Length; Timecode takeOffset = activeTake.Offset; Timecode position; foreach (MediaCommandMarker mcm in media.CommandMarkers) { position = mcm.Position + eventStart - takeOffset; if (position < eventStart || position > eventEnd) { continue; } CommandMarker commandmarker = new CommandMarker(position, mcm.CommandType, /*param*/ mcm.CommandParameter, /*comment*/ mcm.Label); try { proj.CommandMarkers.Add(commandmarker); } catch (Exception e) { AddError(e, mcm, position); } } } } if (0 < myErrors.Count) { StringBuilder msg = new StringBuilder(); msg.Append("Some problems occured in promoting the selected media command markers to the project level:\r\n"); foreach (String err in myErrors) { msg.Append("\r\n"); msg.Append(err); } MessageBox.Show(msg.ToString()); } }
private void SetCurrentMarkerOffset(TrackEvent Event, Timecode Offset) { MetaMarker mmk = Event.FindCurrentMetaMarker(); if (mmk == null) return; Event.ActiveTake.Offset = mmk.LocalMarkerOffset - Offset; }
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); } }
// perform the render. The Render method returns a member of the // RenderStatus enumeration. If it is anything other than OK, // exit the loops. This will throw an error message string if the // render does not complete successfully. RenderStatus DoRender(String filePath, RenderItem renderItem, Timecode start, Timecode length) { ValidateFilePath(filePath); // make sure the file does not already exist if (!OverwriteExistingFiles && File.Exists(filePath)) { throw new ApplicationException("File already exists: " + filePath); } // perform the render. The Render method returns // a member of the RenderStatus enumeration. If // it is anything other than OK, exit the loops. RenderStatus status = myVegas.Render(filePath, renderItem.Template, start, length); switch (status) { case RenderStatus.Complete: case RenderStatus.Canceled: break; case RenderStatus.Failed: default: StringBuilder msg = new StringBuilder("Render failed:\n"); msg.Append("\n file name: "); msg.Append(filePath); msg.Append("\n Renderer: "); msg.Append(renderItem.Renderer.FileTypeName); msg.Append("\n Template: "); msg.Append(renderItem.Template.Name); msg.Append("\n Start Time: "); msg.Append(start.ToString()); msg.Append("\n Length: "); msg.Append(length.ToString()); throw new ApplicationException(msg.ToString()); } return status; }
/// Position manipulation /// private void EventPosInterChange(EventPositionModifyMethod Method, Timecode Interval) { List<TrackEvent> selectedEvents = myVegas.Project.GetSelectedEvents(true); if (selectedEvents.Count <= 1) { selectedEvents = GetEventsByTimeSelection(); if (selectedEvents.Count <= 1) return; } TrackEvent FirstEvent = selectedEvents[0]; TrackEvent LastEvent = selectedEvents[selectedEvents.Count - 1]; if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) Interval = (Timecode.FromNanos(Interval.Nanos * 10)); // Adjust if ((Method == EventPositionModifyMethod.Adjust)) { using (var undo = new UndoBlock("Position: adjust")) { for (int EventCounter = 1; EventCounter < selectedEvents.Count; EventCounter++) { TrackEvent CurEvent = selectedEvents[EventCounter]; if (CurEvent != null) { CurEvent.Start = CurEvent.Start + Timecode.FromNanos(Interval.Nanos * EventCounter); } } } return; } // Auto if (Method == EventPositionModifyMethod.Auto) { // get some stats. Timecode MediumInterval = Timecode.FromNanos((LastEvent.Start.Nanos - FirstEvent.Start.Nanos) / (selectedEvents.Count - 1)); using (var undo = new UndoBlock("Position: auto")) { for (int EventCounter = 1; EventCounter < selectedEvents.Count - 1; EventCounter++) { TrackEvent CurEvent = selectedEvents[EventCounter]; if (CurEvent != null) { CurEvent.Start = FirstEvent.Start + Timecode.FromNanos(MediumInterval.Nanos * EventCounter); } } } return; } // User if (Method == EventPositionModifyMethod.User) { Timecode UserInterval = FormTimeEntry.GetUserTime(); if (UserInterval == null) return; using (var undo = new UndoBlock("Position: adjust")) { for (int EventCounter = 1; EventCounter < selectedEvents.Count; EventCounter++) { TrackEvent CurEvent = selectedEvents[EventCounter]; if (CurEvent != null) { CurEvent.Start = FirstEvent.Start + Timecode.FromNanos(UserInterval.Nanos * EventCounter); } } } } }