// // Adds a given media fileName to the current track at the specified cursorPosition // void InsertFileAt(Vegas vegas, string fileName, Timecode cursorPosition) { VideoEvent videoEvent = null; Media media = new Media(fileName); VideoTrack videoTrack = FindSelectedVideoTrack(vegas.Project); videoEvent = videoTrack.AddVideoEvent(cursorPosition, Timecode.FromSeconds(stillLength)); Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0)); videoEvent.MaintainAspectRatio = false; VideoMotionKeyframe key1 = new VideoMotionKeyframe(Timecode.FromSeconds(stillLength)); videoEvent.VideoMotion.Keyframes.Add(key1); VideoMotionKeyframe key0 = videoEvent.VideoMotion.Keyframes[0]; key0.ScaleBy(new VideoMotionVertex(initialScale, initialScale)); key0.RotateBy(initialRotationRadians * (double)rnd.Next(-1, 1)); key0.MoveBy(new VideoMotionVertex((float)rnd.Next(-15, 15), (float)rnd.Next(-20, 20))); PlugInNode plugIn = vegas.Transitions.FindChildByName(desiredTransitions[rnd.Next(0, desiredTransitions.Length - 1)]); Effect fx = new Effect(plugIn); videoEvent.FadeIn.Transition = fx; }
private VideoEvent createText(Media media, VideoTrack track, TrackEvent eventBelow) { VideoEvent txtEvent = track.AddVideoEvent(eventBelow.Start, eventBelow.End - eventBelow.Start); Take take = txtEvent.AddTake(media.GetVideoStreamByIndex(0)); return(txtEvent); }
// 画像トラックの作り方 // https://www.youtube.com/watch?v=GdrXo_HiNZM TrackEvent AddMedia(Project project, string mediaPath, int trackIndex, Timecode start, Timecode length) { #if false Media media = Media.CreateInstance(project, mediaPath); Track track = project.Tracks[trackIndex]; if (track.MediaType == MediaType.Video) { VideoTrack videoTrack = (VideoTrack)track; VideoEvent videoEvent = videoTrack.AddVideoEvent(start, length); Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0)); return(videoEvent); } // サンプル:画像はこれで追加できる //AddMediaImage(vegas.Project, @"C:\Users\Administrator\Desktop\mouse.png", 0, ); { Media media = Media.CreateInstance(vegas.Project, @"C:\Users\Administrator\Desktop\mouse.png"); Track track = vegas.Project.Tracks[0]; if (track.MediaType == MediaType.Video) { VideoTrack videoTrack = (VideoTrack)track; VideoEvent videoEvent = videoTrack.AddVideoEvent(Timecode.FromSeconds(1), Timecode.FromSeconds(5)); Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0)); return(videoEvent); } } #endif return(null); }
public void FromVegas(Vegas vegas) { foreach (Track track in vegas.Project.Tracks) { if (track.IsValid() && track.IsVideo() && track.Selected) { foreach (TrackEvent trackEvent in track.Events) { if (trackEvent.IsVideo()) { VideoEvent videoEvent = (VideoEvent)trackEvent; string currentMediaPath = videoEvent.ActiveTake.MediaPath; string pathExtension = Path.GetExtension(currentMediaPath); if (pathExtension.Equals(findExtension, StringComparison.OrdinalIgnoreCase)) { string replacementPath = Path.ChangeExtension(currentMediaPath, replaceExtension); Media media = new Media(replacementPath); MediaStream mediaStream = media.GetVideoStreamByIndex(0); Timecode oldTakeOffset = videoEvent.ActiveTake.Offset; videoEvent.AddTake(mediaStream, true); videoEvent.ActiveTake.Offset = oldTakeOffset; } } } } } }
// // Adds a given media fileName to the current track at the specified cursorPosition // void InsertFileAt(Vegas vegas, string fileName, Timecode cursorPosition) { PlugInNode plugIn = vegas.Transitions.FindChildByName("VEGAS Linear Wipe"); VideoEvent videoEvent = null; Media media = new Media(fileName); VideoTrack videoTrack = FindSelectedVideoTrack(vegas.Project); videoEvent = videoTrack.AddVideoEvent(cursorPosition, Timecode.FromSeconds(stillLength)); Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0)); videoEvent.MaintainAspectRatio = false; VideoMotionKeyframe key1 = new VideoMotionKeyframe(Timecode.FromSeconds(stillLength)); videoEvent.VideoMotion.Keyframes.Add(key1); VideoMotionKeyframe key0 = videoEvent.VideoMotion.Keyframes[0]; key0.ScaleBy(new VideoMotionVertex(initialScale, initialScale)); key0.RotateBy(initialRotationRadians); Effect fx = new Effect(plugIn); videoEvent.FadeIn.Transition = fx; fx.Preset = "Top-Down, Soft Edge"; }
// -------------------------------------------------------------------- // パーツを連結 // -------------------------------------------------------------------- private void ConcatParts(List <VideoPart> oVideoParts, Double oAudioLen, Double oInterval) { // トラック作成 VideoTrack aVideoTrack = new VideoTrack(mVegas.Project, 0, TRACK_NAME); mVegas.Project.Tracks.Add(aVideoTrack); // パーツ使用数 Int32 aUseNum = (Int32)Math.Ceiling(oAudioLen / oInterval); PartsUseMode aPartsUseMode; if (oVideoParts.Count >= aUseNum * 3) { aPartsUseMode = PartsUseMode.OnceGroup; } else if (oVideoParts.Count >= aUseNum) { aPartsUseMode = PartsUseMode.Once; } else { aPartsUseMode = PartsUseMode.Reuse; } // パーツ追加 Random aRandom = new Random(); for (Int32 i = 0; i < aUseNum; i++) { // パーツ番号 Int32 aPartsIndex = aRandom.Next(0, oVideoParts.Count); // パーツ VideoEvent aVideoEvent = aVideoTrack.AddVideoEvent(new Timecode(i * oInterval), new Timecode(oInterval)); Take aTake = aVideoEvent.AddTake(oVideoParts[aPartsIndex].VideoStream); aTake.Offset = oVideoParts[aPartsIndex].Offset; // パーツ廃棄 switch (aPartsUseMode) { case PartsUseMode.Once: oVideoParts.RemoveAt(aPartsIndex); break; case PartsUseMode.OnceGroup: for (Int32 j = aPartsIndex + 1; j >= aPartsIndex - 1; j--) { if (0 <= j && j < oVideoParts.Count) { oVideoParts.RemoveAt(j); } } break; } } }
// Adds media event to track at specified start TrackEvent AddMedia(Project project, string mediaPath, int trackIndex, Timecode start, Timecode length) { Media media = Media.CreateInstance(project, mediaPath); Track track = project.Tracks[trackIndex]; TrackEvent currentTrackEvent = null; if (track.MediaType == MediaType.Video) { // If cursor isn't over an event on the track, simply add it to track if ((currentTrackEvent = FindTrack(project, start, trackIndex)) is null) { ; } // If cursor is over an event on the track, remove the portion of that event from where // the cursor is to where the next event starts else { // When an event is split, the left half is the original event, the right split is a new event TrackEvent rightSplit = currentTrackEvent.Split(start - currentTrackEvent.Start); // offset from start // rightSplit is null when you try the split right where a track begins, this if // statement handles that if (rightSplit is null) { length = currentTrackEvent.Length; track.Events.Remove(currentTrackEvent); } else { length = rightSplit.Length; // set new length so new video track will fill in old tracks place track.Events.Remove(rightSplit); } } VideoTrack videoTrack = (VideoTrack)track; VideoEvent videoEvent = videoTrack.AddVideoEvent(start, length); Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0)); return(videoEvent); } else { return(null); } }
public void FromVegas(Vegas vegas) { foreach (Track track in vegas.Project.Tracks) { if (track.IsValid() && track.IsVideo()) { foreach (TrackEvent trackEvent in track.Events) { if (trackEvent.IsVideo()) { VideoEvent videoEvent = (VideoEvent)trackEvent; //has single take if (videoEvent.Takes.Count == 1) { string currentMediaPath = videoEvent.ActiveTake.MediaPath; string pathExtension = Path.GetExtension(currentMediaPath); //has find extension if (pathExtension.Equals(findExtension, StringComparison.OrdinalIgnoreCase)) { string replacementPath = Path.ChangeExtension(currentMediaPath, replaceExtension); Media media = new Media(replacementPath); MediaStream mediaStream = media.GetVideoStreamByIndex(0); Timecode oldTakeOffset = videoEvent.ActiveTake.Offset; //add a new take, without setting as active Take addedTake = videoEvent.AddTake(mediaStream, false); addedTake.Offset = oldTakeOffset; addedTake.Name += "(AVI)"; } } } } } } }
public void FromVegas(Vegas vegas) { Media media = vegas.Project.MediaPool.AddMedia(Script.Args.ValueOf("media")); foreach (MediaStream stream in media.Streams) { if (stream is VideoStream) { VideoTrack t = vegas.Project.AddVideoTrack(); VideoEvent e = t.AddVideoEvent(new Timecode(), media.Length); e.ResampleMode = VideoResampleMode.Disable; e.AddTake(stream); } else if (stream is AudioStream) { AudioTrack t = vegas.Project.AddAudioTrack(); AudioEvent e = t.AddAudioEvent(new Timecode(), media.Length); e.AddTake(stream); } } vegas.SaveProject(Script.Args.ValueOf("output")); vegas.Exit(); }
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 void FromVegas(Vegas vegas) { try { _vegas = vegas; ScriptArgs args = Script.Args; if (args.Count > 0) { _closeonfinish = System.Convert.ToBoolean(args.ValueOf("closeonfinish") ?? "false"); _savewhendone = System.Convert.ToBoolean(args.ValueOf("savewhendone") ?? "false"); _makeveg = System.Convert.ToBoolean(args.ValueOf("makeveg") ?? "false"); _file = args.ValueOf("file"); } else { var dialog = new OpenFileDialog { Filter = ".srt files (*.srt)|*.srt", CheckPathExists = true, InitialDirectory = vegas.Project.FilePath }; DialogResult result = dialog.ShowDialog(); vegas.UpdateUI(); if (result == DialogResult.OK) { _file = Path.GetFullPath(dialog.FileName); } else { return; } } if (_makeveg) { Media media = vegas.Project.MediaPool.AddMedia(Script.Args.ValueOf("media")); foreach (MediaStream stream in media.Streams) { if (stream is VideoStream) { VideoTrack t = vegas.Project.AddVideoTrack(); VideoEvent e = t.AddVideoEvent(new Timecode(), media.Length); e.ResampleMode = VideoResampleMode.Disable; e.AddTake(stream); } else if (stream is AudioStream) { AudioTrack t = vegas.Project.AddAudioTrack(); AudioEvent e = t.AddAudioEvent(new Timecode(), media.Length); e.AddTake(stream); } } vegas.SaveProject(Script.Args.ValueOf("output")); } using (FileStream fs = new FileStream(_file, FileMode.Open, FileAccess.Read)) using (StreamReader stream = new StreamReader(fs)) { while (!stream.EndOfStream) { string line = stream.ReadLine(); if (Regex.IsMatch(line, "^[0-9]+$")) { line = stream.ReadLine(); if (Regex.IsMatch(line, "^" + SRT_TIME_PATTERN + " --> " + SRT_TIME_PATTERN + "$")) { MatchCollection stamps = Regex.Matches(line, SRT_TIME_PATTERN); TimeSpan s = TimeSpan.ParseExact(stamps[0].Value, SRT_TIME_FORMAT, null); TimeSpan e = TimeSpan.ParseExact(stamps[1].Value, SRT_TIME_FORMAT, null); string t = string.Empty; while (!stream.EndOfStream) { line = stream.ReadLine(); if (!string.IsNullOrEmpty(line)) { if (!string.IsNullOrEmpty(t)) { t += "[br]"; } t += line; } else { break; } } Region r = Convert(s, e, t); if (r != null) { vegas.Project.Regions.Add(r); } } } } } if (_savewhendone) { vegas.SaveProject(); } if (_closeonfinish) { vegas.Exit(); } } catch (VegasException e) { Vegas.COM.ShowError(e.Title, e.Message); } }
public void FromVegas(Vegas vegas) { var start = vegas.Transport.LoopRegionStart; var length = vegas.Transport.LoopRegionLength; try { var frameRate = vegas.Project.Video.FrameRate; var frameRateInt = (int)Math.Round(frameRate * 1000); var scriptDirectory = Path.GetDirectoryName(Script.File); if (scriptDirectory == null) { MessageBox.Show("Couldn't get script directory path!"); return; } var xvidPath = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); if (string.IsNullOrEmpty(xvidPath)) { xvidPath = Environment.GetEnvironmentVariable("ProgramFiles"); } if (string.IsNullOrEmpty(xvidPath)) { MessageBox.Show("Couldn't get Xvid install path!"); return; } xvidPath += @"\Xvid\uninstall.exe"; if (!File.Exists(xvidPath)) { MessageBox.Show( "Xvid codec not installed. The script will install it now and may ask for admin access to install it."); var xvid = new Process { StartInfo = { UseShellExecute = true, FileName = Path.Combine(scriptDirectory, "_internal", "xvid", "xvid.exe"), WorkingDirectory = Path.Combine(scriptDirectory,"_internal"), Arguments = "--unattendedmodeui none --mode unattended --AutoUpdater no --decode_divx DIVX --decode_3ivx 3IVX --decode_divx DIVX --decode_other MPEG-4", CreateNoWindow = true, Verb = "runas" } }; try { xvid.Start(); } catch (Win32Exception e) { if (e.NativeErrorCode == 1223) { MessageBox.Show("Admin privilege for Xvid installation refused."); return; } throw; } xvid.WaitForExit(); GetStandardTemplates(vegas); GetTemplate(vegas, frameRateInt); MessageBox.Show( "Xvid installed and render template generated for the current frame rate. Please restart Sony Vegas and run the script again."); return; } var template = GetTemplate(vegas, frameRateInt); if (template == null) { GetStandardTemplates(vegas); GetTemplate(vegas, frameRateInt); MessageBox.Show( "Render template generated for the current frame rate. Please restart Sony Vegas and run the script again."); return; } var frameCount = (string)Registry.GetValue( "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets", "FrameCount", ""); var defaultCount = 1; if (frameCount != "") { try { var value = int.Parse(frameCount); if (value > 0) { defaultCount = value; } } catch (Exception) { // ignore } } var prompt = new Form { Width = 500, Height = 140, Text = "Datamoshing Parameters" }; var textLabel = new Label { Left = 10, Top = 10, Text = "Frame count" }; var inputBox = new NumericUpDown { Left = 200, Top = 10, Width = 200, Minimum = 1, Maximum = 1000000000, Value = defaultCount }; var textLabel2 = new Label { Left = 10, Top = 40, Text = "Frames repeats" }; var inputBox2 = new NumericUpDown { Left = 200, Top = 40, Width = 200, Value = 1, Minimum = 1, Maximum = 1000000000, Text = "" }; var confirmation = new Button { Text = "OK", Left = 200, Width = 100, Top = 70 }; confirmation.Click += (sender, e) => { prompt.DialogResult = DialogResult.OK; prompt.Close(); }; prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.Controls.Add(inputBox); prompt.Controls.Add(textLabel2); prompt.Controls.Add(inputBox2); inputBox2.Select(); prompt.AcceptButton = confirmation; if (prompt.ShowDialog() != DialogResult.OK) { return; } var size = (int)inputBox.Value; var repeat = (int)inputBox2.Value; if (repeat <= 0) { MessageBox.Show("Frames repeats must be > 0!"); return; } if (length.FrameCount < size) { MessageBox.Show("The selection must be as long as the frame count!"); return; } if (start.FrameCount < 1) { MessageBox.Show("The selection mustn't start on the first frame of the project!"); return; } if (defaultCount != size) { Registry.SetValue( "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets", "FrameCount", size.ToString(), RegistryValueKind.String); } VideoTrack videoTrack = null; for (var i = vegas.Project.Tracks.Count - 1; i >= 0; i--) { videoTrack = vegas.Project.Tracks[i] as VideoTrack; if (videoTrack != null) { break; } } AudioTrack audioTrack = null; for (var i = 0; i < vegas.Project.Tracks.Count; i++) { audioTrack = vegas.Project.Tracks[i] as AudioTrack; if (audioTrack != null) { break; } } if (videoTrack == null && audioTrack == null) { MessageBox.Show("No tracks found!"); return; } var changed = false; var finalFolder = (string)Registry.GetValue( "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets", "ClipFolder", ""); while (string.IsNullOrEmpty(finalFolder) || !Directory.Exists(finalFolder)) { MessageBox.Show("Select the folder to put generated datamoshed clips into."); changed = true; var dialog = new CommonOpenFileDialog { IsFolderPicker = true, EnsurePathExists = true, EnsureFileExists = false, AllowNonFileSystemItems = false, DefaultFileName = "Select Folder", Title = "Select the folder to put generated datamoshed clips into" }; if (dialog.ShowDialog() != CommonFileDialogResult.Ok) { MessageBox.Show("No folder selected"); return; } finalFolder = dialog.FileName; } if (changed) { Registry.SetValue( "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets", "ClipFolder", finalFolder, RegistryValueKind.String); } var path = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); var pathEncoded = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); var pathDatamoshedBase = Path.Combine(finalFolder, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8)); var pathDatamoshed = pathDatamoshedBase + ".avi"; var pathEncodedEscape = pathEncoded.Replace("\\", "/"); var pathDatamoshedEscape = pathDatamoshed.Replace("\\", "/"); var renderArgs = new RenderArgs { OutputFile = path, Start = Timecode.FromFrames(start.FrameCount - 1), Length = Timecode.FromFrames(length.FrameCount + 1), RenderTemplate = template }; var status = vegas.Render(renderArgs); if (status != RenderStatus.Complete) { MessageBox.Show("Unexpected render status: " + status); return; } string[] datamoshConfig = { "var input=\"" + pathEncodedEscape + "\";", "var output=\"" + pathDatamoshedEscape + "\";", "var size=" + size + ";", "var repeat=" + repeat + ";" }; File.WriteAllLines(Path.Combine(scriptDirectory, "_internal", "config_datamosh.js"), datamoshConfig); var encode = new Process { StartInfo = { UseShellExecute = false, FileName = Path.Combine(scriptDirectory, "_internal", "ffmpeg", "ffmpeg.exe"), WorkingDirectory = Path.Combine(scriptDirectory, "_internal"), Arguments = "-y -hide_banner -nostdin -i \"" + path + "\" -c:v libxvid -q:v 1 -g 1M -flags +mv4+qpel -mpeg_quant 1 -c:a copy \"" + pathEncoded + "\"", RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; encode.Start(); var output = encode.StandardOutput.ReadToEnd(); var error = encode.StandardError.ReadToEnd(); Debug.WriteLine(output); Debug.WriteLine("---------------------"); Debug.WriteLine(error); encode.WaitForExit(); File.Delete(path); File.Delete(path + ".sfl"); var datamosh = new Process { StartInfo = { UseShellExecute = false, FileName = Path.Combine(scriptDirectory, "_internal", "avidemux", "avidemux2_cli.exe"), WorkingDirectory = Path.Combine(scriptDirectory, "_internal"), Arguments = "--nogui --run avidemux_datamosh.js", RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; datamosh.Start(); datamosh.StandardInput.WriteLine("n"); output = datamosh.StandardOutput.ReadToEnd(); error = datamosh.StandardError.ReadToEnd(); Debug.WriteLine(output); Debug.WriteLine("---------------------"); Debug.WriteLine(error); datamosh.WaitForExit(); File.Delete(pathEncoded); File.Delete(pathEncoded + ".sfl"); var media = vegas.Project.MediaPool.AddMedia(pathDatamoshed); media.TimecodeIn = Timecode.FromFrames(1); VideoEvent videoEvent = null; if (videoTrack != null) { videoEvent = videoTrack.AddVideoEvent(start, Timecode.FromFrames(1 + length.FrameCount + (repeat - 1) * size)); videoEvent.AddTake(media.GetVideoStreamByIndex(0)); } AudioEvent audioEvent = null; if (audioTrack != null) { audioEvent = audioTrack.AddAudioEvent(start, Timecode.FromFrames(1 + length.FrameCount + (repeat - 1) * size)); audioEvent.AddTake(media.GetAudioStreamByIndex(0)); } if (videoTrack != null && audioTrack != null) { var group = new TrackEventGroup(); vegas.Project.Groups.Add(group); group.Add(videoEvent); group.Add(audioEvent); } } catch (Exception e) { MessageBox.Show("Unexpected exception: " + e.Message); Debug.WriteLine(e); } }
public static void AddElement(ElementStep elementStep) { if (!elementStep.Selector.IsValid() || elementStep.Selector.ElementType == ElementType.None) { return; } if (elementStep.Selector.ElementType == ElementType.Event) { Track track = SelectorService.GetTrack(elementStep.Selector); var trackRegEx = new Regex(elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); Media media = MainContainer.Vegas.Project.MediaPool.Cast <Media>().FirstOrDefault(x => trackRegEx.IsMatch(Path.GetFileName(x.FilePath))); if (elementStep.Selector.IsAudio() && media.Streams.Any(x => x.MediaType == MediaType.Audio)) { TrackEvent trackEvent = new AudioEvent( Timecode.FromString(elementStep.DataPropertyList[DataPropertyHolder.TIMECODE].Value), media.Length, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); track.Events.Add(trackEvent); trackEvent.AddTake(media.Streams[0], true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); } if (elementStep.Selector.IsVideo() && media.Streams.Any(x => x.MediaType == MediaType.Video)) { TrackEvent trackEvent = new VideoEvent(Timecode.FromString(elementStep.DataPropertyList[DataPropertyHolder.TIMECODE].Value), media.Length, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); if (media.Streams.Any(x => x.MediaType == MediaType.Audio)) { elementStep.Selector.ElementMediaType = ElementMediaType.Audio; AudioTrack syncAudioTrack = SelectorService.GetTrack(elementStep.Selector) as AudioTrack; MediaStream audioStream = media.Streams.FirstOrDefault(x => x.MediaType == MediaType.Audio); MediaStream videoStream = media.Streams.FirstOrDefault(x => x.MediaType == MediaType.Video); var audioEvent = new AudioEvent( Timecode.FromString(elementStep.DataPropertyList[DataPropertyHolder.TIMECODE].Value), media.Length, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); track.Events.Add(trackEvent); trackEvent.AddTake(videoStream, true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); syncAudioTrack.Events.Add(audioEvent); audioEvent.AddTake(audioStream, true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); } else { track.Events.Add(trackEvent); trackEvent.AddTake(media.Streams[0], true, elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value); } } } if (elementStep.Selector.ElementType == ElementType.Track) { if (elementStep.Selector.IsAudio()) { MainContainer.Vegas.Project.AddAudioTrack().Name = elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value; } if (elementStep.Selector.IsVideo()) { MainContainer.Vegas.Project.AddVideoTrack().Name = elementStep.DataPropertyList[DataPropertyHolder.RESOURCE_NAME].Value; } } }
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 FromVegas(Vegas vegas) { var start = vegas.Transport.LoopRegionStart; var length = vegas.Transport.LoopRegionLength; try { var frameRate = vegas.Project.Video.FrameRate; var frameRateInt = (int)Math.Round(frameRate * 1000); var scriptDirectory = Path.GetDirectoryName(Script.File); if (scriptDirectory == null) { MessageBox.Show("Couldn't get script directory path!"); return; } var template = GetTemplate(vegas, frameRateInt); if (template == null) { GetStandardTemplates(vegas); GetTemplate(vegas, frameRateInt); MessageBox.Show( "Render template generated for the current frame rate. Please restart Sony Vegas and run the script again."); return; } VideoTrack videoTrack = null; for (var i = vegas.Project.Tracks.Count - 1; i >= 0; i--) { videoTrack = vegas.Project.Tracks[i] as VideoTrack; if (videoTrack != null) { break; } } AudioTrack audioTrack = null; for (var i = 0; i < vegas.Project.Tracks.Count; i++) { audioTrack = vegas.Project.Tracks[i] as AudioTrack; if (audioTrack != null) { break; } } if (videoTrack == null && audioTrack == null) { MessageBox.Show("No tracks found!"); return; } var changed = false; var finalFolder = (string)Registry.GetValue( "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets", "RenderClipFolder", ""); while (string.IsNullOrEmpty(finalFolder) || !Directory.Exists(finalFolder)) { MessageBox.Show("Select the folder to put generated rendered clips into.\n" + "(As they are stored uncompressed with alpha, they can take a lot of space (think 1 GB/minute). " + "Choose a location with a lot of available space and go remove some clips there if you need space.)"); changed = true; var dialog = new CommonOpenFileDialog { IsFolderPicker = true, EnsurePathExists = true, EnsureFileExists = false, AllowNonFileSystemItems = false, DefaultFileName = "Select Folder", Title = "Select the folder to put generated rendered clips into" }; if (dialog.ShowDialog() != CommonFileDialogResult.Ok) { MessageBox.Show("No folder selected"); return; } finalFolder = dialog.FileName; } if (changed) { Registry.SetValue( "HKEY_CURRENT_USER\\SOFTWARE\\Sony Creative Software\\Custom Presets", "RenderClipFolder", finalFolder, RegistryValueKind.String); } var path = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); var pathEncoded = Path.Combine(vegas.TemporaryFilesPath, Path.GetFileNameWithoutExtension(vegas.Project.FilePath) + "-" + Guid.NewGuid().ToString("B").ToUpper().Substring(1, 8) + ".avi"); var renderArgs = new RenderArgs { OutputFile = path, Start = Timecode.FromFrames(start.FrameCount), Length = Timecode.FromFrames(length.FrameCount), RenderTemplate = template }; var status = vegas.Render(renderArgs); if (status != RenderStatus.Complete) { MessageBox.Show("Unexpected render status: " + status); return; } File.Delete(pathEncoded + ".sfl"); var media = vegas.Project.MediaPool.AddMedia(path); VideoEvent videoEvent = null; if (videoTrack != null) { videoEvent = videoTrack.AddVideoEvent(start, length); ((VideoStream)videoEvent.AddTake(media.GetVideoStreamByIndex(0)).MediaStream).AlphaChannel = VideoAlphaType.Straight; } AudioEvent audioEvent = null; if (audioTrack != null) { audioEvent = audioTrack.AddAudioEvent(start, length); audioEvent.AddTake(media.GetAudioStreamByIndex(0)); } if (videoTrack != null && audioTrack != null) { var group = new TrackEventGroup(); vegas.Project.Groups.Add(group); group.Add(videoEvent); group.Add(audioEvent); } } catch (Exception e) { MessageBox.Show("Unexpected exception: " + e.Message); Debug.WriteLine(e); } }
public void FromVegas(Vegas vegas) { // 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 ConfigForm configForm = new ConfigForm(); for (int i = 0; i < midi.Events.Tracks; i++) { configForm.comboBoxTrack.Items.Add(trackInfo[i]); } configForm.comboBoxTrack.SelectedIndex = 0; Application.Run(configForm); // apply configuration aconfig = configForm.checkBoxA.Checked; aconfigNoTune = configForm.checkBoxNoTune.Checked; vconfig = configForm.checkBoxV.Checked; vconfigAutoFlip = configForm.checkBoxFlip.Checked; vconfigStartSize = configForm.hScrollBar1.Value; vconfigEndSize = configForm.hScrollBar2.Value; vconfigFadein = configForm.hScrollBar4.Value; vconfigFadeout = configForm.hScrollBar3.Value; aconfigBasePitch = pitchMap[configForm.comboBoxA1.SelectedItem.ToString() + configForm.comboBoxA2.SelectedItem.ToString()]; for (int i = 0; i < midi.Events.Tracks; i++) { if (trackInfo[i] == configForm.comboBoxTrack.SelectedItem.ToString()) { aconfigTrack = i; } } configStartTime = Convert.ToDouble(configForm.startT) * 1000; configEndTime = Convert.ToDouble(configForm.endT) * 1000; // start processing MIDI VideoTrack vTrack = vegas.Project.AddVideoTrack(); AudioTrack[] aTracks = new AudioTrack[20]; double vTrackPosition = 0; int vTrackDirection = 1; double[] aTrackPositions = new double[20]; aTracks[0] = vegas.Project.AddAudioTrack(); aTrackPositions[0] = 0; int aTrackCount = 1; foreach (MidiEvent midiEvent in midi.Events[aconfigTrack]) { 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; int trackIndex = 0; if (startTime < configStartTime) { continue; } if (startTime > configEndTime) { break; } // generate audio events if (aconfig == true) { while (startTime < aTrackPositions[trackIndex]) { trackIndex++; if (trackIndex == aTrackCount) { aTrackCount++; aTracks[trackIndex] = vegas.Project.AddAudioTrack(); } } AudioEvent audioEvent = aTracks[trackIndex].AddAudioEvent(Timecode.FromMilliseconds(startTime), Timecode.FromMilliseconds(duration)); Take take = audioEvent.AddTake(media.GetAudioStreamByIndex(0)); aTrackPositions[trackIndex] = startTime + duration; TrackEvent trackEvent = audioEvent as TrackEvent; trackEvent.PlaybackRate = mediaLength / duration; trackEvent.Loop = false; // apply pitch shifting if (aconfigNoTune == false) { int pitchDelta = pitch - aconfigBasePitch; if (pitchDelta > 0) { while (pitchDelta > 12) { PlugInNode plugIn0 = vegas.AudioFX.FindChildByName("Pitch Shift"); Effect effect0 = new Effect(plugIn0); audioEvent.Effects.Add(effect0); effect0.Preset = "12"; pitchDelta -= 12; } PlugInNode plugIn = vegas.AudioFX.FindChildByName("Pitch Shift"); Effect effect = new Effect(plugIn); audioEvent.Effects.Add(effect); effect.Preset = pitchDelta.ToString(); } else { while (pitchDelta < -12) { PlugInNode plugIn0 = vegas.AudioFX.FindChildByName("Pitch Shift"); Effect effect0 = new Effect(plugIn0); audioEvent.Effects.Add(effect0); effect0.Preset = "-12"; pitchDelta += 12; } PlugInNode plugIn = vegas.AudioFX.FindChildByName("Pitch Shift"); Effect effect = new Effect(plugIn); audioEvent.Effects.Add(effect); effect.Preset = pitchDelta.ToString(); } } } // generate video events if (vconfig == true) { vTrackPosition = startTime + duration; VideoEvent videoEvent = vTrack.AddVideoEvent(Timecode.FromMilliseconds(startTime), Timecode.FromMilliseconds(duration)); Take take = videoEvent.AddTake(media.GetVideoStreamByIndex(0)); TrackEvent trackEvent = videoEvent as TrackEvent; trackEvent.PlaybackRate = mediaLength / duration; trackEvent.Loop = false; videoEvent.FadeIn.Length = Timecode.FromMilliseconds(duration * vconfigFadein / 100); videoEvent.FadeOut.Length = Timecode.FromMilliseconds(duration * vconfigFadeout / 100); VideoMotionKeyframe key0 = videoEvent.VideoMotion.Keyframes[0]; VideoMotionKeyframe key1 = new VideoMotionKeyframe(Timecode.FromMilliseconds(duration)); videoEvent.VideoMotion.Keyframes.Add(key1); key0.ScaleBy(new VideoMotionVertex((vconfigStartSize / 100) * vTrackDirection, (vconfigStartSize / 100))); key1.ScaleBy(new VideoMotionVertex((vconfigEndSize / 100) * vTrackDirection, (vconfigEndSize / 100))); if (vconfigAutoFlip == true) { vTrackDirection *= -1; } } } } }
private void importCallback(object sender, EventArgs e) { LogWriter.LogWrite("Callback"); var importOptions = e as ImportEventArgs; using (var undo = new UndoBlock(moduleName)) { try { var frameOffsetInMs = (1000 / vegas.Project.Video.FrameRate) * importOptions.FrameOffset; var beatLengthInS = 60 / selectedFlp.Tempo; var ppqLengthInS = beatLengthInS / selectedFlp.Ppq; PlugInNode solidColor = vegas.Generators.GetChildByUniqueID("{Svfx:com.sonycreativesoftware:solidcolor}"); vegas.Project.Markers.Clear(); List <List <FullTrackTimes> > fullTrackTimesList = new List <List <FullTrackTimes> >(); foreach (int i in importOptions.SelectedIndices) { List <FullTrackTimes> fullTrackTimes = new List <FullTrackTimes>(); foreach (var j in selectedFlp.Tracks[i].Items) { if (j is PatternPlaylistItem) { var patternItem = j as PatternPlaylistItem; foreach (Channel channel in patternItem.Pattern.Notes.Keys) { foreach (Note note in patternItem.Pattern.Notes[channel]) { if (note.Position < patternItem.StartOffset) { continue; } if (note.Position > patternItem.Length) { continue; } var noteStartPpq = patternItem.Position + (note.Position - patternItem.StartOffset); var startInMs = noteStartPpq * ppqLengthInS * 1000; var noteEndInMs = note.Length * ppqLengthInS * 1000; startInMs = (frameOffsetInMs + startInMs < 0) ? (int)(frameOffsetInMs + startInMs) : (int)startInMs; noteEndInMs = (frameOffsetInMs + noteEndInMs < 0) ? (int)(frameOffsetInMs + noteEndInMs) : (int)noteEndInMs; fullTrackTimes.Add(new FullTrackTimes(startInMs, noteEndInMs)); } } } //if(j is ChannelPlaylistItem) //{ // var channelItem = j as ChannelPlaylistItem; // if(channelItem.Channel.Data is GeneratorData) // { // var audioStartPpq = channelItem.Position; // var startInMs = audioStartPpq * ppqLengthInS * 1000; // var audioEndPpq = audioStartPpq + channelItem.Length; // var noteEndInMs = audioEndPpq * ppqLengthInS * 1000; // fullTrackTimes.Add(); // } //} } fullTrackTimesList.Add(fullTrackTimes); } foreach (var trackTimes in fullTrackTimesList) { if (importOptions.ImportType == "Solid color") { Media solidColorMedia = Media.CreateInstance(vegas.Project, solidColor); VideoTrack v = vegas.Project.AddVideoTrack(); foreach (var fullTrackTimes in trackTimes) { if (importOptions.ImportType == "Solid color") { VideoEvent ve = v.AddVideoEvent(new Timecode(fullTrackTimes.start), new Timecode(fullTrackTimes.end)); //ve. ve.AddTake(solidColorMedia.Streams[0]); } } } else if (importOptions.ImportType == "Marker") { foreach (var fullTrackTimes in trackTimes) { if (importOptions.ImportType == "Marker") { vegas.Project.Markers.Add(new Marker(new Timecode(fullTrackTimes.start))); } } } } } catch (Exception err) { LogWriter.LogWrite(err.ToString()); throw err; } } }