private void comboBoxCodePageList_SelectedIndexChanged(object sender, EventArgs e) { IsModified = true; string strCodePage = (string)comboBoxCodePageList.SelectedItem; int nCodePage = 0; try { nCodePage = Convert.ToInt32(strCodePage); } catch { return; } System.Diagnostics.Debug.Assert((comboBoxCodePageList.SelectedIndex >= 0) && (comboBoxCodePageList.SelectedIndex < m_encInfos.Length)); EncodingInfo encInfo = m_encInfos[comboBoxCodePageList.SelectedIndex]; System.Diagnostics.Debug.Assert(nCodePage == encInfo.CodePage); string strInfo = String.Format("Code Page: {1}{0}Display Name: {2}{0}Registered Name: {3}", Environment.NewLine, encInfo.CodePage, encInfo.DisplayName, encInfo.Name); textBoxCodePageDetails.Text = strInfo; }
public ParatextTextCorpus(ITokenizer <string, int> wordTokenizer, string projectDir) { string settingsFileName = Path.Combine(projectDir, "Settings.xml"); var settingsDoc = XDocument.Load(settingsFileName); var codePage = (int?)settingsDoc.Root.Element("Encoding") ?? 65001; EncodingInfo encodingInfo = Encoding.GetEncodings().FirstOrDefault(ei => ei.CodePage == codePage); if (encodingInfo == null) { throw new InvalidOperationException("The Paratext project contains an unknown encoding."); } Encoding encoding = encodingInfo.GetEncoding(); var scrVersType = (int?)settingsDoc.Root.Element("Versification") ?? (int)ScrVersType.English; Versification = new ScrVers((ScrVersType)scrVersType); var stylesheetName = (string)settingsDoc.Root.Element("StyleSheet") ?? "usfm.sty"; string stylesheetFileName = Path.Combine(projectDir, stylesheetName); var stylesheet = new UsfmStylesheet(stylesheetFileName); foreach (string sfmFileName in Directory.EnumerateFiles(projectDir, "*.SFM")) { AddText(new UsfmFileText(wordTokenizer, stylesheet, encoding, sfmFileName, Versification)); } }
public override bool Equals(object other) { EncodingInfo ei = other as EncodingInfo; return(ei != null && ei.codepage == codepage); }
private void InitEncodingsComboBox(EncodingInfo selectedEncoding) { selectedEncoding = selectedEncoding ?? _defaultEncodingInfo; comboBoxEncoding.BeginUpdate(); try { comboBoxEncoding.SelectedItem = null; EncodingInfo[] encodings = checkBoxShowAllEncodings.Checked ? _allEncodingsInfo : _preferableEncodingsInfo; comboBoxEncoding.DataSource = encodings; int idx = comboBoxEncoding.Items.IndexOf(selectedEncoding); if (idx == -1) { idx = comboBoxEncoding.Items.IndexOf(_defaultEncodingInfo); } comboBoxEncoding.SelectedIndex = idx; } finally { comboBoxEncoding.EndUpdate(); } }
public void Read(Stream raf) { tag = new Tag(); ei = new EncodingInfo(); br = new BinaryReader(raf); Parse(); }
/// <inheritdoc cref="IImageAdapter.Commit(BitmapInfo,Bitmap,EncodingInfo)"/> public virtual bool Commit(BitmapInfo bitmapInfo, Bitmap image, EncodingInfo imageEncoding) { // Validity checks if (bitmapInfo == null) { throw new ArgumentNullException(nameof(bitmapInfo)); } if (imageEncoding == null) { throw new ArgumentNullException(nameof(imageEncoding)); } if (!ImageEncodingInfos.Contains(imageEncoding)) { throw new ArgumentException(nameof(imageEncoding)); } if (imageEncoding.IsIndexed) { throw new IndexedEncodingNotSupported(imageEncoding); } bitmapInfo.Image = image ?? throw new ArgumentNullException(nameof(image)); bitmapInfo.ImageEncoding = imageEncoding; return(true); }
private void DisplayEncodingCharacters(EncodingInfo encodingInfo) { if (encodingInfo == null) { return; } listView1.BeginUpdate(); try { var encoding = Encoding.GetEncoding(encodingInfo.Name, new EncoderReplacementFallback(""), new DecoderReplacementFallback("")); listView1.Items.Clear(); var chars = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' , 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' , 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' , 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ь', 'ы', 'ъ', 'э', 'ю', 'я' , 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ь', 'Ы', 'Ъ', 'Э', 'Ю', 'Я' }; for (int i = 0; i < chars.Length; i++) { string s = chars[i].ToString(); var item = new ListViewItem(s); item.SubItems.Add(ByteArrayToString(encoding.GetBytes(s))); listView1.Items.Add(item); } } finally { listView1.EndUpdate(); } }
public bool DecodePackagea(string sMsg, EncodingInfo AEncodingInfo) { int bPos;//, ePos; // Decode Packet Head PacketHead = CommandBase.DecodePacketHead(sMsg); if (PacketHead.PacketType != PacketType) { return(false); } // Decode Commandcomefrom bPos = sMsg.IndexOf("Command come from", 0); _ComeFrom = CommandBase.ExtractValue(sMsg, bPos); //CommandGUID, Result bPos = sMsg.IndexOf("CommandGUID", bPos); _CommandGUID = CommandBase.ExtractValue(sMsg, bPos); bPos = sMsg.IndexOf("Result", bPos); _CommandResult = CommandBase.ExtractValue(sMsg, bPos); return(true); }
protected GeneralAppSettingsPageBase(CommonEditorOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } this.options = options; GroupSizeInBytesVM = new Int32VM(a => { }, useDecimal: true) { Min = 0, Max = int.MaxValue }; HexOffsetFormatVM = new EnumListVM(hexOffsetFormatList); EncodingInfoVM = new EnumListVM(Encoding.GetEncodings().OrderBy(a => a.DisplayName, StringComparer.CurrentCultureIgnoreCase).Select(a => new EnumVM(a, a.DisplayName)).ToArray()); EnableHighlightCurrentLine = options.EnableHighlightCurrentLine; HighlightCurrentValue = options.HighlightCurrentValue; HighlightStructureUnderMouseCursor = options.HighlightStructureUnderMouseCursor; HighlightActiveColumn = options.HighlightActiveColumn; ValuesLowerCaseHex = options.ValuesLowerCaseHex; OffsetLowerCaseHex = options.OffsetLowerCaseHex; EnableColorization = options.EnableColorization; GroupSizeInBytesVM.Value = options.GroupSizeInBytes; HexOffsetFormat = options.HexOffsetFormat; EncodingInfo = GetEncodingInfo(options.EncodingCodePage) ?? GetEncodingInfo(Encoding.UTF8.CodePage) ?? (EncodingInfo)EncodingInfoVM.Items.FirstOrDefault()?.Value; }
public static void Init() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;; OSVersion = float.Parse($"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor}"); Encodings = Encoding.GetEncodings(); PuttyColorlNames = DatabaseServices.GetPuttyColorlNames(); EqualWidthFonts = GetEqualWidthFonts(); DesktopSizes = GetSystemResolutions(); if (Encodings == null) { Encodings = new EncodingInfo[0]; } if (PuttyColorlNames == null) { PuttyColorlNames = new string[0]; } if (EqualWidthFonts == null) { EqualWidthFonts = new string[0]; } if (DesktopSizes == null) { DesktopSizes = new Size[0]; } //加载默认设置 DatabaseServices.GetDefaultSetting(RemoteType.rdp).SetDefaultSetting(); DatabaseServices.GetDefaultSetting(RemoteType.ssh).SetDefaultSetting(); DatabaseServices.GetDefaultSetting(RemoteType.telnet).SetDefaultSetting(); }
[System.Security.SecuritySafeCritical] // auto-generated internal static unsafe EncodingInfo[] GetEncodings() { if (lastCodePageItem == 0) { int count; for (count = 0; codePageDataPtr[count].codePage != 0; count++) { // Count them } lastCodePageItem = count; } EncodingInfo[] arrayEncodingInfo = new EncodingInfo[lastCodePageItem]; int i; for (i = 0; i < lastCodePageItem; i++) { arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0), #if MONO Environment.GetResourceStringEncodingName(codePageDataPtr[i].codePage)); #else Environment.GetResourceString("Globalization.cp_" + codePageDataPtr[i].codePage)); #endif } return(arrayEncodingInfo); }
public override bool Equals(object value) { EncodingInfo ei = value as EncodingInfo; return(ei != null && ei.codepage == codepage); }
public EncodingInfo Read(Stream raf) { EncodingInfo info = new EncodingInfo(); //Begin info fetch------------------------------------------- if (raf.Length == 0) { //Empty File throw new CannotReadException("File is empty"); } raf.Seek(0, SeekOrigin.Begin); //MP+ Header string byte[] b = new byte[3]; raf.Read(b, 0, b.Length); string mpc = new string(System.Text.Encoding.ASCII.GetChars(b)); if (mpc != "MP+" && mpc == "ID3") { //TODO Do we have to do this ?? //we have an ID3v2 tag at the beginning //We quickly jump to MPC data raf.Seek(6, SeekOrigin.Begin); int tagSize = ReadSyncsafeInteger(raf); raf.Seek(tagSize + 10, SeekOrigin.Begin); //retry to read MPC stream b = new byte[3]; raf.Read(b, 0, b.Length); mpc = new string(System.Text.Encoding.ASCII.GetChars(b)); if (mpc != "MP+") { //We could definitely not go there throw new CannotReadException("MP+ Header not found"); } } else if (mpc != "MP+") { throw new CannotReadException("MP+ Header not found"); } b = new byte[25]; raf.Read(b, 0, b.Length); MpcHeader mpcH = new MpcHeader(b); //We only support v7 Stream format, so if it isn't v7, then returned values //will be bogus, and the file will be ignored double pcm = mpcH.SamplesNumber; info.Duration = new TimeSpan((long)(pcm * 1152 / mpcH.SamplingRate) * TimeSpan.TicksPerSecond); info.ChannelNumber = mpcH.ChannelNumber; info.SamplingRate = mpcH.SamplingRate; info.EncodingType = mpcH.EncodingType; info.ExtraEncodingInfos = mpcH.EncoderInfo; info.Bitrate = ComputeBitrate(info.Duration.Seconds, raf.Length); return(info); }
public void GetAllAvailableEncodings(EncodingInfo info) { // Requires <MandroidI18n>All</MandroidI18n> or can throw: // System.NotSupportedException : Encoding 37 data could not be found. Make sure you have correct international codeset assembly installed and enabled. Encoding enc = info.GetEncoding(); Assert.IsNotNull(enc.EncodingName, $"Failed to get Encoding from '{info.DisplayName}'."); }
public EncodingInfo Read(Stream raf) { //Read the infos-------------------------------------------------------- if (raf.Length == 0) { //Empty File throw new CannotReadException("Error: File empty"); } raf.Seek(0, SeekOrigin.Begin); //FLAC Header string byte[] b = new byte[4]; raf.Read(b, 0, b.Length); string flac = new string(System.Text.Encoding.ASCII.GetChars(b)); if (flac != "fLaC") { throw new CannotReadException("fLaC Header not found"); } MetadataBlockDataStreamInfo mbdsi = null; bool isLastBlock = false; while (!isLastBlock) { b = new byte[4]; raf.Read(b, 0, b.Length); MetadataBlockHeader mbh = new MetadataBlockHeader(b); if (mbh.BlockType == MetadataBlockHeader.BlockTypes.StreamInfo) { b = new byte[mbh.DataLength]; raf.Read(b, 0, b.Length); mbdsi = new MetadataBlockDataStreamInfo(b); if (!mbdsi.Valid) { throw new CannotReadException("FLAC StreamInfo not valid"); } break; } raf.Seek(raf.Position + mbh.DataLength, SeekOrigin.Begin); isLastBlock = mbh.IsLastBlock; mbh = null; //Free memory } EncodingInfo info = new EncodingInfo(); info.Duration = new TimeSpan(mbdsi.Length * TimeSpan.TicksPerSecond); info.ChannelNumber = mbdsi.ChannelNumber; info.SamplingRate = mbdsi.SamplingRate; info.EncodingType = mbdsi.EncodingType; info.ExtraEncodingInfos = ""; info.Bitrate = ComputeBitrate(mbdsi.Length, raf.Length); return(info); }
/* * TODO: Better Implementation of bitrate determination. * Somehow first audio stream makes the day. Then Streamnumber must * be stored, to read the right info out of an optional stream bitrate properties * chunk. Or if that comes first, store all the data and assign it on occurence of the * fist audio stream. * Where is the info about VBR */ public EncodingInfo Read(Stream stream) { EncodingInfo result = new EncodingInfo(); GUID header_guid = GUID.ReadGUID(stream); if (!GUID.GUID_HEADER.Equals(header_guid)) { return(result); } BinaryReader reader = new BinaryReader(stream); // Skip length of header stream.Seek(8, SeekOrigin.Current); // Read the number of chunks. uint chunk_count = reader.ReadUInt32(); // Skip unknown bytes stream.Seek(2, SeekOrigin.Current); // Two flags, When both are set, all Information needed has ben read bool is_file_header_parsed = false; bool is_stream_chunk_parsed = false; // Now read the chunks for (int i = 0; i < chunk_count && !(is_file_header_parsed && is_stream_chunk_parsed); i++) { long chunk_start = stream.Position; GUID current_guid = GUID.ReadGUID(stream); ulong chunk_len = reader.ReadUInt64(); if (GUID.GUID_FILE.Equals(current_guid)) { stream.Seek(48, SeekOrigin.Current); result.Duration = new TimeSpan((long)reader.ReadUInt64()); is_file_header_parsed = true; } else if (GUID.GUID_STREAM.Equals(current_guid)) { GUID streamTypeGUID = GUID.ReadGUID(stream); if (GUID.GUID_AUDIOSTREAM.Equals(streamTypeGUID)) { // Jump over ignored values. stream.Seek(38, SeekOrigin.Current); result.EncodingType = GetFormatDescription(reader.ReadUInt16()); result.ChannelNumber = reader.ReadUInt16(); result.SamplingRate = (int)reader.ReadUInt32(); result.Bitrate = (int)(reader.ReadUInt32() * 8 / 1000); is_stream_chunk_parsed = true; } } stream.Seek((long)((ulong)chunk_start + chunk_len - (ulong)stream.Position), SeekOrigin.Current); } return(result); }
public EncodingChooser(EncodingInfo encoding) { InitializeComponent(); foreach (var encode in Encoding.GetEncodings().OrderBy(x => x.DisplayName)) { listBox1.Items.Add(encode.DisplayName); } SelectEncoding(encoding); }
private void InitCodePage() { this.cbCodePage.Items.Clear(); for (int i = 0; i < EncodingPage.GetAllCodePages().Length; i++) { EncodingInfo ei = EncodingPage.GetAllCodePages()[i]; cbCodePage.Items.Add(ei.DisplayName + " (" + ei.CodePage.ToString() + ")"); } }
private void chooser_EncodingChosen(EncodingEventArgs e) { encoding = e.Encoding; Settings.Default.Encoding = encoding.DisplayName; Settings.Default.Save(); LoadLastFile(); UpdateGUI(); this.Focus(); }
protected override Bitmap Transcode(BitmapInfo bitmapInfo, EncodingInfo imageEncoding, IProgress <ProgressReport> progress) { var img = bitmapInfo.Image; var settings = new ImageSettings(BTX.Encodings[imageEncoding.EncodingIndex], img.Width, img.Height); var data = Kanvas.Kolors.Save(img, settings); _format.Texture = Kanvas.Kolors.Load(data, settings); return(_format.Texture); }
private void cboResEncoding_SelectedIndexChanged(object sender, EventArgs e) { EncodingInfo ei = cboResEncoding.SelectedItem as EncodingInfo; if (null == ei) { return; } _ResEncoding = ei.GetEncoding(); }
public override bool Equals(object value) { EncodingInfo that = value as EncodingInfo; if (that != null) { return(this.CodePage == that.CodePage); } return(false); }
/// <summary>获取一个值,该值指示指定的对象是否等于当前的 <see cref="T:System.Text.EncodingInfo" /> 对象。</summary> /// <returns>如果 <paramref name="value" /> 是一个 <see cref="T:System.Text.EncodingInfo" /> 对象且等于当前的 <see cref="T:System.Text.EncodingInfo" /> 对象,则为 true;否则为 false。</returns> /// <param name="value">与当前的 <see cref="T:System.Text.EncodingInfo" /> 对象进行比较的对象。</param> /// <filterpriority>1</filterpriority> public override bool Equals(object value) { EncodingInfo encodingInfo = value as EncodingInfo; if (encodingInfo != null) { return(this.CodePage == encodingInfo.CodePage); } return(false); }
public EncodingInfo Read( Stream raf ) { EncodingInfo info = new EncodingInfo(); //Begin info fetch------------------------------------------- if ( raf.Length == 0 ) { //Empty File throw new CannotReadException("File is empty"); } raf.Seek( 0 , SeekOrigin.Begin); //MP+ Header string byte[] b = new byte[4]; raf.Read(b, 0, b.Length); string mpc = new string(System.Text.Encoding.ASCII.GetChars(b)); if (mpc != "MAC ") { throw new CannotReadException("'MAC ' Header not found"); } b = new byte[4]; raf.Read(b, 0, b.Length); int version = Utils.GetNumber(b, 0,3); if(version < 3970) throw new CannotReadException("Monkey Audio version <= 3.97 is not supported"); b = new byte[44]; raf.Read(b, 0, b.Length); MonkeyDescriptor md = new MonkeyDescriptor(b); b = new byte[24]; raf.Read(b, 0, b.Length); MonkeyHeader mh = new MonkeyHeader(b); raf.Seek(md.RiffWavOffset, SeekOrigin.Begin); b = new byte[12]; raf.Read(b, 0, b.Length); WavRIFFHeader wrh = new WavRIFFHeader(b); if(!wrh.Valid) throw new CannotReadException("No valid RIFF Header found"); b = new byte[24]; raf.Read(b, 0, b.Length); WavFormatHeader wfh = new WavFormatHeader(b); if(!wfh.Valid) throw new CannotReadException("No valid WAV Header found"); info.Length = mh.Length; info.ChannelNumber = wfh.ChannelNumber ; info.SamplingRate = wfh.SamplingRate ; info.Bitrate = ComputeBitrate(info.Length, raf.Length) ; info.EncodingType = "Monkey Audio v" + (((double)version)/1000)+", compression level "+mh.CompressionLevel; info.ExtraEncodingInfos = ""; return info; }
public static Encoding parseText(String valueText) { EncodingInfo match = Encoding.GetEncodings().FirstOrDefault(enc => TextUtil.isEqualsIgnoreCase(enc.Name, valueText)); if (match == null) { throw new InvalidArgumentException("Could not convert text '{0}' to an encoding", valueText); } return(match.GetEncoding()); }
public static string GetEncodingsText() { StringBuilder builder = new StringBuilder(); builder.AppendLine("# Awailable encodings"); builder.AppendLine(); EncodingInfo[] infos = Encoding.GetEncodings(); int cols = 4; int rows = Math.Max(1, (infos.Length + cols - 1) / cols); EncodingInfo[,] grid = new EncodingInfo[cols, rows]; for (int i = 0; i < infos.Length; ++i) { EncodingInfo info = infos[i]; grid[i / rows, i % rows] = info; } int[] maxSizes = new int[cols]; for (int col = 0; col < cols; ++col) { for (int row = 0; row < rows; ++row) { EncodingInfo info = grid[col, row]; string name = info.Name + " bom"; if (info != null && maxSizes[col] < name.Length) { maxSizes[col] = name.Length; } } } for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { EncodingInfo info = grid[col, row]; if (info != null) { string name = info.Name + " bom"; builder.Append(name); builder.Append(new string(' ', maxSizes[col] - name.Length)); } else { builder.Append(new string(' ', maxSizes[col])); } if (col != cols - 1) { builder.Append(" │ "); } } builder.AppendLine(); } return(builder.ToString()); }
public EncodeSourceType(EncodingInfo info) { if (info != null) { PriceEncode = info.CodePage; PriceEncodeName = info.DisplayName; } else { PriceEncodeName = "<Не установлена>"; } }
private async Task <bool> ImageEncode(BitmapInfo bitmapInfo, EncodingInfo imageEncoding, EncodingInfo paletteEncoding) { if (!tsbFormat.Enabled && !tsbPalette.Enabled) { return(false); } if (_imageAdapter is IIndexedImageAdapter && imageEncoding.IsIndexed && paletteEncoding == null) { return(false); } var report = new Progress <ProgressReport>(); report.ProgressChanged += Report_ProgressChanged; DisablePaletteControls(); DisableImageControls(); bool commitResult; try { ImageTranscodeResult result; if (_imageAdapter is IIndexedImageAdapter indexAdapter && imageEncoding.IsIndexed) { result = await indexAdapter.TranscodeImage(bitmapInfo, imageEncoding, paletteEncoding, report); if (!result.Result) { MessageBox.Show(result.Exception?.ToString() ?? "Encoding was not successful.", "Encoding was not successful", MessageBoxButtons.OK, MessageBoxIcon.Error); UpdateForm(); return(result.Result); } commitResult = indexAdapter.Commit(bitmapInfo, result.Image, imageEncoding, result.Palette, paletteEncoding); } else { result = await _imageAdapter.TranscodeImage(bitmapInfo, imageEncoding, report); if (!result.Result) { MessageBox.Show(result.Exception?.ToString() ?? "Encoding was not successful.", "Encoding was not successful", MessageBoxButtons.OK, MessageBoxIcon.Error); UpdateForm(); return(result.Result); } commitResult = _imageAdapter.Commit(bitmapInfo, result.Image, imageEncoding); } }
/* * TODO: Better Implementation of bitrate determination. * Somehow first audio stream makes the day. Then Streamnumber must * be stored, to read the right info out of an optional stream bitrate properties * chunk. Or if that comes first, store all the data and assign it on occurence of the * fist audio stream. * Where is the info about VBR */ public EncodingInfo Read(Stream stream) { EncodingInfo result = new EncodingInfo(); GUID header_guid = GUID.ReadGUID(stream); if(!GUID.GUID_HEADER.Equals(header_guid)) { return result; } BinaryReader reader = new BinaryReader(stream); // Skip length of header stream.Seek(8, SeekOrigin.Current); // Read the number of chunks. uint chunk_count = reader.ReadUInt32(); // Skip unknown bytes stream.Seek (2, SeekOrigin.Current); // Two flags, When both are set, all Information needed has ben read bool is_file_header_parsed = false; bool is_stream_chunk_parsed = false; // Now read the chunks for(int i = 0; i < chunk_count && !(is_file_header_parsed && is_stream_chunk_parsed); i++) { long chunk_start = stream.Position; GUID current_guid = GUID.ReadGUID(stream); ulong chunk_len = reader.ReadUInt64(); if(GUID.GUID_FILE.Equals(current_guid)) { stream.Seek(48, SeekOrigin.Current); result.Duration = new TimeSpan((long)reader.ReadUInt64()); is_file_header_parsed = true; } else if(GUID.GUID_STREAM.Equals(current_guid)) { GUID streamTypeGUID = GUID.ReadGUID(stream); if(GUID.GUID_AUDIOSTREAM.Equals(streamTypeGUID)) { // Jump over ignored values. stream.Seek(38, SeekOrigin.Current); result.EncodingType = GetFormatDescription(reader.ReadUInt16()); result.ChannelNumber = reader.ReadUInt16(); result.SamplingRate = (int)reader.ReadUInt32(); result.Bitrate = (int)(reader.ReadUInt32() * 8 / 1000); is_stream_chunk_parsed = true; } } stream.Seek((long)((ulong)chunk_start + chunk_len - (ulong)stream.Position), SeekOrigin.Current); } return result; }
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { EncodingInfo info = value as EncodingInfo; if (info != null) { return(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", info.CodePage, info.DisplayName)); } else { return(Binding.DoNothing); } }
public static string CreateNfoContents(string ripper, Tags tags, EncodingInfo encodingInfo, Chapters chapters) { int _hours = (int)tags.duration.TotalHours; string myDuration = (_hours > 0 ? _hours + " hours, " : "") + tags.duration.Minutes + " minutes, " + tags.duration.Seconds + " seconds"; string str4 = "General Information\r\n" + "===================\r\n" + " Title: " + tags.title + "\r\n" + " Author: " + tags.author + "\r\n" + " Read By: " + tags.narrator + "\r\n" + " Copyright: " + tags.year + "\r\n" + " Audiobook Copyright: " + tags.year + "\r\n"; if (tags.genre != "") { str4 = str4 + " Genre: " + tags.genre + "\r\n"; } string s = str4 + " Publisher: " + tags.publisher + "\r\n" + " Duration: " + myDuration + "\r\n" + " Chapters: " + chapters.Count() + "\r\n" + "\r\n" + "\r\n" + "Media Information\r\n" + "=================\r\n" + " Source Format: Audible AAX\r\n" + " Source Sample Rate: " + encodingInfo.sampleRate + " Hz\r\n" + " Source Channels: " + encodingInfo.channels + "\r\n" + " Source Bitrate: " + encodingInfo.originalBitrate + " kbits\r\n" + "\r\n" + " Lossless Encode: Yes\r\n" + " Encoded Codec: AAC / M4B\r\n" + " Encoded Sample Rate: " + encodingInfo.sampleRate + " Hz\r\n" + " Encoded Channels: " + encodingInfo.channels + "\r\n" + " Encoded Bitrate: " + encodingInfo.originalBitrate + " kbits\r\n" + "\r\n" + " Ripper: " + ripper + "\r\n" + "\r\n" + "\r\n" + "Book Description\r\n" + "================\r\n" + tags.comments; return(s); }
public static string CreateContents(string ripper, Tags tags, EncodingInfo encodingInfo, Chapters chapters) { var _hours = (int)tags.duration.TotalHours; var myDuration = (_hours > 0 ? _hours + " hours, " : "") + tags.duration.Minutes + " minutes, " + tags.duration.Seconds + " seconds"; var header = "General Information\r\n" + "===================\r\n" + $" Title: {tags.title}\r\n" + $" Author: {tags.author}\r\n" + $" Read By: {tags.narrator}\r\n" + $" Copyright: {tags.year}\r\n" + $" Audiobook Copyright: {tags.year}\r\n"; if (tags.genre != "") { header += $" Genre: {tags.genre}\r\n"; } var s = header + $" Publisher: {tags.publisher}\r\n" + $" Duration: {myDuration}\r\n" + $" Chapters: {chapters.Count}\r\n" + "\r\n" + "\r\n" + "Media Information\r\n" + "=================\r\n" + " Source Format: Audible AAX\r\n" + $" Source Sample Rate: {encodingInfo.sampleRate} Hz\r\n" + $" Source Channels: {encodingInfo.channels}\r\n" + $" Source Bitrate: {encodingInfo.originalBitrate} kbits\r\n" + "\r\n" + " Lossless Encode: Yes\r\n" + " Encoded Codec: AAC / M4B\r\n" + $" Encoded Sample Rate: {encodingInfo.sampleRate} Hz\r\n" + $" Encoded Channels: {encodingInfo.channels}\r\n" + $" Encoded Bitrate: {encodingInfo.originalBitrate} kbits\r\n" + "\r\n" + $" Ripper: {ripper}\r\n" + "\r\n" + "\r\n" + "Book Description\r\n" + "================\r\n" + tags.comments; return(s); }
public EncodingInfo Read( Stream raf ) { EncodingInfo info = new EncodingInfo(); //Begin info fetch------------------------------------------- if ( raf.Length==0 ) { //Empty File throw new CannotReadException("File is empty"); } raf.Seek( 0 , SeekOrigin.Begin); //MP+ Header string byte[] b = new byte[3]; raf.Read(b, 0, b.Length); string mpc = new string(System.Text.Encoding.ASCII.GetChars(b)); if (mpc != "MP+" && mpc == "ID3") { //TODO Do we have to do this ?? //we have an ID3v2 tag at the beginning //We quickly jump to MPC data raf.Seek(6, SeekOrigin.Begin); int tagSize = ReadSyncsafeInteger(raf); raf.Seek(tagSize+10, SeekOrigin.Begin); //retry to read MPC stream b = new byte[3]; raf.Read(b, 0, b.Length); mpc = new string(System.Text.Encoding.ASCII.GetChars(b)); if (mpc != "MP+") { //We could definitely not go there throw new CannotReadException("MP+ Header not found"); } } else if (mpc != "MP+"){ throw new CannotReadException("MP+ Header not found"); } b = new byte[25]; raf.Read(b, 0, b.Length); MpcHeader mpcH = new MpcHeader(b); //We only support v7 Stream format, so if it isn't v7, then returned values //will be bogus, and the file will be ignored double pcm = mpcH.SamplesNumber; info.Duration = new TimeSpan((long)(pcm * 1152 / mpcH.SamplingRate) * TimeSpan.TicksPerSecond); info.ChannelNumber = mpcH.ChannelNumber; info.SamplingRate = mpcH.SamplingRate; info.EncodingType = mpcH.EncodingType; info.ExtraEncodingInfos = mpcH.EncoderInfo; info.Bitrate = ComputeBitrate( info.Duration.Seconds, raf.Length ); return info; }
public EncodingInfo Read(Stream raf) { //Read the infos-------------------------------------------------------- if (raf.Length == 0) { //Empty File throw new CannotReadException("Error: File empty"); } raf.Seek(0, SeekOrigin.Begin); //FLAC Header string byte[] b = new byte[4]; raf.Read(b, 0, b.Length); string flac = new string(System.Text.Encoding.ASCII.GetChars(b)); if (flac != "fLaC") { throw new CannotReadException("fLaC Header not found"); } MetadataBlockDataStreamInfo mbdsi = null; bool isLastBlock = false; while (!isLastBlock) { b = new byte[4]; raf.Read(b, 0, b.Length); MetadataBlockHeader mbh = new MetadataBlockHeader(b); if (mbh.BlockType == (int) MetadataBlockHeader.BlockTypes.StreamInfo) { b = new byte[mbh.DataLength]; raf.Read(b, 0, b.Length); mbdsi = new MetadataBlockDataStreamInfo(b); if (!mbdsi.Valid) { throw new CannotReadException("FLAC StreamInfo not valid"); } break; } raf.Seek(raf.Position + mbh.DataLength, SeekOrigin.Begin); isLastBlock = mbh.IsLastBlock; mbh = null; //Free memory } EncodingInfo info = new EncodingInfo(); info.Length = mbdsi.Length; info.ChannelNumber = mbdsi.ChannelNumber; info.SamplingRate = mbdsi.SamplingRate; info.EncodingType = mbdsi.EncodingType; info.ExtraEncodingInfos = ""; info.Bitrate = ComputeBitrate(mbdsi.Length, raf.Length); return info; }
public EncodingInfo Read( Stream raf ) { EncodingInfo encodingInfo = new EncodingInfo(); //Begin info fetch------------------------------------------- if ( raf.Length == 0 ) { throw new CannotReadException("File is empty"); } int id3TagSize = 0; raf.Seek( 0 , SeekOrigin.Begin); // skip id3v2 tag, because there may be long pictures inside with // slows reading and they can be not unsyncronized byte[] bbb = new byte[3]; raf.Read(bbb, 0, 3); raf.Seek(0, SeekOrigin.Begin); string ID3 = new string(System.Text.Encoding.ASCII.GetChars(bbb)); if (ID3 == "ID3") { raf.Seek(6, SeekOrigin.Begin); id3TagSize = ReadSyncsafeInteger(raf); raf.Seek(id3TagSize+10, SeekOrigin.Begin); } MPEGFrame firstFrame = null; byte[] b = new byte[4]; raf.Read(b, 0, b.Length); // search for sync mark, but also for a right bitrate, samplerate and layer(that way you can // read corrupted but playable files) while ( !( (b[0]&0xFF)==0xFF && (b[1]&0xE0)==0xE0 && (b[1]&0x06)!=0 && (b[2]&0xF0)!=0xF0 && (b[2]&0x0C)!=0x0C ) && raf.Position < raf.Length-4) { raf.Seek( -3, SeekOrigin.Current); raf.Read(b, 0, b.Length); } firstFrame = new MPEGFrame( b ); if ( firstFrame == null || !firstFrame.Valid || firstFrame.SamplingRate == 0 ) { //MP3File corrupted, no valid MPEG frames throw new CannotReadException("Error: could not synchronize to first mp3 frame"); } int firstFrameLength = firstFrame.FrameLength; //---------------------------------------------------------------------------- int skippedLength = 0; if ( firstFrame.MpegVersion == MPEGFrame.MPEG_VERSION_1 && firstFrame.ChannelMode == MPEGFrame.CHANNEL_MODE_MONO ) { raf.Seek( 17, SeekOrigin.Current ); skippedLength += 17; } else if ( firstFrame.MpegVersion == MPEGFrame.MPEG_VERSION_1 ) { raf.Seek( 32 , SeekOrigin.Current ); skippedLength += 32; } else if ( firstFrame.MpegVersion == MPEGFrame.MPEG_VERSION_2 && firstFrame.ChannelMode == MPEGFrame.CHANNEL_MODE_MONO ) { raf.Seek(9, SeekOrigin.Current ); skippedLength += 9; } else if ( firstFrame.MpegVersion == MPEGFrame.MPEG_VERSION_2 ) { raf.Seek( 17, SeekOrigin.Current ); skippedLength += 17; } int optionalFrameLength = 0; byte[] xingPart1 = new byte[16]; raf.Read( xingPart1, 0, xingPart1.Length ); raf.Seek( 100 , SeekOrigin.Current ); byte[] xingPart2 = new byte[4]; raf.Read( xingPart2, 0, xingPart2.Length ); XingMPEGFrame currentXingFrame = new XingMPEGFrame( xingPart1, xingPart2 ); //System.err.println(currentXingFrame); if ( !currentXingFrame.Valid ) raf.Seek( - 120 - skippedLength - 4 , SeekOrigin.Current ); //120 Xing bytes, unused skipped bytes and 4 mpeg info bytes //Skipping Xing frame reading else { optionalFrameLength += 120; byte[] lameHeader = new byte[36]; raf.Read( lameHeader, 0, lameHeader.Length); LameMPEGFrame currentLameFrame = new LameMPEGFrame( lameHeader ); if ( !currentLameFrame.Valid ) raf.Seek( - 36 , SeekOrigin.Current ); //Skipping Lame frame reading else optionalFrameLength += 36; //Lame Frame read } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //Length computation if ( currentXingFrame.Valid ) raf.Seek( firstFrameLength - ( skippedLength + optionalFrameLength + 4 ) , SeekOrigin.Current ); double timePerFrame = ((double) firstFrame.SampleNumber) / firstFrame.SamplingRate; double lengthInSeconds; if ( currentXingFrame.Valid ) { //Preffered Method: extracts time length with the Xing Header (vbr:Xing or cbr:Info)******************** lengthInSeconds = ( timePerFrame * currentXingFrame.FrameCount ); encodingInfo.Vbr = currentXingFrame.IsVbr; int fs = currentXingFrame.FileSize; encodingInfo.Bitrate = (int)( ( (fs==0 ? raf.Length-id3TagSize : fs) * 8 ) / ( timePerFrame * currentXingFrame.FrameCount * 1000 ) ); } else { //Default Method: extracts time length using the file length and assuming CBR******************** int frameLength = firstFrame.FrameLength; if (frameLength==0) throw new CannotReadException("Error while reading header(maybe file is corrupted, or missing first mpeg frame before xing header)"); lengthInSeconds = timePerFrame * ((raf.Length-id3TagSize) / frameLength); encodingInfo.Vbr = false; encodingInfo.Bitrate = firstFrame.Bitrate ; } //Populates encodingInfo---------------------------------------------------- encodingInfo.Length = (int) lengthInSeconds; encodingInfo.ChannelNumber = firstFrame.ChannelNumber; encodingInfo.SamplingRate = firstFrame.SamplingRate; encodingInfo.EncodingType = firstFrame.MpegVersionToString( firstFrame.MpegVersion ) + " || " + firstFrame.LayerToString( firstFrame.LayerVersion ); encodingInfo.ExtraEncodingInfos = ""; return encodingInfo; }
public EncodingInfo Read( Stream raf ) { EncodingInfo info = new EncodingInfo(); long oldPos = 0; //Reads the file encoding infos ----------------------------------- raf.Seek( 0 , SeekOrigin.Begin); double PCMSamplesNumber = -1; raf.Seek( raf.Length-2, SeekOrigin.Begin); while(raf.Position >= 4) { if(raf.ReadByte()==0x53) { raf.Seek( raf.Position - 4, SeekOrigin.Begin); byte[] ogg = new byte[3]; raf.Read(ogg, 0, 3); if(ogg[0]==0x4F && ogg[1]==0x67 && ogg[2]==0x67) { raf.Seek( raf.Position - 3, SeekOrigin.Begin); oldPos = raf.Position; raf.Seek(raf.Position + 26, SeekOrigin.Begin); int _pageSegments = raf.ReadByte()&0xFF; //Unsigned raf.Seek( oldPos , SeekOrigin.Begin); byte[] _b = new byte[27 + _pageSegments]; raf.Read( _b, 0, _b.Length ); OggPageHeader _pageHeader = new OggPageHeader( _b ); raf.Seek(0, SeekOrigin.Begin); PCMSamplesNumber = _pageHeader.AbsoluteGranulePosition; break; } } raf.Seek( raf.Position - 2, SeekOrigin.Begin); } if(PCMSamplesNumber == -1){ throw new CannotReadException("Error: Could not find the Ogg Setup block"); } //Supposing 1st page = codec infos // 2nd page = comment+decode info //...Extracting 1st page byte[] b = new byte[4]; oldPos = raf.Position; raf.Seek(26, SeekOrigin.Begin); int pageSegments = raf.ReadByte()&0xFF; //Unsigned raf.Seek( oldPos , SeekOrigin.Begin); b = new byte[27 + pageSegments]; raf.Read( b , 0, b .Length); OggPageHeader pageHeader = new OggPageHeader( b ); byte[] vorbisData = new byte[pageHeader.PageLength]; raf.Read( vorbisData , 0, vorbisData.Length); VorbisCodecHeader vorbisCodecHeader = new VorbisCodecHeader( vorbisData ); //Populates encodingInfo---------------------------------------------------- info.Duration = new TimeSpan((long)(PCMSamplesNumber / vorbisCodecHeader.SamplingRate) * TimeSpan.TicksPerSecond); info.ChannelNumber = vorbisCodecHeader.ChannelNumber; info.SamplingRate = vorbisCodecHeader.SamplingRate; info.EncodingType = vorbisCodecHeader.EncodingType; info.ExtraEncodingInfos = ""; if(vorbisCodecHeader.NominalBitrate != 0 && vorbisCodecHeader.MaxBitrate == vorbisCodecHeader.NominalBitrate && vorbisCodecHeader.MinBitrate == vorbisCodecHeader.NominalBitrate) { //CBR info.Bitrate = vorbisCodecHeader.NominalBitrate; info.Vbr = false; } else if(vorbisCodecHeader.NominalBitrate != 0 && vorbisCodecHeader.MaxBitrate == 0 && vorbisCodecHeader.MinBitrate == 0) { //Average vbr info.Bitrate = vorbisCodecHeader.NominalBitrate; info.Vbr = true; } else { info.Bitrate = ComputeBitrate( (int)info.Duration.TotalSeconds, raf.Length ); info.Vbr = true; } return info; }
public EncodingInfo Read(Stream raf) { EncodingInfo info = new EncodingInfo(); return info; }