public static bool Verify(InstanceDeclaration instance) { bool result = true; XmlNodeList list = instance.Node.SelectNodes("ea:Pivot", instance.Document.NamespaceManager); Dictionary <uint, string> hashMap = new Dictionary <uint, string>(); foreach (XmlNode pivot in list) { string name = pivot.Attributes["Name"]?.Value; if (string.IsNullOrEmpty(name)) { _tracer.TraceError("W3DHierarchy {0} has a pivot without a name.", instance.Node.Attributes["id"].Value); result = false; } uint hash = HashProvider.GetCaseInsensitiveSymbolHash(name); if (hashMap.ContainsKey(hash)) { _tracer.TraceError("W3DHierarchy {0} has two pivots ('{1}' and '{2}') sharing a common hash", instance.Node.Attributes["id"].Value, hashMap[hash], name); result = false; } else { hashMap.Add(hash, name); } } return(result); }
/// <summary> /// Initializes the control. /// </summary> public void Initialize(Session session, NodeId typeId) { ItemsLV.Items.Clear(); AdjustColumns(); if (session == null) { return; } ILocalNode root = session.NodeCache.Find(typeId) as ILocalNode; if (root == null) { return; } m_session = session; SortedDictionary <string, InstanceDeclaration> instances = new SortedDictionary <string, InstanceDeclaration>(); InstanceDeclaration declaration = new InstanceDeclaration(); declaration.Instance = root; declaration.DisplayPath = Utils.Format("({0})", root.NodeClass); declaration.Description = Utils.Format("{0}", root.Description); declaration.DataType = "NodeId"; IVariableBase variable = root as IVariableBase; if (variable != null) { INode dataType = m_session.NodeCache.Find(variable.DataType); if (dataType != null) { declaration.DataType = Utils.Format("{0}", dataType); } if (variable.ValueRank >= 0) { declaration.DataType += "[]"; } } instances.Add(declaration.DisplayPath, declaration); CollectInstances(root, String.Empty, instances); foreach (InstanceDeclaration instance in instances.Values) { AddItem(instance); } AdjustColumns(); }
public AssetBuffer ProcessMP3PassthroughInstance(InstanceDeclaration declaration) { foreach (PluginDescriptor plugin in Settings.Current.Plugins) { if (plugin.Plugin is AudioCompiler.Plugin acPlugin) { return(acPlugin.ProcessMP3PassthroughInstance(declaration)); } } throw new InvalidOperationException("Critical: Original EALA BinaryAssetBuilder.AudioCompiler.dll plugin not found."); }
public AssetBuffer ProcessInstance(InstanceDeclaration instance) { switch (instance.Handle.TypeId) { case 0x166B084Du: return(ProcessAudioFileInstance(instance)); default: _tracer.TraceWarning("Couldn't process {0}. No matching handler found.", instance); return(null); } }
/// <summary> /// Handles the AfterSelect event of the BrowseTV control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param> private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) { try { DeclarationsLV.Items.Clear(); if (e.Node == null) { OkBTN.Enabled = false; return; } OkBTN.Enabled = true; // get the currently selected event. NodeId typeId = m_rootId; ReferenceDescription reference = e.Node.Tag as ReferenceDescription; if (reference != null) { typeId = (NodeId)reference.NodeId; } // get the instance declarations. List <InstanceDeclaration> instances = ModelUtils.CollectInstanceDeclarationsForType(m_session, typeId); // populate the list box. for (int ii = 0; ii < instances.Count; ii++) { InstanceDeclaration instance = instances[ii]; ListViewItem item = new ListViewItem(instance.DisplayPath); item.SubItems.Add(instance.DataTypeDisplayText); item.SubItems.Add(instance.Description); item.Tag = instance; DeclarationsLV.Items.Add(item); } // resize columns to fit text. for (int ii = 0; ii < DeclarationsLV.Columns.Count; ii++) { DeclarationsLV.Columns[ii].Width = -2; } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
public bool VerifyInstance(InstanceDeclaration instance) { if (instance.Node is null) { return(true); } switch (instance.Node.Name) { case "W3DHierarchy": return(HierarchyVerifier.Verify(instance)); default: return(true); } }
/// <see cref="Opc.Ua.Client.Controls.BaseListCtrl.UpdateItem(ListViewItem,object)" /> protected override void UpdateItem(ListViewItem listItem, object item) { InstanceDeclaration instance = item as InstanceDeclaration; if (instance == null) { base.UpdateItem(listItem, item); return; } listItem.SubItems[0].Text = instance.DisplayPath; listItem.SubItems[1].Text = instance.DataType; listItem.SubItems[2].Text = instance.Description; listItem.ImageKey = GuiUtils.GetTargetIcon(m_session, instance.Instance.NodeClass, instance.Instance.TypeDefinitionId); listItem.Tag = item; }
public AssetBuffer ProcessInstance(InstanceDeclaration declaration) { AssetBuffer result; if ((AssetType)declaration.Handle.TypeId == AssetType.AudioFile) { result = ProcessAudioFileInstance(declaration); } else if ((AssetType)declaration.Handle.TypeId == AssetType.AudioFileMP3Passthrough) { result = ProcessMP3PassthroughInstance(declaration); } else { _tracer.TraceWarning($"Warning: Couldn't process {declaration}. No matching handler found."); result = null; } return(result); }
/// <summary> /// Shows all fields for the current condition. /// </summary> public bool ShowDialog(FilterDeclaration filter, VariantCollection fields) { // fill in dialog. for (int ii = 0; ii < filter.Fields.Count; ii++) { InstanceDeclaration instance = filter.Fields[ii].InstanceDeclaration; ListViewItem item = new ListViewItem(instance.DisplayPath); item.SubItems.Add(instance.DataTypeDisplayText); string text = null; // check for missing fields. if (fields.Count <= ii || fields[ii].Value == null) { text = String.Empty; } // use default string format. else { text = fields[ii].ToString(); } item.SubItems.Add(text); item.Tag = filter.Fields[ii]; FieldsLV.Items.Add(item); } // adjust columns. for (int ii = 0; ii < FieldsLV.Columns.Count; ii++) { FieldsLV.Columns[ii].Width = -2; } // display the dialog. if (ShowDialog() != DialogResult.OK) { return(false); } return(true); }
public AssetBuffer ProcessAudioFileInstance(InstanceDeclaration declaration) { XmlNamespaceManager namespaceManager = declaration.Document.NamespaceManager; XPathNavigator navigator = declaration.Node.CreateNavigator(); // TODO: initialize tracker on new audiofileruntimeptr AudioFile audioFile = AudioFile.MarshalFromNode(declaration.Node); if (_platform != TargetPlatform.Win32 || audioFile.PCCompression != PCAudioCompressionSetting.EALAYER3) { foreach (PluginDescriptor plugin in Settings.Current.Plugins) { if (plugin.Plugin is AudioCompiler.Plugin acPlugin) { return(acPlugin.ProcessAudioFileInstance(declaration)); } } throw new InvalidOperationException("Critical: Original EALA BinaryAssetBuilder.AudioCompiler.dll plugin not found."); } if (!EncodeEALayer3(declaration, audioFile, out AssetBuffer result)) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "EALayer3 audio compiler was unable to compile AudioFile:{0}.", audioFile.id); } return(result); }
/// <summary> /// Collects the instance declarations to display in the control. /// </summary> private void CollectInstances(ILocalNode parent, string basePath, SortedDictionary <string, InstanceDeclaration> instances) { if (parent == null) { return; } IList <IReference> supertypes = parent.References.Find( ReferenceTypeIds.HasSubtype, true, false, m_session.TypeTree); for (int ii = 0; ii < supertypes.Count; ii++) { ILocalNode supertype = m_session.NodeCache.Find(supertypes[ii].TargetId) as ILocalNode; if (supertype == null) { continue; } CollectInstances(supertype, basePath, instances); } IList <IReference> children = parent.References.Find( ReferenceTypeIds.HierarchicalReferences, false, true, m_session.TypeTree); for (int ii = 0; ii < children.Count; ii++) { ILocalNode child = m_session.NodeCache.Find(children[ii].TargetId) as ILocalNode; if (child == null) { continue; } if (child.NodeClass != NodeClass.Object && child.NodeClass != NodeClass.Variable) { continue; } if (child.ModellingRule != Objects.ModellingRule_Mandatory && child.ModellingRule != Objects.ModellingRule_Optional) { continue; } string displayPath = Utils.Format("{0}", child); if (!String.IsNullOrEmpty(basePath)) { displayPath = Utils.Format("{0}/{1}", basePath, displayPath); } InstanceDeclaration declaration = new InstanceDeclaration(); declaration.Instance = child; declaration.DisplayPath = displayPath; declaration.Description = Utils.Format("{0}", child.Description); declaration.DataType = String.Empty; IVariableBase variable = child as IVariableBase; if (variable != null) { INode dataType = m_session.NodeCache.Find(variable.DataType); if (dataType != null) { declaration.DataType = Utils.Format("{0}", dataType); } if (variable.ValueRank >= 0) { declaration.DataType += "[]"; } } IObject objectn = child as IObject; if (objectn != null) { declaration.DataType = "NodeId"; } instances[displayPath] = declaration; CollectInstances(child, displayPath, instances); } }
/// <summary> /// Collects the instance declarations to display in the control. /// </summary> private void CollectInstances(ILocalNode parent, string basePath, SortedDictionary<string,InstanceDeclaration> instances) { if (parent == null) { return; } IList<IReference> supertypes = parent.References.Find( ReferenceTypeIds.HasSubtype, true, false, m_session.TypeTree); for (int ii = 0; ii < supertypes.Count; ii++) { ILocalNode supertype = m_session.NodeCache.Find(supertypes[ii].TargetId) as ILocalNode; if (supertype == null) { continue; } CollectInstances(supertype, basePath, instances); } IList<IReference> children = parent.References.Find( ReferenceTypeIds.HierarchicalReferences, false, true, m_session.TypeTree); for (int ii = 0; ii < children.Count; ii++) { ILocalNode child = m_session.NodeCache.Find(children[ii].TargetId) as ILocalNode; if (child == null) { continue; } if (child.NodeClass != NodeClass.Object && child.NodeClass != NodeClass.Variable) { continue; } if (child.ModellingRule != Objects.ModellingRule_Mandatory && child.ModellingRule != Objects.ModellingRule_Optional) { continue; } string displayPath = Utils.Format("{0}", child); if (!String.IsNullOrEmpty(basePath)) { displayPath = Utils.Format("{0}/{1}", basePath, displayPath); } InstanceDeclaration declaration = new InstanceDeclaration(); declaration.Instance = child; declaration.DisplayPath = displayPath; declaration.Description = Utils.Format("{0}", child.Description); declaration.DataType = String.Empty; IVariableBase variable = child as IVariableBase; if (variable != null) { INode dataType = m_session.NodeCache.Find(variable.DataType); if (dataType != null) { declaration.DataType = Utils.Format("{0}", dataType); } if (variable.ValueRank >= 0) { declaration.DataType += "[]"; } } IObject objectn = child as IObject; if (objectn != null) { declaration.DataType = "NodeId"; } instances[displayPath] = declaration; CollectInstances(child, displayPath, instances); } }
private unsafe bool EncodeEALayer3(InstanceDeclaration declaration, AudioFile audioFile, out AssetBuffer result) { if (_platform != TargetPlatform.Win32) { throw new InvalidOperationException("Critical: EALayer3 audio compiler should not be called on non Win32 platforms."); } if (audioFile.PCCompression != PCAudioCompressionSetting.EALAYER3) { throw new InvalidOperationException("Critical: EALayer3 audio compiler should not be called on non EALayer3 compression."); } AudioFileRuntime *audioFileRuntime; Tracker tracker = new Tracker(&audioFileRuntime, _platform == TargetPlatform.Xbox360); string filePath = audioFile.File; if (!filePath.EndsWith(".mp3")) { throw new InvalidOperationException("Critical: EALayer3 audio compiler should not be called on non MP3 files."); } bool isPathEndingWithSound = Path.GetDirectoryName(filePath).ToLower().EndsWith("\\sounds"); // flag2 bool?isStreamedBox = audioFile.IsStreamedOnPC; // flagPtr int? sampleRateBox = audioFile.PCSampleRate; // numPtr1 int quality = audioFile.PCQuality; // num3 // compressionType, 1 == none, 29 == xas, 28 == xma (xbox, will actually set to none or same as xas depending on the isPathEndingWithSound flag) MpegConverterCompressionType compression; // num4 switch (audioFile.PCCompression) { case PCAudioCompressionSetting.NONE: compression = !isPathEndingWithSound ? MpegConverterCompressionType.None : MpegConverterCompressionType.XAS; break; case PCAudioCompressionSetting.XAS: compression = MpegConverterCompressionType.XAS; break; case PCAudioCompressionSetting.EALAYER3: compression = MpegConverterCompressionType.EALayer3; break; default: throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Internal error: xml compiler returned bad PC audio compression type of {0}.", audioFile.PCCompression); } bool isStreamed = isStreamedBox ?? !isPathEndingWithSound; // flag1 if (audioFile.SubtitleStringName != null) { Relo.Marshaler.Marshal(audioFile.SubtitleStringName, &audioFileRuntime->SubtitleStringName, tracker); } else { Relo.Marshaler.Marshal($"DIALOGEVENT:{Path.GetFileNameWithoutExtension(filePath)}SubTitle", &audioFileRuntime->SubtitleStringName, tracker); } audioFileRuntime->NumberOfChannels = 0; audioFileRuntime->NumberOfSamples = 0; audioFileRuntime->SampleRate = 0; audioFileRuntime->HeaderData = IntPtr.Zero; audioFileRuntime->HeaderDataSize = 0; // identify format (SIMEX_id(streamPtr)) - we don't need that, though we might want to check for mp3 // check format needs to be 0 or 1 aka WAVE or AIFF - we don't need that, though we might want to check for mp3 // open audio file (SIMEX_open(streamPtr, &instancePtr, format) using (MpegConverter converter = new MpegConverter(filePath)) { string tempFile = declaration.CustomDataPath + _tempFilenameSuffix; // str2 _tracer.TraceNote("Creating temp file {0}", tempFile); using (AutoCleanUpTempFiles cleanUpTempFiles = new AutoCleanUpTempFiles(tempFile)) { // set temp filename SIMEX_setfilename(str2ptr) converter.SetOutputFilePath(tempFile); // create temp output file SIMEX_create(null, &instancePtr, 39) try { converter.CreateOutputFiles(); MpegConverterSettings converterSettings = converter.GetSettings(); // start iterating through elements (num elements is returned by SIMEX_open) // get info SIMEX_info(instancePtr, &infoPtr, idx) // read element SIMEX_read(instancePtr, infoPtr, idx) if (isStreamed) { // infoPtr + 526 = 0x1000; converterSettings.IsStreamed = true; _tracer.TraceNote("Setting play location to streamed."); } else { // infoPtr + 526 = 0x0800; converterSettings.IsStreamed = false; _tracer.TraceNote("Setting play location to RAM."); } // infoPtr + 509 = compression; converterSettings.CompressionType = compression; _tracer.TraceNote("Setting compression type to {0}.", compression); // SIMEX_getsamplerepname(compression) if (compression == MpegConverterCompressionType.XMA || compression == MpegConverterCompressionType.EALayer3) { if (quality < 0 || quality > 100) { throw new BinaryAssetBuilderException(ErrorCode.InvalidArgument, "Audio file {0}: Quality parameter must be between 0 and 100.", declaration); } // infoPtr + 536 = quality converterSettings.CompressionQuality = quality; _tracer.TraceNote("Setting compression quality to {0}.", quality); } // if (sampleRateBox.HasValue && sampleRateBox.Value != *(int*)(*(infoPtr + 540)) if (sampleRateBox.HasValue && sampleRateBox.Value != converterSettings.SampleRate) { int sampleRate = sampleRateBox.Value; if (sampleRate < 400 || sampleRate > 96000) { throw new BinaryAssetBuilderException(ErrorCode.InvalidArgument, "Audio file {0}: Sample rate must be between 400 and 96000.", declaration); } _tracer.TraceNote("Resampling from {0} to {1}", converterSettings.SampleRate, sampleRate); // infoPtr + 540 // TODO: resampling _tracer.TraceWarning("Warning: Resampling is currently not implemented."); } // if (*(int*)infoPtr != 0) audioFileRuntime->NumberOfChannels = (byte)converterSettings.NumberOfChannels; // infoPtr + 510 audioFileRuntime->NumberOfSamples = converterSettings.NumberOfSamples; // infoPtr + 544 audioFileRuntime->SampleRate = converterSettings.SampleRate; // infoPtr + 540 if (audioFileRuntime->NumberOfChannels != 1 && audioFileRuntime->NumberOfChannels != 2 && audioFileRuntime->NumberOfChannels != 4 && audioFileRuntime->NumberOfChannels != 6) { _tracer.TraceWarning("Warning: Audio file {0} has {1} channels. The only supported channel counts are 1, 2, 4, and 6; sample will probably use only the first channel in the engine.", declaration, audioFileRuntime->NumberOfChannels); } // TODO if (!SIMEX_write(tmpFile, infoPtr, idx)) if (converter.WriteOutput(converterSettings)) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Internal error writing element of \"{0}\".", tempFile); } } finally { converter.CloseOutputFiles(); } string tempFileSnr = tempFile + ".snr"; if (isStreamed) { string tempFileSns = tempFile + ".sns"; if (File.Exists(declaration.CustomDataPath)) { File.Delete(declaration.CustomDataPath); } _tracer.TraceNote("Creating output file {0}\n", declaration.CustomDataPath); File.Move(tempFileSns, declaration.CustomDataPath); using (Stream headerStream = new FileStream(tempFileSnr, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { int length = (int)headerStream.Length; sbyte **headerData = (sbyte **)audioFileRuntime->HeaderData; tracker.Push((void **)headerData, 1, length); headerStream.Read((IntPtr)(*(int *)audioFileRuntime->HeaderData), length); audioFileRuntime->HeaderDataSize = length; tracker.Pop(); } } else { if (File.Exists(declaration.CustomDataPath)) { File.Delete(declaration.CustomDataPath); } _tracer.TraceNote("Creating output file {0}\n", declaration.CustomDataPath); File.Move(tempFileSnr, declaration.CustomDataPath); } if (tracker.IsBigEndian) { Tracker.ByteSwap32((uint *)&audioFileRuntime->NumberOfSamples); Tracker.ByteSwap32((uint *)&audioFileRuntime->SampleRate); Tracker.ByteSwap32((uint *)&audioFileRuntime->HeaderDataSize); } result = new AssetBuffer(); FinalizeTracker(tracker, result); } } return(true); }
/// <summary> /// Initializes the control. /// </summary> public void Initialize(Session session, NodeId typeId) { ItemsLV.Items.Clear(); AdjustColumns(); if (session == null) { return; } ILocalNode root = session.NodeCache.Find(typeId) as ILocalNode; if (root == null) { return; } m_session = session; SortedDictionary<string,InstanceDeclaration> instances = new SortedDictionary<string,InstanceDeclaration>(); InstanceDeclaration declaration = new InstanceDeclaration(); declaration.Instance = root; declaration.DisplayPath = Utils.Format("({0})", root.NodeClass); declaration.Description = Utils.Format("{0}", root.Description); declaration.DataType = "NodeId"; IVariableBase variable = root as IVariableBase; if (variable != null) { INode dataType = m_session.NodeCache.Find(variable.DataType); if (dataType != null) { declaration.DataType = Utils.Format("{0}", dataType); } if (variable.ValueRank >= 0) { declaration.DataType += "[]"; } } instances.Add(declaration.DisplayPath, declaration); CollectInstances(root, String.Empty, instances); foreach (InstanceDeclaration instance in instances.Values) { AddItem(instance); } AdjustColumns(); }
private unsafe AssetBuffer ProcessAudioFileInstance(InstanceDeclaration declaration) { AssetBuffer result = new AssetBuffer(); bool isBigEndian = _platform != TargetPlatform.Win32; Node node = new Node(declaration.Node.CreateNavigator(), declaration.Document.NamespaceManager); AudioFileRuntime *audioFileRuntime; using (Tracker tracker = new Tracker((void **)&audioFileRuntime, (uint)sizeof(AudioFileRuntime), isBigEndian)) { AudioFile audioFile = new AudioFile(); audioFile.Marshal(node); string file = declaration.XmlNode.Attributes["File"].Value; bool isSound = Path.GetDirectoryName(file).ToLower().EndsWith("\\sounds"); int codec; PCAudioCompressionSetting compression = audioFile.PCCompression ?? (isSound ? PCAudioCompressionSetting.XAS : PCAudioCompressionSetting.NONE); switch (compression) { case PCAudioCompressionSetting.NONE: // would become '1' codec = 1; break; case PCAudioCompressionSetting.XAS: // would become '29', xbox XMA would be '28' codec = 29; break; case PCAudioCompressionSetting.EALAYER3: // would become '31', '30' in TW (-ealayer3_int) codec = 31; break; default: throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Internal error: xml compiler returned bad PC audio compression type of {0}", compression); } bool isStreamed = audioFile.IsStreamedOnPC ?? !isSound; if (audioFile.SubtitleStringName is null) { audioFile.SubtitleStringName = $"DIALOGEVENT:{Path.GetFileNameWithoutExtension(file)}SubTitle"; } Marshaler.Marshal(audioFile.SubtitleStringName, &audioFileRuntime->SubtitleStringName, tracker); int type = SIMEX_id(file, 0); if (type < 0) { Console.WriteLine("Warning: Unable to identify format of \"{0}\"; cannot process. (Error: {1})", file, SIMEX_getlasterr()); return(null); } if (type != 1) { Console.WriteLine("Warning: Input files must be WAVE format. Cannot process \"{0}\"", file); return(null); } SINSTANCE *instance = null; int count = SIMEX_open(file, 0, type, &instance); using (AutoSINSTANCECloser closer = new AutoSINSTANCECloser(instance)) { if (count <= 0 || instance == null) { Console.WriteLine("Warning: Could not begin audio processing of \"{0}\": {1}.", file, SIMEX_getlasterr()); return(null); } string tempFile = declaration.CustomDataPath + _tempFilenameSuffix; using (AutoCleanUpTempFiles tempFiles = new AutoCleanUpTempFiles(tempFile)) { SINSTANCE *instance2 = null; if (SIMEX_create(tempFile, 39, &instance2) == 0) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Internal error preparing audio output file \"{0}\" (SIMEX_create(): {1}).", tempFile, SIMEX_getlasterr()); } using (AutoSINSTANCEWCloser closer2 = new AutoSINSTANCEWCloser(instance2)) { for (int i = 0; i < count; i++) { SINFO *info = null; if (SIMEX_info(instance, &info, i) == 0) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Internal error reading element {0} of \"{1}\" (SIMEX_info(): {2}).", file, SIMEX_getlasterr()); } using (AutoSINFOFreer freer = new AutoSINFOFreer(info)) { if (info != null) { if (SIMEX_read(instance, info, i) == 0) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Internal error reading element {0} of \"{1}\" (SIMEX_read(): {2}).", file, SIMEX_getlasterr()); } if (isStreamed) { SIMEX_setplayloc(info, 4096); _tracer.TraceNote("Setting play location to streamed"); } else { SIMEX_setplayloc(info, 2048); _tracer.TraceNote("Setting play location to RAM"); } SIMEX_setcodec(info, codec); _tracer.TraceNote("Setting compression type to {0}. ", SIMEX_getsamplerepname(codec)); } if (codec == 31 || codec == 38) { int quality = audioFile.PCQuality; if (quality < 0 || quality > 100) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Audio file {0}: Quality parameter must be between 0 and 100", file); } SIMEX_setvbrquality(info, quality); _tracer.TraceNote("Setting compression quality to {0}", quality); } if (audioFile.PCSampleRate.HasValue) { int oldrate = SIMEX_getsamplerate(info); int newrate = audioFile.PCSampleRate.Value; if (oldrate != newrate) { if (newrate < 400 || newrate > 96000) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Audio file {0}: Sample rate must be between 400 and 96000", file); } _tracer.TraceNote("Resampling from {0} to {1} ", oldrate, newrate); SIMEX_resample(info, newrate); int rate = SIMEX_getsamplerate(info); if (newrate != rate) { Console.WriteLine("Warning: Downsampling of audio file {0} not completely sucessful. Wanted final sample of {1}Hz but got {2}Hz", file, newrate, rate); } } } audioFileRuntime->NumberOfChannels = SIMEX_getchannelconfig(info); audioFileRuntime->NumberOfSamples = SIMEX_getnumsamples(info); audioFileRuntime->SampleRate = SIMEX_getsamplerate(info); if (audioFileRuntime->NumberOfChannels != 1 && audioFileRuntime->NumberOfChannels != 2 && audioFileRuntime->NumberOfChannels != 4 && audioFileRuntime->NumberOfChannels != 6) { Console.WriteLine("Warning: Audio file {0} has {1} channels. The only supported channel counts are 1, 2, 4, and 6; sample will probably use only the first channel in the engine", file, audioFileRuntime->NumberOfChannels); } if (SIMEX_write(instance2, info, i) == 0) { throw new BinaryAssetBuilderException(ErrorCode.InternalError, "Internal error writing element {0} of \"{1}\" (SIMEX_write(): {2}).", i, tempFile, SIMEX_getlasterr()); } } } string snr = tempFile + ".snr"; byte[] buffer; using (Stream stream = File.Open(snr, FileMode.Open, FileAccess.Read, FileShare.Read)) { buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } if (isStreamed) { string sns = tempFile + ".sns"; if (File.Exists(declaration.CustomDataPath)) { File.Delete(declaration.CustomDataPath); } _tracer.TraceNote("Creating output file {0}\n", declaration.CustomDataPath); File.Move(sns, declaration.CustomDataPath); audioFileRuntime->HeaderDataSize = buffer.Length; fixed(byte *pBuffer = &buffer[0]) { using (Tracker.Context context = tracker.Push(&audioFileRuntime->HeaderData, 1u, (uint)buffer.Length)) { Native.MsVcRt.MemCpy(new IntPtr(audioFileRuntime->HeaderData), new IntPtr(pBuffer), new Native.SizeT(buffer.Length)); } } } else { if (File.Exists(declaration.CustomDataPath)) { File.Delete(declaration.CustomDataPath); } _tracer.TraceNote("Creating output file {0}\n", declaration.CustomDataPath); File.Move(snr, declaration.CustomDataPath); } FinalizeTracker(tracker, result); } } } } return(result); }
/// <summary> /// Updates the row with the node to read. /// </summary> public void UpdateRow(DataRow row, InstanceDeclaration declaration) { row[0] = declaration; row[1] = ImageList.Images[ClientUtils.GetImageIndex((declaration.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId, null)]; row[2] = declaration.DisplayPath; row[3] = declaration.DataTypeDisplayText; row[4] = declaration.Description; }
/// <summary> /// Collects the fields for the instance node. /// </summary> private static void CollectInstanceDeclarations( Session session, NodeId typeId, InstanceDeclaration parent, List<InstanceDeclaration> instances, IDictionary<string, InstanceDeclaration> map) { // find the children. BrowseDescription nodeToBrowse = new BrowseDescription(); if (parent == null) { nodeToBrowse.NodeId = typeId; } else { nodeToBrowse.NodeId = parent.NodeId; } nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasChild; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable | NodeClass.Method); nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; // ignore any browsing errors. ReferenceDescriptionCollection references = ClientUtils.Browse(session, nodeToBrowse, false); if (references == null) { return; } // process the children. List<NodeId> nodeIds = new List<NodeId>(); List<InstanceDeclaration> children = new List<InstanceDeclaration>(); for (int ii = 0; ii < references.Count; ii++) { ReferenceDescription reference = references[ii]; if (reference.NodeId.IsAbsolute) { continue; } // create a new declaration. InstanceDeclaration child = new InstanceDeclaration(); child.RootTypeId = typeId; child.NodeId = (NodeId)reference.NodeId; child.BrowseName = reference.BrowseName; child.NodeClass = reference.NodeClass; if (!LocalizedText.IsNullOrEmpty(reference.DisplayName)) { child.DisplayName = reference.DisplayName.Text; } else { child.DisplayName = reference.BrowseName.Name; } if (parent != null) { child.BrowsePath = new QualifiedNameCollection(parent.BrowsePath); child.BrowsePathDisplayText = Utils.Format("{0}/{1}", parent.BrowsePathDisplayText, reference.BrowseName); child.DisplayPath = Utils.Format("{0}/{1}", parent.DisplayPath, reference.DisplayName); } else { child.BrowsePath = new QualifiedNameCollection(); child.BrowsePathDisplayText = Utils.Format("{0}", reference.BrowseName); child.DisplayPath = Utils.Format("{0}", reference.DisplayName); } child.BrowsePath.Add(reference.BrowseName); // check if reading an overridden declaration. InstanceDeclaration overriden = null; if (map.TryGetValue(child.BrowsePathDisplayText, out overriden)) { child.OverriddenDeclaration = overriden; } map[child.BrowsePathDisplayText] = child; // add to list. children.Add(child); nodeIds.Add(child.NodeId); } // check if nothing more to do. if (children.Count == 0) { return; } // find the modelling rules. List<NodeId> modellingRules = FindTargetOfReference(session, nodeIds, Opc.Ua.ReferenceTypeIds.HasModellingRule, false); if (modellingRules != null) { for (int ii = 0; ii < nodeIds.Count; ii++) { children[ii].ModellingRule = modellingRules[ii]; // if the modelling rule is null then the instance is not part of the type declaration. if (NodeId.IsNull(modellingRules[ii])) { map.Remove(children[ii].BrowsePathDisplayText); } } } // update the descriptions. UpdateInstanceDescriptions(session, children, false); // recusively collect instance declarations for the tree below. for (int ii = 0; ii < children.Count; ii++) { if (!NodeId.IsNull(children[ii].ModellingRule)) { instances.Add(children[ii]); CollectInstanceDeclarations(session, typeId, children[ii], instances, map); } } }
/// <summary> /// Displays the available areas in a tree view. /// </summary> /// <param name="session">The session.</param> /// <returns></returns> public TypeDeclaration ShowDialog(Session session, NodeId rootId, string caption) { m_session = session; // set the caption. if (!String.IsNullOrEmpty(caption)) { this.Text = caption; } // set default root. if (NodeId.IsNull(rootId)) { rootId = Opc.Ua.ObjectTypeIds.BaseEventType; } m_rootId = rootId; // display root. TreeNode root = new TreeNode(session.NodeCache.GetDisplayText(rootId)); root.Nodes.Add(new TreeNode()); BrowseTV.Nodes.Add(root); root.Expand(); BrowseTV.SelectedNode = root; // display the dialog. if (ShowDialog() != DialogResult.OK) { return(null); } // ensure selection is valid. if (BrowseTV.SelectedNode == null) { return(null); } // get the currently selected event. NodeId typeId = m_rootId; ReferenceDescription reference = BrowseTV.SelectedNode.Tag as ReferenceDescription; if (reference != null) { typeId = (NodeId)reference.NodeId; } TypeDeclaration declaration = new TypeDeclaration(); declaration.NodeId = typeId; declaration.Declarations = new List <InstanceDeclaration>(); // update selected fields. for (int ii = 0; ii < DeclarationsLV.Items.Count; ii++) { InstanceDeclaration instance = DeclarationsLV.Items[ii].Tag as InstanceDeclaration; if (instance != null) { declaration.Declarations.Add(instance); } } // return the result. return(declaration); }