void PlayerMoveHandler(Codecs cs, byte[] data) { MoveProto proto = cs.Decode <MoveProto>(data); if (proto.id == player.GetComponent <Player>().GetID()) { return; } string line = "[" + proto.id + "] move " + proto.x.ToString() + ", " + proto.z.ToString(); print(line); if (!_players.ContainsKey(proto.id)) { GameObject e = Instantiate(preplayer, new Vector3(proto.x, 0, proto.z), Quaternion.identity); e.GetComponent <Renderer>().material.color = RandomColor(); _players.Add(proto.id, e); Transform PlayerMapIconTransform = e.transform.GetChild(0); PlayerMapIconTransform.GetComponent <Renderer>().material.color = Color.red; } else { GameObject e = _players[proto.id]; Rigidbody rg = e.GetComponent <Rigidbody>(); rg.MovePosition(new Vector3(proto.x, 0, proto.z)); e.GetComponent <Player>().SetScore(proto.score); } }
// Decode G.711 private void button1_Click(object sender, EventArgs e) { try { if (codecToDecode.SelectedItem == null) { throw new Exception("Вы не выбрали кодэк."); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } OpenFileDialog open = new OpenFileDialog(); open.Filter = "Wave File (*.wav)|*.wav;"; if (open.ShowDialog() != DialogResult.OK) { return; } AudioFile searchFile = files.Find(x => x.Path == open.FileName); if (searchFile != null) { MessageBox.Show("Этот файл уже добавлен в список.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Codecs codec = (codecToDecode.SelectedIndex == 0) ? Codecs.ALAW : Codecs.MULAW; this.decodeG711(open.FileName, codec); }
public static void Main() { var engine = Engine.Engine .Builder( Fitness, Codecs.OfScalar(DoubleRange.Of(0.0, 2.0 * Math.PI))) .PopulationSize(500) .Optimize(Optimize.Minimum) .Alterers( new Mutator <DoubleGene, double>(0.03), new MeanAlterer <DoubleGene, double>(0.6)) .Build(); var statistics = EvolutionStatistics.OfNumber <double>(); var best = engine.Stream() .TakeWhile(BySteadyFitness <DoubleGene, double>(7)) .Take(100) .Peek(statistics.Accept) .ToBestPhenotype(); Console.WriteLine(statistics); Console.WriteLine(best); }
/// <summary> /// Implementation of method to load codecs from assembly(ies) at the specified <paramref name="path"/> and /// with the specified <paramref name="search"/> pattern. /// </summary> /// <param name="path">Directory path to codec assemblies.</param> /// <param name="search">Search pattern for codec assemblies.</param> protected override void LoadCodecsImpl(string path, string search) { if (IsLoaded) { return; } Codecs.Clear(); var foundAnyCodecs = false; var assembly = Assembly.GetExecutingAssembly(); var types = assembly.GetTypes(); var codecTypes = types.Where(t => typeof(IDicomCodec).IsAssignableFrom(t) && !t.IsAbstract); var log = LogManager.GetLogger("Efferent.Native.Codec"); foreach (var codecType in codecTypes) { foundAnyCodecs = true; IDicomCodec codec = (IDicomCodec)Activator.CreateInstance(codecType); Codecs[codec.TransferSyntax] = codec; } if (!foundAnyCodecs) { log.Warn("No Dicom codecs were found after searching {path}\\{wildcard}", path, search); } else { IsLoaded = true; var codecNames = string.Join("\n", Codecs.Keys.Select(k => "- " + k.ToString())); System.Diagnostics.Debug.WriteLine($"Codecs found:\n{codecNames}"); } }
private void decodeG711(string filename, Codecs codec) { WaveFileReader reader = new WaveFileReader(filename); byte[] buffer = new byte[reader.Length]; short[] samples = new short[buffer.Length]; reader.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (codec == Codecs.ALAW) { samples[i] = ALawDecoder.ALawToLinearSample(buffer[i]); } else if (codec == Codecs.MULAW) { samples[i] = MuLawDecoder.MuLawToLinearSample(buffer[i]); } } WaveFileWriter writer = new WaveFileWriter("tmp_" + (++this.tmpCount) + ".wav", new WaveFormat(44100, 16, 2)); writer.WriteSamples(samples, 0, samples.Length); writer.Close(); WaveFileReader tmpReader = new WaveFileReader("tmp_" + this.tmpCount + ".wav"); WaveStream pcm = new WaveChannel32(tmpReader); BlockAlignReductionStream stream = new BlockAlignReductionStream(pcm); AudioFile file = new WaveFile(tmpReader, stream, filename); this.files.Add(file); this.addFileToListView(file); this.initAudio(file); }
protected void WhenFindingCodecsFor <TResourceType>(params string[] contentTypes) { ThenTheResult = Codecs.FindMediaTypeWriter(typeSystem.FromClr(typeof(TResourceType)), MediaType.Parse(string.Join(",", contentTypes))) .ToList(); }
public override string ToString() { return(string.Format("ResourceKey: {0}, Uris: {1}, Handlers: {2}, Codecs: {3}", ResourceKey, Uris.Aggregate(string.Empty, (str, reg) => str + reg + ";"), Handlers.Aggregate(string.Empty, (str, reg) => str + reg + ";"), Codecs.Aggregate(string.Empty, (str, reg) => str + reg + ";"))); }
public void Add(Codecs codec, string file, string name) { if (!_streams.ContainsKey(codec)) { _streams[codec] = new Dictionary <string, string>(); } _streams[codec][name] = file; }
public void TestGetOutputFileExtension() { foreach (CodecID codecID in Enum.GetValues(typeof(CodecID))) { Assert.IsNotNull(Codecs.GetOutputFileExtension(codecID)); } Assert.AreEqual(CodecOutputFileExtension, Codecs.GetOutputFileExtension(CodecIdentifier), "Codecs.GetOutputFileExtension()"); }
public void TestParse() { foreach (string name in Enum.GetNames(typeof(CodecID))) { Assert.IsTrue(Enum.IsDefined(typeof(CodecID), Codecs.Parse(name)), "Codecs.Parse()"); } Assert.AreEqual(CodecID.Unknown, Codecs.Parse(InvalidName), "Codecs.Parse() invalid name"); }
public AudioConfig Clone() { return(new AudioConfig() { Codecs = Codecs?.ToDictionary(p => p.Key, p => p.Value?.Clone()), PassthruMatchingTracks = PassthruMatchingTracks }); }
// Encode G.711 private void button2_Click(object sender, EventArgs e) { try { if (this.currentAudio == null) { throw new Exception("Вы не выбрали файл для кодирования."); } if (codecToEncode.SelectedItem == null) { throw new Exception("Вы не выбрали кодэк."); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } SaveFileDialog save = new SaveFileDialog(); save.Filter = "Wave File (*.wav)|*.wav;"; if (save.ShowDialog() != DialogResult.OK) { return; } Codecs codec = (codecToEncode.SelectedIndex == 0) ? Codecs.ALAW : Codecs.MULAW; byte[] samples = new byte[this.currentAudio.ShortSamples.Length]; for (int i = 0; i < this.currentAudio.ShortSamples.Length; i++) { if (codec == Codecs.ALAW) { samples[i] = ALawEncoder.LinearToALawSample(this.currentAudio.ShortSamples[i]); } else if (codec == Codecs.MULAW) { samples[i] = MuLawEncoder.LinearToMuLawSample(this.currentAudio.ShortSamples[i]); } } WaveFormat format = null; if (codec == Codecs.ALAW) { format = WaveFormat.CreateALawFormat(this.currentAudio.SampleRate, this.currentAudio.Stream.WaveFormat.Channels); } else if (codec == Codecs.MULAW) { format = WaveFormat.CreateMuLawFormat(this.currentAudio.SampleRate, this.currentAudio.Stream.WaveFormat.Channels); } WaveFileWriter writer = new WaveFileWriter(save.FileName, format); writer.Write(samples, 0, samples.Length); writer.Close(); DialogResult dres = MessageBox.Show("Аудиофайл успешно сохранен. Открыть файл?", "Файл сохранен", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dres == DialogResult.Yes) { this.decodeG711(save.FileName, codec); } }
public sound_cache_file_gestalt(CacheBase Cache, int Address) { EndianReader Reader = Cache.Reader; Reader.SeekTo(Address); #region Codec Chunk int iCount = Reader.ReadInt32(); int iOffset = Reader.ReadInt32() - Cache.Magic; for (int i = 0; i < iCount; i++) { Codecs.Add(new Codec(Cache, iOffset + 3 * i)); } #endregion #region SoundName Chunk Reader.SeekTo(Address + 36); iCount = Reader.ReadInt32(); iOffset = Reader.ReadInt32() - Cache.Magic; for (int i = 0; i < iCount; i++) { SoundNames.Add(new SoundName(Cache, iOffset + 4 * i)); } #endregion #region Playback Chunk Reader.SeekTo(Address + 72); iCount = Reader.ReadInt32(); iOffset = Reader.ReadInt32() - Cache.Magic; for (int i = 0; i < iCount; i++) { PlayBacks.Add(new Playback(Cache, iOffset + 12 * i)); } #endregion #region SoundPermutation Chunk Reader.SeekTo(Address + 84); iCount = Reader.ReadInt32(); iOffset = Reader.ReadInt32() - Cache.Magic; for (int i = 0; i < iCount; i++) { SoundPermutations.Add(new SoundPermutation(Cache, iOffset + 16 * i)); } #endregion #region Raw Chunks Reader.SeekTo(Address + 160); iCount = Reader.ReadInt32(); iOffset = Reader.ReadInt32() - Cache.Magic; for (int i = 0; i < iCount; i++) { RawChunks.Add(new RawChunk(Cache, iOffset + 20 * i)); } #endregion }
public void Invoke(string type, Codecs cs, byte[] data) { if (callbacks.ContainsKey(type)) { callbacks[type](cs, data); } else { Debug.Log("event type invalid: " + type); } }
public VideoConfig Clone() { return(new VideoConfig() { Codecs = Codecs?.ToDictionary(p => p.Key, p => p.Value?.Clone()), CropDetectOptions = CropDetectOptions, DeinterlaceOptions = DeinterlaceOptions, DenoiseOptions = DenoiseOptions, TonemapOptions = TonemapOptions, }); }
protected void given_resource <T>(string template) { var resourceKey = TypeSystem.FromClr <T>(); UriResolver.Add(new UriRegistration(template, resourceKey)); Codecs.Add(new CodecRegistration(typeof(XmlCodec), resourceKey, false, MediaType.Xml, new[] { "xml" }, null, false)); }
public VideoConfig Clone() { return(new VideoConfig() { Codecs = Codecs?.ToDictionary(p => p.Key, p => p.Value?.Clone()), SizePresets = SizePresets?.ToDictionary(p => p.Key, p => p.Value), AspectRatioPresets = AspectRatioPresets?.ToDictionary(p => p.Key, p => p.Value), SizeDivisor = SizeDivisor, Deinterlace = Deinterlace }); }
public string GetUrl(Codecs codec, string name) { if (_rtspUrls.ContainsKey(codec)) { if (_rtspUrls[codec].ContainsKey(name)) { return(_rtspUrls[codec][name]); } } return(String.Empty); }
public static void Main() { var engine = Engine.Engine .Builder(Area, Codecs.OfScalar(NextDimension)) .Build(); var pt = engine.Stream() .Take(50) .ToBestPhenotype(); Console.WriteLine(pt); }
public string[] GetUrls(Codecs codec) { List <string> urls = new List <string>(); if (_rtspUrls.ContainsKey(codec)) { foreach (string url in _rtspUrls[codec].Values) { urls.Add(url); } } return(urls.ToArray()); }
protected void given_registration_codec <TCodec, TResource>(string mediaTypes) { foreach (var contentType in MediaType.Parse(mediaTypes)) { Codecs.Add(CodecRegistration.FromResourceType(typeof(TResource), typeof(TCodec), TypeSystem, contentType, null, null, false)); } }
private void SaveConfig() { try { if (Files.Exists("simple-aio-gatherer.json")) { Files.Delete("simple-aio-gatherer.json"); } Files.WriteText("simple-aio-gatherer.json", Codecs.ToJson(config)); } catch (Exception e) { Logging.Log("Failed to save config " + e, LogLevel.Error); } }
public static string [] CodecArray(int Value) { string [] values; string value_list; Codecs codec_mask = (Codecs)Value; value_list = codec_mask.ToString("G"); values = value_list.Split(','); for (int i = 0; i < values.Length; i++) { values[i] = values[i].Trim(); } return(values); }
/// <summary> /// Implementation of method to load codecs /// </summary> /// <param name="path">Directory path to codec assemblies</param> /// <param name="search">Search pattern for codec assemblies</param> protected override void LoadCodecsImpl(String path, String search) { // Clear all loaded codecs Codecs.Clear(); // Register the JPEG-LS near lossless decoder var jpegLsNearLosslessDecoder = (IDicomCodec)Activator.CreateInstance(typeof(DicomJpegLsNearLosslessDecoder)); Codecs[jpegLsNearLosslessDecoder.TransferSyntax] = jpegLsNearLosslessDecoder; // Register the JPEG-LS lossless decoder var jpegLsLosslessDecoder = (IDicomCodec)Activator.CreateInstance(typeof(DicomJpegLsLosslessDecoder)); Codecs[jpegLsLosslessDecoder.TransferSyntax] = jpegLsLosslessDecoder; }
/// <summary> /// Shows the codec settings form. /// </summary> /// <remarks>Documented by Dev02, 2008-04-15</remarks> private void ShowCodecSettings() { CodecSettings settingsForm = new CodecSettings(); settingsForm.Codecs = codecs; settingsForm.ShowEncoder = Settings.Default.ShowEncodingWindow; settingsForm.ShowDecoder = Settings.Default.ShowDecodingWindow; settingsForm.MinimizeWindows = Settings.Default.MimimizeWindows; if (settingsForm.ShowDialog() == DialogResult.OK) { codecs = settingsForm.Codecs; Settings.Default.ShowEncodingWindow = settingsForm.ShowEncoder; Settings.Default.ShowDecodingWindow = settingsForm.ShowDecoder; Settings.Default.MimimizeWindows = settingsForm.MinimizeWindows; Settings.Default.Save(); } }
private void SaveConfig() { var extention = ".json"; var title = "Albion_Ennui_gatherer_for_"; try { if (Files.Exists(title + localPlayer.Name + extention)) { Files.Delete(title + localPlayer.Name + extention); } Files.WriteText(title + localPlayer.Name + extention, Codecs.ToJson(config)); } catch (Exception e) { Logging.Log("Failed to save config " + e, LogLevel.Error); } }
public string DecryptAES(string encryptedString, string Key) { //First write to memory MemoryStream mmsStream = new MemoryStream(); StreamWriter srwTemp = new StreamWriter(mmsStream); //sBuffer is my encodedtext. srwTemp.Write(encryptedString); srwTemp.Flush(); mmsStream.Position = 0; MemoryStream outstream = new MemoryStream(); //CallingUUDecode Codecs.UUDecode(mmsStream, outstream); //Extract the bytes of each of the values byte[] input = outstream.ToArray(); byte[] key = Convert.FromBase64String(Key); string decryptedText = null; using (RijndaelManaged algorithm = new RijndaelManaged()) { // initialize settings to match those used by CF algorithm.Mode = CipherMode.ECB; algorithm.Padding = PaddingMode.PKCS7; algorithm.BlockSize = 128; algorithm.KeySize = 128; algorithm.Key = key; ICryptoTransform decryptor = algorithm.CreateDecryptor(); using (MemoryStream msDecrypt = new MemoryStream(input)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { decryptedText = srDecrypt.ReadToEnd(); } } } } return(decryptedText); }
void PlayerJoinHandler(Codecs cs, byte[] data) { JoinProto proto = cs.Decode <JoinProto>(data); string line = "[" + proto.id + "] join"; print(line); if (proto.id == player.GetComponent <Player>().GetID()) { _players.Add(proto.id, player); return; } GameObject e = Instantiate(preplayer, new Vector3(0, 0, 0), Quaternion.identity); e.GetComponent <Renderer>().material.color = RandomColor(); _players.Add(proto.id, e); Transform PlayerMapIconTransform = e.transform.GetChild(0); PlayerMapIconTransform.GetComponent <Renderer>().material.color = Color.red; }
void PlayerExitHandler(Codecs cs, byte[] data) { ExitProto proto = cs.Decode <ExitProto>(data); string line = "[" + proto.id + "] exit"; print(line); if (proto.id == player.GetComponent <Player>().GetID()) { return; } if (!_players.ContainsKey(proto.id)) { return; } GameObject e = _players[proto.id]; _players.Remove(proto.id); Destroy(e); }
private void LoadConfig() { try { if (Files.Exists("simple-aio-gatherer.json")) { config = Codecs.FromJson <Configuration>(Files.ReadAllText("simple-aio-gatherer.json")); if (config.TypeSetsToUse == null) { config.TypeSetsToUse = new List <SafeTypeSet>(); } } } catch (Exception e) { Logging.Log("Failed to log config " + e, LogLevel.Error); } if (config == null) { config = new Configuration(); } }
/// <summary> /// Shows the codec settings form. /// </summary> /// <remarks>Documented by Dev02, 2008-04-15</remarks> private void ShowCodecSettings() { CodecSettings settingsForm = new CodecSettings(); settingsForm.Codecs = codecs; settingsForm.ShowEncoder = Settings.Default.ShowEncodingWindow; settingsForm.ShowDecoder = Settings.Default.ShowDecodingWindow; settingsForm.MinimizeWindows = Settings.Default.MimimizeWindows; if (settingsForm.ShowDialog() == DialogResult.OK) { codecs = settingsForm.Codecs; Settings.Default.ShowEncodingWindow = settingsForm.ShowEncoder; Settings.Default.ShowDecodingWindow = settingsForm.ShowDecoder; Settings.Default.MimimizeWindows = settingsForm.MinimizeWindows; Settings.Default.Save(); } }
/// <summary> /// Generates the audio book. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="audiobook">The target audiobook file.</param> /// <param name="options">The options.</param> /// <param name="worker">The worker.</param> /// <param name="codecs">The codecs.</param> /// <remarks>Documented by Dev02, 2008-03-10</remarks> public static void GenerateAudioBook(IDictionary dictionary, FileInfo audiobook, AudioBookOptions options, Codecs codecs) { if (workerthread != null && workerthread.IsAlive) { AddLog("Error: Another operation is still active."); return; } workerthread = new Thread(delegate() { try { Dictionary<string, Codec> encodeCodecs = codecs.encodeCodecs; Dictionary<string, Codec> decodeCodecs = codecs.decodeCodecs; if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant() && !encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { AddLog(string.Format("Specified extension ({0}) is not available => Check encoder settings", audiobook.Extension.ToLowerInvariant())); return; } List<MediaFieldFile> sourcefiles = new List<MediaFieldFile>(); //source files from dictionary Environment.CurrentDirectory = new FileInfo(dictionary.Connection).Directory.FullName; //fetch source audio files AddLog("Fetching source audio files"); int count = dictionary.Cards.Cards.Count; int index = 0; foreach (ICard card in dictionary.Cards.Cards) { sourcefiles.AddRange(GetCardMediaFiles(card, options.MediaFields)); ReportProgress(index++, count); } //search and generate a new temp folder DirectoryInfo tempfolder; int tempfolderindex = 0; do { tempfolder = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Settings.Default.TempFolderPath + tempfolderindex.ToString())); tempfolderindex++; } while (tempfolder.Exists); tempfolder.Create(); try { //convert all source files to wave where necessary AddLog("Converting source files"); bool foundfile = false; count = sourcefiles.Count; index = 0; for (int i = 0; i < sourcefiles.Count; i++) { if (sourcefiles[i].ContainsFile && decodeCodecs.ContainsKey(sourcefiles[i].Extension)) { //decode file string filename = sourcefiles[i].file.Name; sourcefiles[i].file = decodeCodecs[sourcefiles[i].Extension].Decode(sourcefiles[i].file, tempfolder, Settings.Default.ShowDecodingWindow, Settings.Default.MimimizeWindows); if (sourcefiles[i].ContainsFile) foundfile = true; else AddLog(string.Format("Decoding ({0}) did not produce a file => Check decoder settings", filename)); } else if (sourcefiles[i].ContainsFile && sourcefiles[i].Extension == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) foundfile = true; else if (sourcefiles[i].ContainsFile) AddLog(string.Format("Extension {0} not supported ({1}) => Check decoder settings", sourcefiles[i].Extension, sourcefiles[i].file.Name)); ReportProgress(index++, count); } if (!foundfile) { AddLog("No supported audio files found in the selected fields of the learning module"); ReportProgress(0, 0); //disable progress reporting } else { //concatenate all wave files AddLog("Joining audio files"); FileInfo audiobookwave = new FileInfo(Path.Combine(tempfolder.FullName, Resources.AUDIOBOOK_DEFAULTNAME + Resources.AUDIO_WAVE_EXTENSION)); ABWaveCat wavecat = new ABWaveCat(); wavecat.Concatenate(sourcefiles, audiobookwave, options.Stereo); ReportProgress(0, 0); //disable progress reporting bool changeToWaveExtension = true; //fix for [MLA-1272] error message for file path without extension if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { if (encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { //convert audiobook to specified format AddLog("Converting audiobook"); FileInfo encodedfile = encodeCodecs[audiobook.Extension.ToLowerInvariant()].Encode(audiobookwave, tempfolder, Settings.Default.ShowEncodingWindow, Settings.Default.MimimizeWindows); if (encodedfile != null) { try { if (audiobook.Exists) audiobook.Delete(); encodedfile.MoveTo(audiobook.FullName); changeToWaveExtension = false; } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } else { AddLog(string.Format("Encoding ({0}) did not produce a file => Check encoder settings", audiobook.Name)); } } } if (changeToWaveExtension) //change file to wave extension and force wave generation audiobook = new FileInfo(Path.ChangeExtension(audiobook.FullName, Resources.AUDIO_WAVE_EXTENSION)); if (audiobook.Extension.ToLowerInvariant() == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { try { if (audiobook.Exists) audiobook.Delete(); audiobookwave.MoveTo(audiobook.FullName); } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } AddLog("Finished: " + audiobook.FullName); } } finally { //try to delete the temp directory (try multiple times in case it is still locked) Thread cleanthread = new Thread(delegate() { int tries = 0; while (tries++ < 10) { System.Threading.Thread.Sleep(1000); try { tempfolder.Delete(true); TempFiles.ForEach(f => f.Delete()); break; } catch { } } }); cleanthread.IsBackground = true; cleanthread.Start(); } } catch (Exception exp) { ReportProgress(0, 0); //disable progressbar if (exp is ThreadAbortException) { AddLog("Operation cancelled"); } else { AddLog("GenerateAudioBook Thread Exception: " + exp.ToString()); } } finally { //fire the working thread finished event in every case OnWorkingThreadFinished(EventArgs.Empty); } }); workerthread.IsBackground = true; workerthread.Start(); return; }