From c2dd43ed38083e5f07bc8d39ba22d343e28bbf88 Mon Sep 17 00:00:00 2001 From: tautcony Date: Sun, 22 Jan 2017 13:44:57 +0800 Subject: [PATCH 01/31] Fix toLower in GetCueSheet --- Time_Shift/Util/ChapterData/CueData.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Time_Shift/Util/ChapterData/CueData.cs b/Time_Shift/Util/ChapterData/CueData.cs index 213e706..b77f6ce 100644 --- a/Time_Shift/Util/ChapterData/CueData.cs +++ b/Time_Shift/Util/ChapterData/CueData.cs @@ -207,7 +207,7 @@ private static string GetCueSheet(byte[] buffer, string type) for (int i = 0; i < length; ++i) { if (buffer[i] >= 'A' && buffer[i] <= 'Z') - buffer[i] -= 'a' - 'A'; + buffer[i] = (byte)(buffer[i] - 'A' + 'a'); switch ((char)buffer[i]) { case 'c': state = 1; break;//C From 535790d6324105fd24507da5057f3d2f26267979 Mon Sep 17 00:00:00 2001 From: tautcony Date: Sun, 22 Jan 2017 14:01:39 +0800 Subject: [PATCH 02/31] Fix flac size calculate. --- Time_Shift/Util/ChapterData/FlacData.cs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Time_Shift/Util/ChapterData/FlacData.cs b/Time_Shift/Util/ChapterData/FlacData.cs index 27fa71b..c525b5e 100644 --- a/Time_Shift/Util/ChapterData/FlacData.cs +++ b/Time_Shift/Util/ChapterData/FlacData.cs @@ -10,11 +10,11 @@ namespace ChapterTool.Util.ChapterData { public class FlacInfo { - public long RawLength { get; set; } - public long TrueLength { get; } - public double CompressRate { get; } - public bool HasCover { get; set; } - public string Encoder { get; set; } + public long RawLength { get; set; } + public long TrueLength { get; set; } + public double CompressRate => TrueLength / (double)RawLength; + public bool HasCover { get; set; } + public string Encoder { get; set; } public Dictionary VorbisComment { get; set; } public FlacInfo() @@ -47,7 +47,7 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) using (var fs = File.Open(flacPath, FileMode.Open, FileAccess.Read)) { if (fs.Length < SizeThreshold) return new FlacInfo(); - FlacInfo info = new FlacInfo(); + FlacInfo info = new FlacInfo {TrueLength = fs.Length}; var header = fs.ReadBytes(4); if (Encoding.ASCII.GetString(header, 0, 4) != "fLaC") throw new InvalidDataException($"Except an flac but get an {Encoding.ASCII.GetString(header, 0, 4)}"); @@ -61,7 +61,7 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) bool lastMetadataBlock = blockHeader >> 31 == 0x1; BlockType blockType = (BlockType)((blockHeader >> 24) & 0x7f); int length = (int) (blockHeader & 0xffffff); - info.RawLength += length; + info.TrueLength -= length; OnLog?.Invoke($"|+{blockType} with Length: {length}"); switch (blockType) { @@ -103,7 +103,7 @@ private static void ParseStreamInfo(Stream fs, ref FlacInfo info) int bitPerSample = (int) br.GetBits(5)+1; int totalSample = (int) br.GetBits(36); var md5 = fs.ReadBytes(16); - info.RawLength += channelCount * bitPerSample * totalSample; + info.RawLength = channelCount * bitPerSample / 8 * totalSample; OnLog?.Invoke($" | minimum block size: {minBlockSize}, maximum block size: {maxBlockSize}"); OnLog?.Invoke($" | minimum frame size: {minFrameSize}, maximum frame size: {maxFrameSize}"); OnLog?.Invoke($" | Sample rate: {sampleRate}Hz, bits per sample: {bitPerSample}-bit"); @@ -148,7 +148,7 @@ private static void ParsePicture(Stream fs, ref FlacInfo info) int indexedColorCount = (int) fs.ReadUInt(); int pictureDataLength = (int) fs.ReadUInt(); fs.Seek(pictureDataLength, SeekOrigin.Current); - info.RawLength += pictureDataLength; + info.TrueLength -= pictureDataLength; info.HasCover = true; OnLog?.Invoke($" | picture type: {mimeType}"); OnLog?.Invoke($" | attribute: {pictureWidth}px*{pictureHeight}px@{colorDepth}-bit"); @@ -177,7 +177,7 @@ private static uint ReadUInt(this Stream fs, bool littleEndian = false) if (!littleEndian) buffer = buffer.Reverse().ToArray(); return BitConverter.ToUInt32(buffer, 0); } - + private static byte[] ReadBytes(this Stream fs, int length) { var ret = new byte[length]; From 27f43f28b4290f8f566b4f3ed29d5dca9381cedf Mon Sep 17 00:00:00 2001 From: tautcony Date: Sun, 22 Jan 2017 21:31:34 +0800 Subject: [PATCH 03/31] Use `Action` to replace the `delegate`. --- Time_Shift/Knuckleball/ChapterList.cs | 4 +--- Time_Shift/Util/ChapterData/BDMVData.cs | 4 +--- Time_Shift/Util/ChapterData/MatroskaData.cs | 4 +--- Time_Shift/Util/ChapterData/MplsData.cs | 4 +--- Time_Shift/Util/ChapterData/OgmData.cs | 4 +--- 5 files changed, 5 insertions(+), 15 deletions(-) diff --git a/Time_Shift/Knuckleball/ChapterList.cs b/Time_Shift/Knuckleball/ChapterList.cs index aeaebba..51b92da 100644 --- a/Time_Shift/Knuckleball/ChapterList.cs +++ b/Time_Shift/Knuckleball/ChapterList.cs @@ -31,9 +31,7 @@ public sealed class ChapterList : IList private List chapters = new List(); private HashSet hashedIndex = new HashSet(); - public delegate void LogEventHandler(string message); - - public static event LogEventHandler OnLog; + public static event Action OnLog; /// /// Prevents a default instance of the class from being created. diff --git a/Time_Shift/Util/ChapterData/BDMVData.cs b/Time_Shift/Util/ChapterData/BDMVData.cs index 50397d5..03ba0b6 100644 --- a/Time_Shift/Util/ChapterData/BDMVData.cs +++ b/Time_Shift/Util/ChapterData/BDMVData.cs @@ -9,9 +9,7 @@ namespace ChapterTool.Util.ChapterData { public static class BDMVData { - public delegate void LogEventHandler(string message); - - public static event LogEventHandler OnLog; + public static event Action OnLog; private static readonly Regex RDiskInfo = new Regex(@"(?\d)\) (?\d+\.mpls), (?:(?:(?\d+:\d+:\d+)[\n\s\b]*(?.+\.m2ts))|(?:(?.+\.m2ts), (?\d+:\d+:\d+)))", RegexOptions.Compiled); diff --git a/Time_Shift/Util/ChapterData/MatroskaData.cs b/Time_Shift/Util/ChapterData/MatroskaData.cs index d0bf4dd..4c98e98 100644 --- a/Time_Shift/Util/ChapterData/MatroskaData.cs +++ b/Time_Shift/Util/ChapterData/MatroskaData.cs @@ -33,9 +33,7 @@ internal class MatroskaData private readonly string _mkvextractPath; - public delegate void LogEventHandler(string message); - - public static event LogEventHandler OnLog; + public static event Action OnLog; public MatroskaData() { diff --git a/Time_Shift/Util/ChapterData/MplsData.cs b/Time_Shift/Util/ChapterData/MplsData.cs index bb510aa..6bf9412 100644 --- a/Time_Shift/Util/ChapterData/MplsData.cs +++ b/Time_Shift/Util/ChapterData/MplsData.cs @@ -40,9 +40,7 @@ public class MplsData public static readonly decimal[] FrameRate = { 0M, 24000M / 1001, 24M, 25M, 30000M / 1001, 0M, 50M, 60000M / 1001 }; - public delegate void LogEventHandler(string message); - - public static event LogEventHandler OnLog; + public static event Action OnLog; public MplsData(string path) { diff --git a/Time_Shift/Util/ChapterData/OgmData.cs b/Time_Shift/Util/ChapterData/OgmData.cs index 9f54bcd..682979a 100644 --- a/Time_Shift/Util/ChapterData/OgmData.cs +++ b/Time_Shift/Util/ChapterData/OgmData.cs @@ -29,9 +29,7 @@ public static class OgmData private static readonly Regex RTimeCodeLine = new Regex(@"^\s*CHAPTER\d+\s*=\s*(.*)", RegexOptions.Compiled); private static readonly Regex RNameLine = new Regex(@"^\s*CHAPTER\d+NAME\s*=\s*(?.*)", RegexOptions.Compiled); - public delegate void LogEventHandler(string message); - - public static event LogEventHandler OnLog; + public static event Action OnLog; private enum LineState { From a102cef04f8f0885067f2485a4ec77898c0347e0 Mon Sep 17 00:00:00 2001 From: tautcony Date: Wed, 25 Jan 2017 10:15:27 +0800 Subject: [PATCH 04/31] Add OnLog to IData. --- Time_Shift/ChapterData/IData.cs | 5 ++++- Time_Shift/Util/ChapterData/CueData.cs | 1 + Time_Shift/Util/ChapterData/FlacData.cs | 29 ++++++++++++++++++++----- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/Time_Shift/ChapterData/IData.cs b/Time_Shift/ChapterData/IData.cs index c9ed6f2..1c1bc43 100644 --- a/Time_Shift/ChapterData/IData.cs +++ b/Time_Shift/ChapterData/IData.cs @@ -1,4 +1,5 @@ -using ChapterTool.Util; +using System; +using ChapterTool.Util; namespace ChapterTool.ChapterData { @@ -9,5 +10,7 @@ public interface IData// : IEnumerable ChapterInfo this[int index] { get; } string ChapterType { get; } + + event Action OnLog; } } diff --git a/Time_Shift/Util/ChapterData/CueData.cs b/Time_Shift/Util/ChapterData/CueData.cs index b77f6ce..4e50bd0 100644 --- a/Time_Shift/Util/ChapterData/CueData.cs +++ b/Time_Shift/Util/ChapterData/CueData.cs @@ -303,5 +303,6 @@ public ChapterInfo this[int index] } public string ChapterType { get; } = "CUE"; + public event Action OnLog; } } \ No newline at end of file diff --git a/Time_Shift/Util/ChapterData/FlacData.cs b/Time_Shift/Util/ChapterData/FlacData.cs index c525b5e..cf7a134 100644 --- a/Time_Shift/Util/ChapterData/FlacData.cs +++ b/Time_Shift/Util/ChapterData/FlacData.cs @@ -1,4 +1,23 @@ -using System; +// **************************************************************************** +// +// Copyright (C) 2014-2017 TautCony (TautCony@vcb-s.com) +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// **************************************************************************** +using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -48,9 +67,9 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) { if (fs.Length < SizeThreshold) return new FlacInfo(); FlacInfo info = new FlacInfo {TrueLength = fs.Length}; - var header = fs.ReadBytes(4); - if (Encoding.ASCII.GetString(header, 0, 4) != "fLaC") - throw new InvalidDataException($"Except an flac but get an {Encoding.ASCII.GetString(header, 0, 4)}"); + var header = Encoding.ASCII.GetString(fs.ReadBytes(4), 0, 4); + if (header != "fLaC") + throw new InvalidDataException($"Except an flac but get an {header}"); //METADATA_BLOCK_HEADER //1-bit Last-metadata-block flag //7-bit BLOCK_TYPE @@ -82,7 +101,7 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) fs.Seek(length, SeekOrigin.Current); break; default: - throw new ArgumentOutOfRangeException($"Invalid BLOCK_TYPE: 0x{blockType:X}"); + throw new ArgumentOutOfRangeException($"Invalid BLOCK_TYPE: 0x{blockType:X2}"); } if (lastMetadataBlock) break; } From 3112e0a033f3a6e8da413a543a234b27136f2b98 Mon Sep 17 00:00:00 2001 From: tautcony Date: Wed, 25 Jan 2017 11:48:40 +0800 Subject: [PATCH 05/31] Pending OnLog use. --- Time_Shift/ChapterData/IData.cs | 2 +- Time_Shift/Util/ChapterData/CueData.cs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Time_Shift/ChapterData/IData.cs b/Time_Shift/ChapterData/IData.cs index 1c1bc43..d1ac3ac 100644 --- a/Time_Shift/ChapterData/IData.cs +++ b/Time_Shift/ChapterData/IData.cs @@ -11,6 +11,6 @@ public interface IData// : IEnumerable string ChapterType { get; } - event Action OnLog; + //event Action OnLog; } } diff --git a/Time_Shift/Util/ChapterData/CueData.cs b/Time_Shift/Util/ChapterData/CueData.cs index 4e50bd0..b77f6ce 100644 --- a/Time_Shift/Util/ChapterData/CueData.cs +++ b/Time_Shift/Util/ChapterData/CueData.cs @@ -303,6 +303,5 @@ public ChapterInfo this[int index] } public string ChapterType { get; } = "CUE"; - public event Action OnLog; } } \ No newline at end of file From bca30fe7e55338f452272426a8e744ed26874f81 Mon Sep 17 00:00:00 2001 From: tautcony Date: Wed, 25 Jan 2017 11:49:31 +0800 Subject: [PATCH 06/31] Add json as a new ouput type. --- Time_Shift/Forms/Form1.Designer.cs | 81 +- Time_Shift/Forms/Form1.cs | 5 +- Time_Shift/Forms/Form1.resx | 1506 +++++++++++++--------------- Time_Shift/Util/ChapterInfo.cs | 30 + 4 files changed, 782 insertions(+), 840 deletions(-) diff --git a/Time_Shift/Forms/Form1.Designer.cs b/Time_Shift/Forms/Form1.Designer.cs index b2a0835..8a8cd92 100644 --- a/Time_Shift/Forms/Form1.Designer.cs +++ b/Time_Shift/Forms/Form1.Designer.cs @@ -85,47 +85,44 @@ private void InitializeComponent() // // btnLoad // - resources.ApplyResources(this.btnLoad, "btnLoad"); this.btnLoad.ContextMenuStrip = this.loadMenuStrip; this.btnLoad.FlatAppearance.BorderColor = System.Drawing.SystemColors.Highlight; this.btnLoad.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(184)))), ((int)(((byte)(184)))), ((int)(((byte)(184))))); this.btnLoad.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(207)))), ((int)(((byte)(207))))); + resources.ApplyResources(this.btnLoad, "btnLoad"); this.btnLoad.Name = "btnLoad"; this.btnLoad.TabStop = false; - this.toolTip1.SetToolTip(this.btnLoad, resources.GetString("btnLoad.ToolTip")); this.btnLoad.UseVisualStyleBackColor = true; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // loadMenuStrip // - resources.ApplyResources(this.loadMenuStrip, "loadMenuStrip"); this.loadMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.reloadToolStripMenuItem, this.appendToolStripMenuItem}); this.loadMenuStrip.Name = "loadMenuStrip"; - this.toolTip1.SetToolTip(this.loadMenuStrip, resources.GetString("loadMenuStrip.ToolTip")); + resources.ApplyResources(this.loadMenuStrip, "loadMenuStrip"); // // reloadToolStripMenuItem // - resources.ApplyResources(this.reloadToolStripMenuItem, "reloadToolStripMenuItem"); this.reloadToolStripMenuItem.Name = "reloadToolStripMenuItem"; + resources.ApplyResources(this.reloadToolStripMenuItem, "reloadToolStripMenuItem"); this.reloadToolStripMenuItem.Click += new System.EventHandler(this.reloadToolStripMenuItem_Click); // // appendToolStripMenuItem // - resources.ApplyResources(this.appendToolStripMenuItem, "appendToolStripMenuItem"); this.appendToolStripMenuItem.Name = "appendToolStripMenuItem"; + resources.ApplyResources(this.appendToolStripMenuItem, "appendToolStripMenuItem"); this.appendToolStripMenuItem.Click += new System.EventHandler(this.appendToolStripMenuItem_Click); // // btnSave // - resources.ApplyResources(this.btnSave, "btnSave"); this.btnSave.FlatAppearance.BorderColor = System.Drawing.SystemColors.Highlight; this.btnSave.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(184)))), ((int)(((byte)(184)))), ((int)(((byte)(184))))); this.btnSave.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(207)))), ((int)(((byte)(207))))); + resources.ApplyResources(this.btnSave, "btnSave"); this.btnSave.Name = "btnSave"; this.btnSave.TabStop = false; - this.toolTip1.SetToolTip(this.btnSave, resources.GetString("btnSave.ToolTip")); this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); this.btnSave.MouseEnter += new System.EventHandler(this.btnSave_MouseEnter); @@ -136,19 +133,17 @@ private void InitializeComponent() // resources.ApplyResources(this.lbPath, "lbPath"); this.lbPath.Name = "lbPath"; - this.toolTip1.SetToolTip(this.lbPath, resources.GetString("lbPath.ToolTip")); this.lbPath.MouseEnter += new System.EventHandler(this.lbPath_MouseEnter); this.lbPath.MouseLeave += new System.EventHandler(this.ToolTipRemoveAll); // // btnTrans // - resources.ApplyResources(this.btnTrans, "btnTrans"); this.btnTrans.FlatAppearance.BorderColor = System.Drawing.SystemColors.Highlight; this.btnTrans.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(184)))), ((int)(((byte)(184)))), ((int)(((byte)(184))))); this.btnTrans.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(207)))), ((int)(((byte)(207))))); + resources.ApplyResources(this.btnTrans, "btnTrans"); this.btnTrans.Name = "btnTrans"; this.btnTrans.TabStop = false; - this.toolTip1.SetToolTip(this.btnTrans, resources.GetString("btnTrans.ToolTip")); this.btnTrans.UseVisualStyleBackColor = true; this.btnTrans.Click += new System.EventHandler(this.refresh_Click); this.btnTrans.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Color_MouseUp); @@ -164,9 +159,9 @@ private void InitializeComponent() // // comboBox1 // - resources.ApplyResources(this.comboBox1, "comboBox1"); this.comboBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + resources.ApplyResources(this.comboBox1, "comboBox1"); this.comboBox1.ForeColor = System.Drawing.SystemColors.WindowText; this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { @@ -179,7 +174,6 @@ private void InitializeComponent() resources.GetString("comboBox1.Items6")}); this.comboBox1.Name = "comboBox1"; this.comboBox1.TabStop = false; - this.toolTip1.SetToolTip(this.comboBox1, resources.GetString("comboBox1.ToolTip")); this.comboBox1.SelectionChangeCommitted += new System.EventHandler(this.comboBox1_SelectionChangeCommitted); // // cbRound @@ -196,24 +190,23 @@ private void InitializeComponent() // // deviationMenuStrip // - resources.ApplyResources(this.deviationMenuStrip, "deviationMenuStrip"); this.deviationMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsmAccuracy}); this.deviationMenuStrip.Name = "contextMenuStrip1"; - this.toolTip1.SetToolTip(this.deviationMenuStrip, resources.GetString("deviationMenuStrip.ToolTip")); + resources.ApplyResources(this.deviationMenuStrip, "deviationMenuStrip"); // // tsmAccuracy // - resources.ApplyResources(this.tsmAccuracy, "tsmAccuracy"); this.tsmAccuracy.Name = "tsmAccuracy"; + resources.ApplyResources(this.tsmAccuracy, "tsmAccuracy"); this.tsmAccuracy.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.Accuracy_DropDownItemClicked); // // numericUpDown1 // - resources.ApplyResources(this.numericUpDown1, "numericUpDown1"); this.numericUpDown1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.numericUpDown1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.numericUpDown1.ForeColor = System.Drawing.SystemColors.WindowText; + resources.ApplyResources(this.numericUpDown1, "numericUpDown1"); this.numericUpDown1.Maximum = new decimal(new int[] { 50, 0, @@ -221,21 +214,18 @@ private void InitializeComponent() 0}); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.TabStop = false; - this.toolTip1.SetToolTip(this.numericUpDown1, resources.GetString("numericUpDown1.ToolTip")); this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); // // lbShift // resources.ApplyResources(this.lbShift, "lbShift"); this.lbShift.Name = "lbShift"; - this.toolTip1.SetToolTip(this.lbShift, resources.GetString("lbShift.ToolTip")); // // cbShift // resources.ApplyResources(this.cbShift, "cbShift"); this.cbShift.Name = "cbShift"; this.cbShift.TabStop = false; - this.toolTip1.SetToolTip(this.cbShift, resources.GetString("cbShift.ToolTip")); this.cbShift.UseVisualStyleBackColor = true; this.cbShift.CheckedChanged += new System.EventHandler(this.cbShift_CheckedChanged); // @@ -250,33 +240,31 @@ private void InitializeComponent() // // comboBox2 // - resources.ApplyResources(this.comboBox2, "comboBox2"); this.comboBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.comboBox2.ContextMenuStrip = this.combineMenuStrip; this.comboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + resources.ApplyResources(this.comboBox2, "comboBox2"); this.comboBox2.ForeColor = System.Drawing.SystemColors.WindowText; this.comboBox2.FormattingEnabled = true; this.comboBox2.Name = "comboBox2"; this.comboBox2.TabStop = false; - this.toolTip1.SetToolTip(this.comboBox2, resources.GetString("comboBox2.ToolTip")); this.comboBox2.SelectionChangeCommitted += new System.EventHandler(this.comboBox2_SelectionChangeCommitted); this.comboBox2.MouseEnter += new System.EventHandler(this.comboBox2_MouseEnter); this.comboBox2.MouseLeave += new System.EventHandler(this.ToolTipRemoveAll); // // combineMenuStrip // - resources.ApplyResources(this.combineMenuStrip, "combineMenuStrip"); this.combineMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.combineToolStripMenuItem}); this.combineMenuStrip.Name = "contextMenuStrip2"; - this.toolTip1.SetToolTip(this.combineMenuStrip, resources.GetString("combineMenuStrip.ToolTip")); + resources.ApplyResources(this.combineMenuStrip, "combineMenuStrip"); this.combineMenuStrip.Closed += new System.Windows.Forms.ToolStripDropDownClosedEventHandler(this.contextMenuStrip2_Closed); this.combineMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip2_Opening); // // combineToolStripMenuItem // - resources.ApplyResources(this.combineToolStripMenuItem, "combineToolStripMenuItem"); this.combineToolStripMenuItem.Name = "combineToolStripMenuItem"; + resources.ApplyResources(this.combineToolStripMenuItem, "combineToolStripMenuItem"); this.combineToolStripMenuItem.Click += new System.EventHandler(this.combineToolStripMenuItem_Click); // // folderBrowserDialog1 @@ -297,19 +285,17 @@ private void InitializeComponent() // // btnLog // - resources.ApplyResources(this.btnLog, "btnLog"); this.btnLog.FlatAppearance.BorderColor = System.Drawing.SystemColors.Highlight; this.btnLog.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(184)))), ((int)(((byte)(184)))), ((int)(((byte)(184))))); this.btnLog.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(207)))), ((int)(((byte)(207))))); + resources.ApplyResources(this.btnLog, "btnLog"); this.btnLog.Name = "btnLog"; this.btnLog.TabStop = false; - this.toolTip1.SetToolTip(this.btnLog, resources.GetString("btnLog.ToolTip")); this.btnLog.UseVisualStyleBackColor = true; this.btnLog.Click += new System.EventHandler(this.btnLog_Click); // // dataGridView1 // - resources.ApplyResources(this.dataGridView1, "dataGridView1"); this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.None; @@ -322,11 +308,11 @@ private void InitializeComponent() this.cFrams}); this.dataGridView1.EnableHeadersVisualStyles = false; this.dataGridView1.GridColor = System.Drawing.SystemColors.Highlight; + resources.ApplyResources(this.dataGridView1, "dataGridView1"); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; this.dataGridView1.RowTemplate.Height = 23; this.dataGridView1.TabStop = false; - this.toolTip1.SetToolTip(this.dataGridView1, resources.GetString("dataGridView1.ToolTip")); this.dataGridView1.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellDoubleClick); this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit); this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_CellMouseUp); @@ -367,9 +353,9 @@ private void InitializeComponent() // // savingType // - resources.ApplyResources(this.savingType, "savingType"); this.savingType.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.savingType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + resources.ApplyResources(this.savingType, "savingType"); this.savingType.FormattingEnabled = true; this.savingType.Items.AddRange(new object[] { resources.GetString("savingType.Items"), @@ -377,72 +363,66 @@ private void InitializeComponent() resources.GetString("savingType.Items2"), resources.GetString("savingType.Items3"), resources.GetString("savingType.Items4"), - resources.GetString("savingType.Items5")}); + resources.GetString("savingType.Items5"), + resources.GetString("savingType.Items6")}); this.savingType.Name = "savingType"; this.savingType.TabStop = false; - this.toolTip1.SetToolTip(this.savingType, resources.GetString("savingType.ToolTip")); this.savingType.SelectedIndexChanged += new System.EventHandler(this.savingType_SelectedIndexChanged); // // lbFormat // resources.ApplyResources(this.lbFormat, "lbFormat"); this.lbFormat.Name = "lbFormat"; - this.toolTip1.SetToolTip(this.lbFormat, resources.GetString("lbFormat.ToolTip")); // // btnPreview // - resources.ApplyResources(this.btnPreview, "btnPreview"); this.btnPreview.FlatAppearance.BorderColor = System.Drawing.SystemColors.Highlight; this.btnPreview.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(184)))), ((int)(((byte)(184)))), ((int)(((byte)(184))))); this.btnPreview.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(207)))), ((int)(((byte)(207))))); + resources.ApplyResources(this.btnPreview, "btnPreview"); this.btnPreview.Name = "btnPreview"; this.btnPreview.TabStop = false; - this.toolTip1.SetToolTip(this.btnPreview, resources.GetString("btnPreview.ToolTip")); this.btnPreview.UseVisualStyleBackColor = true; this.btnPreview.Click += new System.EventHandler(this.btnPreview_Click); this.btnPreview.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnPreview_MouseUp); // // xmlLang // - resources.ApplyResources(this.xmlLang, "xmlLang"); this.xmlLang.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.xmlLang.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + resources.ApplyResources(this.xmlLang, "xmlLang"); this.xmlLang.FormattingEnabled = true; this.xmlLang.Name = "xmlLang"; this.xmlLang.TabStop = false; - this.toolTip1.SetToolTip(this.xmlLang, resources.GetString("xmlLang.ToolTip")); this.xmlLang.SelectionChangeCommitted += new System.EventHandler(this.xmlLang_SelectionChangeCommitted); // // lbXmlLang // resources.ApplyResources(this.lbXmlLang, "lbXmlLang"); this.lbXmlLang.Name = "lbXmlLang"; - this.toolTip1.SetToolTip(this.lbXmlLang, resources.GetString("lbXmlLang.ToolTip")); // // createZonestMenuStrip // - resources.ApplyResources(this.createZonestMenuStrip, "createZonestMenuStrip"); this.createZonestMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.creatZonesToolStripMenuItem, this.ShiftForwardToolStripMenuItem}); this.createZonestMenuStrip.Name = "createZonestMenuStrip"; - this.toolTip1.SetToolTip(this.createZonestMenuStrip, resources.GetString("createZonestMenuStrip.ToolTip")); + resources.ApplyResources(this.createZonestMenuStrip, "createZonestMenuStrip"); // // creatZonesToolStripMenuItem // - resources.ApplyResources(this.creatZonesToolStripMenuItem, "creatZonesToolStripMenuItem"); this.creatZonesToolStripMenuItem.Name = "creatZonesToolStripMenuItem"; + resources.ApplyResources(this.creatZonesToolStripMenuItem, "creatZonesToolStripMenuItem"); this.creatZonesToolStripMenuItem.Click += new System.EventHandler(this.creatZonesToolStripMenuItem_Click); // // ShiftForwardToolStripMenuItem // - resources.ApplyResources(this.ShiftForwardToolStripMenuItem, "ShiftForwardToolStripMenuItem"); this.ShiftForwardToolStripMenuItem.Name = "ShiftForwardToolStripMenuItem"; + resources.ApplyResources(this.ShiftForwardToolStripMenuItem, "ShiftForwardToolStripMenuItem"); this.ShiftForwardToolStripMenuItem.Click += new System.EventHandler(this.ShiftForwardToolStripMenuItem_Click); // // panel1 // - resources.ApplyResources(this.panel1, "panel1"); this.panel1.Controls.Add(this.cbPostFix); this.panel1.Controls.Add(this.textBoxExpression); this.panel1.Controls.Add(this.lbFormat); @@ -455,52 +435,50 @@ private void InitializeComponent() this.panel1.Controls.Add(this.btnLog); this.panel1.Controls.Add(this.lbShift); this.panel1.Controls.Add(this.numericUpDown1); + resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; - this.toolTip1.SetToolTip(this.panel1, resources.GetString("panel1.ToolTip")); // // textBoxExpression // resources.ApplyResources(this.textBoxExpression, "textBoxExpression"); this.textBoxExpression.Name = "textBoxExpression"; - this.toolTip1.SetToolTip(this.textBoxExpression, resources.GetString("textBoxExpression.ToolTip")); this.textBoxExpression.TextChanged += new System.EventHandler(this.textBoxExpression_TextChanged); // // statusStrip1 // - resources.ApplyResources(this.statusStrip1, "statusStrip1"); this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsTips, this.tsProgressBar1, this.tsBtnExpand}); + resources.ApplyResources(this.statusStrip1, "statusStrip1"); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.SizingGrip = false; - this.toolTip1.SetToolTip(this.statusStrip1, resources.GetString("statusStrip1.ToolTip")); // // tsTips // - resources.ApplyResources(this.tsTips, "tsTips"); this.tsTips.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.tsTips.Name = "tsTips"; + resources.ApplyResources(this.tsTips, "tsTips"); this.tsTips.Spring = true; // // tsProgressBar1 // - resources.ApplyResources(this.tsProgressBar1, "tsProgressBar1"); this.tsProgressBar1.Name = "tsProgressBar1"; + resources.ApplyResources(this.tsProgressBar1, "tsProgressBar1"); this.tsProgressBar1.Click += new System.EventHandler(this.progressBar1_Click); // // tsBtnExpand // - resources.ApplyResources(this.tsBtnExpand, "tsBtnExpand"); this.tsBtnExpand.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + resources.ApplyResources(this.tsBtnExpand, "tsBtnExpand"); this.tsBtnExpand.Name = "tsBtnExpand"; this.tsBtnExpand.ShowDropDownArrow = false; this.tsBtnExpand.Click += new System.EventHandler(this.btnExpand_Click); // // Form1 // - resources.ApplyResources(this, "$this"); this.AllowDrop = true; + resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.WhiteSmoke; this.Controls.Add(this.statusStrip1); @@ -518,7 +496,6 @@ private void InitializeComponent() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "Form1"; - this.toolTip1.SetToolTip(this, resources.GetString("$this.ToolTip")); this.TransparencyKey = System.Drawing.Color.FromArgb(((int)(((byte)(18)))), ((int)(((byte)(10)))), ((int)(((byte)(143))))); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index fe9226e..a2c1434 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -782,7 +782,7 @@ private string GeneRateSavePath(int saveType) if (ext == ".mpls" || ext == ".ifo") savePath += $"__{_info.SourceName}"; - string[] saveingTypeSuffix = { ".txt", ".xml", ".qpf", ".TimeCodes.txt", ".TsMuxeR_Meta.txt", ".cue" }; + string[] saveingTypeSuffix = { ".txt", ".xml", ".qpf", ".TimeCodes.txt", ".TsMuxeR_Meta.txt", ".cue" , ".json" }; int index = 1; while (File.Exists($"{savePath}_{index}{saveingTypeSuffix[saveType]}")) ++index; savePath += $"_{index}{saveingTypeSuffix[saveType]}"; @@ -823,6 +823,9 @@ private void SaveFile(int saveType) case 5: //CUE _info.SaveCue(Path.GetFileName(FilePath), savePath, AutoGenName); break; + case 6: //JSON + _info.SaveJsonChapter(savePath, AutoGenName); + break; } tsProgressBar1.Value = 100; tsTips.Text = Resources.Tips_Save_Success; diff --git a/Time_Shift/Forms/Form1.resx b/Time_Shift/Forms/Form1.resx index 1361658..c217b07 100644 --- a/Time_Shift/Forms/Form1.resx +++ b/Time_Shift/Forms/Form1.resx @@ -117,537 +117,847 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 12 - + + 1058, 20 + - - 125, 26 + + 124, 22 - - textBoxExpression + + 重新载入 + + + 124, 22 + + + 追加合并 + + + 125, 48 + + + loadMenuStrip + + + System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 3, 4, 3, 4 + + Flat - - P + + 12, 36 - - tsBtnExpand + + 12, 4, 3, 4 - - 178, 23 + + 80, 40 - - 97, 21 + + + 0 - - 501, 37 + + 载入 - - + + btnLoad - - + + System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + $this - - 4 + + 14 - - 追加合并 + + Flat - - 182, 40 + + 109, 36 - - System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 3, 4, 3, 4 - - 182, 8 + + 80, 40 - - 135, 22 + + 3 - - 重新载入 + + 保存 - - Flat + + btnSave - - System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 帧数 + + $this - - panel1 + + 13 - - tsTips + + 12, 9 - - + + 374, 23 - - 20, 20 + + 5 - - cbShift + + lbPath - - 7 + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 501, 7 + + $this - - 0, 511 + + 12 - - 10 + + Flat - - 413, 9 + + 538, 9 - - 18 + + 4, 4, 4, 4 - - combineMenuStrip + + 30, 30 - - 章节名 + + 2 - - System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + - - + + btnTrans - - 3 + + System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 3, 10 + + $this - - 108, 25 + + 11 + + + Flat 303, 8 - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 3, 4, 3, 4 - - System.Windows.Forms.ToolStripStatusLabel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 97, 21 - - ShiftForwardToolStripMenuItem + + 3 - - loadMenuStrip + + 不使用章节名 - - 30, 30 + + 489, 18 + + + 将章节名重新从Chapter 01开始标记 - - 21 + + cbAutoGenName - - 135, 22 + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - numericUpDown1 + + panel1 - + 7 - - - - - 580, 22 + + Flat - - 68, 17 + + 24000 / 1001 - - lbFormat + + 24000 / 1000 - - System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 25000 / 1000 - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 30000 / 1001 - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + RESER / VED - - panel1 + + 50000 / 1000 - - 4 + + 60000 / 1001 - - 12 + + 447, 52 - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 121, 25 - + 11 - - 57 + + comboBox1 - - cbRound - - - cFrams + + System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 417, 14 + + $this - - 447, 52 + + 10 - - System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + True - - 12, 11 + + 10, 15 + + + 124, 22 - - btnLoad + + 误差范围 - - Flat + + 125, 26 - - - iVBORw0KGgoAAAANSUhEUgAAABsAAAAbCAYAAACN1PRVAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - wwAADsMBx2+oZAAAAFBJREFUSEtjGAWjYBSMguEBmIC4D4gPEIFB6kDqKQJCQHwOiP/jwSB5kDqqAHwW - UtUiGMBmIU0sggFkC2lqEQyALFgApUfBKBgFo4AugIEBAIBHH5UlpwJuAAAAAElFTkSuQmCC - + + deviationMenuStrip - - btnLog + + System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 124, 22 + + Flat - - createZonestMenuStrip + + 417, 14 - - System.Windows.Forms.ToolStripProgressBar, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 76, 21 - - + + 12 - - $this + + 帧数取整 - - OGM + + 右键菜单可设置误差范围 - - 载入 + + cbRound - - + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + $this - - 96, 96 - - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 9 - - 0 + + 501, 7 - - 使用章节名模板 + + 52, 23 - - panel1 + + 16 - - Flat + + numericUpDown1 - - Flat + + System.Windows.Forms.NumericUpDown, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + panel1 - - System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 11 - - 12, 3, 3, 3 + + True - - 124, 22 + + 413, 9 - - 124, 22 + + 68, 17 - - Flat + + 17 - - 56, 17 + + 平移章节号 - - 21 + + lbShift - - System.Windows.Forms.Form, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 3, 4, 3, 4 + + panel1 - - 23 + + 10 - - + + True - - System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Flat - - CUE + + 182, 40 - - TsMuxeR Meta + + 100, 21 - - Time Codes + + 18 - - QPF + + 应用表达式 (t) - - XML + + cbShift - - System.Windows.Forms.StatusStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - comboBox1 + + panel1 - - + + 8 - - 12, 9 + + True - + Flat - - 121, 25 - - - 误差范围 + + 182, 8 - - $this + + 12, 3, 3, 3 - - reloadToolStripMenuItem + + 108, 21 - - $this + + 21 - - 13 + + 使用章节名模板 - - btnSave + + 不取消勾选时将持续生效 - - System.Windows.Forms.FolderBrowserDialog, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + cbChapterName - - 45 + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 生成Zones + + panel1 - - 时间点 + + 6 - - xmlLang + + 590, 18 + + + 124, 22 - - 32 + + 合并章节 - - 保存 + + 125, 26 - - panel1 + + combineMenuStrip - - 5 + + System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Flat - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 318, 51 - - 10 + + 121, 25 - - 30, 30 + + 23 - - btnTrans + + comboBox2 - - System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - True + + $this - - 4, 4, 4, 4 + + 8 - - 9 + + 175, 15 + + + 请设置所要保存的位置 - - System.Windows.Forms.NumericUpDown, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 355, 15 + + + 打开文件 - + True - - 保存格式 + + Flat - - 帧数取整 + + 285, 45 - - + + 12, 11 - + + 32 + + + 逆波兰表达式 + + + cbPostFix + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + panel1 - - 27 + + 0 - - System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Flat - - cChapterName + + 501, 37 - - appendToolStripMenuItem + + 52, 23 - - 12, 36 + + 24 - - 逆波兰表达式 + + LOG - + + btnLog + + + System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + panel1 - - 平移章节号 + + 9 - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + True + + + # - - statusStrip1 + + 21 - - Magenta + + True + + + 时间点 - - 2 + + 57 - - 5 + + True + + + 章节名 + + + 57 + + + True + + + 帧数 + + + 45 + + + 12, 83 + + + 556, 351 + + + 25 dataGridView1 - - 1 - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + System.Windows.Forms.DataGridView, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + $this - - 12, 4, 3, 4 + + 7 - + Flat - - 121, 25 + + OGM - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + XML + + + QPF + + + Time Codes + + + TsMuxeR Meta + + + CUE + + + JSON - - + + 62, 4 + + + 108, 25 + + + 26 savingType - - deviationMenuStrip + + System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - + + panel1 - + + 3 + + + True + + + 3, 10 + + + 56, 17 + + + 27 + + + 保存格式 + + + lbFormat + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + panel1 + + + 2 + + Flat - - 125, 48 + + 500, 9 4, 4, 4, 4 - - 3 + + 30, 30 - - System.Windows.Forms.ToolStripDropDownButton, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 28 - - System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + P - - + + btnPreview + + + System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 6 + + + Flat + + + 62, 37 + + + 108, 25 + + + 29 + + + xmlLang + + + System.Windows.Forms.ComboBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + panel1 + + + 5 + + + True + + + 3, 42 + + + 58, 17 + + + 30 + + + XML语言 + + + lbXmlLang + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + panel1 + + + 4 + + + 755, 18 + + + 135, 22 + + + 生成Zones + + + 135, 22 + + + 向前平移 + + + 136, 48 + + + createZonestMenuStrip + + + System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 303, 37 + + + 178, 23 + + + 31 + + + textBoxExpression + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + panel1 + + + 1 + + + 12, 440 + + + 556, 64 + + + 32 + + + panel1 + + + System.Windows.Forms.Panel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 5 + + + 937, 20 + + + 443, 17 + + + + + + MiddleLeft + + + 100, 16 + + + + iVBORw0KGgoAAAANSUhEUgAAABsAAAAbCAYAAACN1PRVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABQSURBVEhLYxgFo2AUjILhAZiAuA+IDxCBQepA6ikCQkB8 + Doj/48EgeZA6qgB8FlLVIhjAZiFNLIIBZAtpahEMgCxYAKVHwSgYBaOALoCBAQCARx+VJacCbgAAAABJ + RU5ErkJggg== + + + + Magenta + + + 20, 20 + + + toolStripDropDownButton1 + + + 0, 511 + + + 580, 22 + + + 33 + + + statusStrip1 + + + statusStrip1 + + + System.Windows.Forms.StatusStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 4 + + + True + + + 61 + + + 96, 96 + + + 580, 533 + + + 微软雅黑, 9pt @@ -699,490 +1009,112 @@ AAD///////8AAP///////wAA////////AAD///////8AAA== - - System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 3, 4, 3, 4 - - panel1 + + Chapter Tool - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + reloadToolStripMenuItem System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 285, 45 + + appendToolStripMenuItem - - 303, 37 + + System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + tsmAccuracy - - + + System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 80, 40 + + combineToolStripMenuItem - - btnPreview + + System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 443, 17 + + folderBrowserDialog1 - - 24000 / 1001 + + System.Windows.Forms.FolderBrowserDialog, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 11 + + openFileDialog1 - - + + System.Windows.Forms.OpenFileDialog, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 32 + + toolTip1 - - RESER / VED + + System.Windows.Forms.ToolTip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 33 + + cOrder - - - - - 14 - - - 556, 64 - - - Flat - - - panel1 - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - True - - - 25 - - - 100, 16 - - - 向前平移 - - - lbPath - - - - - - 24 - - - 80, 40 - - - LOG - - - $this - - - Flat - - - - - - 374, 23 - - - Chapter Tool - - - 17 - - - 500, 9 - - - cbPostFix - - - Form1 - - - 28 - - - 微软雅黑, 9pt - - - True - - - 应用表达式 (t) - - - 6 - - - 6 - - - System.Windows.Forms.OpenFileDialog, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 136, 48 - - - cOrder - - - $this - - - Flat - - - 24000 / 1000 - - - 不使用章节名 - - - cbChapterName - - - panel1 - - - 31 - - - 合并章节 - - - XML语言 - - - 62, 4 - - - 125, 26 - - - System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - comboBox2 - - - - - - panel1 - - - 12, 83 - - - 2 - - - tsProgressBar1 - - - 76, 21 - - - System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 16 + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 cTimeCode - - cbAutoGenName - - - 30000 / 1001 - - - # - - - System.Windows.Forms.ToolTip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 0 - - - 52, 23 - - - 打开文件 - - - panel1 - - - $this - - - - - - MiddleLeft - - - Flat - - - 25000 / 1000 - - - - - - 5 - - - $this - - - System.Windows.Forms.Panel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - True - - - panel1 - - - 58, 17 - - - - - - panel1 - - - openFileDialog1 - - - statusStrip1 - - - 3 - - - 将章节名重新从Chapter 01开始标记 - - - 26 - - - 8 - - - 50000 / 1000 - - - toolStripDropDownButton1 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Flat - - - lbShift - - - 538, 9 - - - 556, 351 - - - 9 - - - 30 - - - 580, 533 - - - 11 - - - - - - folderBrowserDialog1 - - - combineToolStripMenuItem - - - 请设置所要保存的位置 - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 100, 21 - - - True - - - 右键菜单可设置误差范围 - - - tsmAccuracy - - - 3, 4, 3, 4 - - - $this - - - 不取消勾选时将持续生效 - - - 57 - - - lbXmlLang - - - toolTip1 - - - 8 - - - 109, 36 - - - 12, 440 + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 52, 23 + + cChapterName - - 3, 42 + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 60000 / 1001 + + cFrams - - 62, 37 + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 creatZonesToolStripMenuItem - - 108, 21 - - - True - - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - System.Windows.Forms.DataGridView, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + ShiftForwardToolStripMenuItem - - + + System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 318, 51 + + tsTips - - 124, 22 + + System.Windows.Forms.ToolStripStatusLabel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Flat + + tsProgressBar1 - - + + System.Windows.Forms.ToolStripProgressBar, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 29 + + tsBtnExpand - - + + System.Windows.Forms.ToolStripDropDownButton, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 108, 25 + + Form1 - - $this + + System.Windows.Forms.Form, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - True - - - 175, 15 - - - 937, 20 - - - 61 - - - True - - - 755, 18 - - - 590, 18 - - - 355, 15 - - - 1058, 20 - - - 10, 15 - - - True - - - True - - - 489, 18 - - - True - \ No newline at end of file diff --git a/Time_Shift/Util/ChapterInfo.cs b/Time_Shift/Util/ChapterInfo.cs index f958d23..9de703f 100644 --- a/Time_Shift/Util/ChapterInfo.cs +++ b/Time_Shift/Util/ChapterInfo.cs @@ -340,5 +340,35 @@ public void SaveCue(string sourceFileName, string fileName, bool autoGenName) } File.WriteAllText(fileName, cueBuilder.ToString()); } + + public void SaveJsonChapter(string fileName, bool autoGenName) + { + StringBuilder jsonBuilder = new StringBuilder(); + jsonBuilder.Append("{"); + jsonBuilder.Append("\"sourceName\":"); + jsonBuilder.Append(SourceType == "MPLS" ? $"\"{SourceName}.m2ts\"," : "\"undefined\","); + jsonBuilder.Append("\"chapter\":"); + jsonBuilder.Append("["); + + TimeSpan baseTime = TimeSpan.Zero; + Chapter prevChapter = null; + var name = ChapterName.GetChapterName("Chapter"); + foreach (Chapter chapter in Chapters) + { + if (chapter.Time == TimeSpan.MinValue && prevChapter != null) + { + baseTime = prevChapter.Time;//update base time + name = ChapterName.GetChapterName("Chapter"); + } + TimeSpan time = chapter.Time - baseTime; + string chapterName = (autoGenName ? name() : chapter.Name); + jsonBuilder.Append($"{{\"name\":\"{chapterName}\",\"time\":{time.TotalSeconds}}},"); + prevChapter = chapter; + } + jsonBuilder.Remove(jsonBuilder.Length - 1, 1); + jsonBuilder.Append("]"); + jsonBuilder.Append("}"); + File.WriteAllText(fileName, jsonBuilder.ToString()); + } } } From 2ee8a3bc025f417dd2ae29fff7db874bcb2b2931 Mon Sep 17 00:00:00 2001 From: tautcony Date: Wed, 25 Jan 2017 12:33:35 +0800 Subject: [PATCH 07/31] Add split row for json output. --- Time_Shift/Forms/Form1.Designer.cs | 11 ++++++++- Time_Shift/Forms/Form1.cs | 8 +++++++ Time_Shift/Forms/Form1.resx | 18 ++++++++++++--- Time_Shift/Util/ChapterInfo.cs | 36 ++++++++++++++++++++++-------- 4 files changed, 60 insertions(+), 13 deletions(-) diff --git a/Time_Shift/Forms/Form1.Designer.cs b/Time_Shift/Forms/Form1.Designer.cs index 8a8cd92..d43ab98 100644 --- a/Time_Shift/Forms/Form1.Designer.cs +++ b/Time_Shift/Forms/Form1.Designer.cs @@ -73,6 +73,7 @@ private void InitializeComponent() this.tsTips = new System.Windows.Forms.ToolStripStatusLabel(); this.tsProgressBar1 = new System.Windows.Forms.ToolStripProgressBar(); this.tsBtnExpand = new System.Windows.Forms.ToolStripDropDownButton(); + this.InsertSplitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loadMenuStrip.SuspendLayout(); this.deviationMenuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); @@ -405,7 +406,8 @@ private void InitializeComponent() // this.createZonestMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.creatZonesToolStripMenuItem, - this.ShiftForwardToolStripMenuItem}); + this.ShiftForwardToolStripMenuItem, + this.InsertSplitToolStripMenuItem}); this.createZonestMenuStrip.Name = "createZonestMenuStrip"; resources.ApplyResources(this.createZonestMenuStrip, "createZonestMenuStrip"); // @@ -475,6 +477,12 @@ private void InitializeComponent() this.tsBtnExpand.ShowDropDownArrow = false; this.tsBtnExpand.Click += new System.EventHandler(this.btnExpand_Click); // + // InsertSplitToolStripMenuItem + // + this.InsertSplitToolStripMenuItem.Name = "InsertSplitToolStripMenuItem"; + resources.ApplyResources(this.InsertSplitToolStripMenuItem, "InsertSplitToolStripMenuItem"); + this.InsertSplitToolStripMenuItem.Click += new System.EventHandler(this.InsertSplitToolStripMenuItem_Click); + // // Form1 // this.AllowDrop = true; @@ -561,6 +569,7 @@ private void InitializeComponent() private System.Windows.Forms.ContextMenuStrip loadMenuStrip; private System.Windows.Forms.ToolStripMenuItem reloadToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem appendToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem InsertSplitToolStripMenuItem; } } diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index a2c1434..c741f3f 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -1565,5 +1565,13 @@ private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEvent } #endregion + private void InsertSplitToolStripMenuItem_Click(object sender, EventArgs e) + { + if (dataGridView1.SelectedRows.Count != 1) return; + DataGridViewRow row = dataGridView1.SelectedRows[0]; + Chapter split = new Chapter("Split line", TimeSpan.MinValue, -1); + _info.Chapters.Insert(row.Index, split); + UpdataGridView(); + } } } diff --git a/Time_Shift/Forms/Form1.resx b/Time_Shift/Forms/Form1.resx index c217b07..ddcede7 100644 --- a/Time_Shift/Forms/Form1.resx +++ b/Time_Shift/Forms/Form1.resx @@ -826,19 +826,25 @@ 755, 18 - 135, 22 + 152, 22 生成Zones - 135, 22 + 152, 22 向前平移 + + 152, 22 + + + 插入分隔条 + - 136, 48 + 153, 92 createZonestMenuStrip @@ -1111,6 +1117,12 @@ System.Windows.Forms.ToolStripDropDownButton, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + InsertSplitToolStripMenuItem + + + System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Form1 diff --git a/Time_Shift/Util/ChapterInfo.cs b/Time_Shift/Util/ChapterInfo.cs index 9de703f..c335354 100644 --- a/Time_Shift/Util/ChapterInfo.cs +++ b/Time_Shift/Util/ChapterInfo.cs @@ -74,6 +74,13 @@ public DataGridViewRow GetRow(int index, bool autoGenName) Tag = Chapters[index], //绑定对象,以便删除行时可以得知对应的 Chapter DefaultCellStyle = {BackColor = (Chapters[index].Number - 1)%2 == 0 ? EVEN_COLOR : ODD_COLOR} }; + if (Chapters[index].Number == -1) + { + row.DefaultCellStyle.BackColor = Color.Black; + for (int i = 0; i < 4; ++i) + row.Cells.Add(new DataGridViewTextBoxCell {Value = ""}); + return row; + } row.Cells.Add(new DataGridViewTextBoxCell {Value = $"{Chapters[index].Number:D2}"}); row.Cells.Add(new DataGridViewTextBoxCell {Value = Time2String(Chapters[index])}); row.Cells.Add(new DataGridViewTextBoxCell {Value = autoGenName ? ChapterName.Get(index + 1) : Chapters[index].Name}); @@ -91,6 +98,12 @@ public void EditRow(DataGridViewRow row, bool autoGenName) { var item = Chapters[row.Index]; row.Tag = item; + if (item.Number == -1) + { + row.DefaultCellStyle.BackColor = Color.Black; + for(int i = 0; i < 4; ++i) row.Cells[i].Value = ""; + return; + } row.DefaultCellStyle.BackColor = (item.Number-1)%2 == 0 ? EVEN_COLOR : ODD_COLOR; row.Cells[0].Value = $"{item.Number:D2}"; row.Cells[1].Value = item.Time2String(this); @@ -198,7 +211,7 @@ public string GetText(bool autoGenName) { var lines = new StringBuilder(); var name = ChapterName.GetChapterName("Chapter"); - foreach (var item in Chapters) + foreach (var item in Chapters.Where(c => c.Time != TimeSpan.MinValue)) { lines.Append($"CHAPTER{item.Number:D2}={Time2String(item)}{Environment.NewLine}"); lines.Append($"CHAPTER{item.Number:D2}NAME="); @@ -210,7 +223,7 @@ public string GetText(bool autoGenName) public void SaveText(string filename, bool autoGenName) => File.WriteAllText(filename, GetText(autoGenName), Encoding.UTF8); - public void SaveQpfile(string filename) => File.WriteAllLines(filename, Chapters.Select(c => c.FramsInfo.ToString().Replace("*", "I").Replace("K", "I")).ToArray()); + public void SaveQpfile(string filename) => File.WriteAllLines(filename, Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(c => c.FramsInfo.ToString().Replace("*", "I").Replace("K", "I")).ToArray()); public static void Chapter2Qpfile(string ipath, string opath, double fps, string tcfile = "") { @@ -279,17 +292,17 @@ public static void Chapter2Qpfile(string ipath, string opath, double fps, string File.WriteAllLines(opath, olines); } - public void SaveCelltimes(string filename) => File.WriteAllLines(filename, Chapters.Select(c => ((long) Math.Round(c.Time.TotalSeconds*FramesPerSecond)).ToString()).ToArray()); + public void SaveCelltimes(string filename) => File.WriteAllLines(filename, Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(c => ((long) Math.Round(c.Time.TotalSeconds*FramesPerSecond)).ToString()).ToArray()); public void SaveTsmuxerMeta(string filename) { string text = $"--custom-{Environment.NewLine}chapters="; - text = Chapters.Aggregate(text, (current, chapter) => current + Time2String(chapter) + ";"); + text = Chapters.Where(c => c.Time != TimeSpan.MinValue).Aggregate(text, (current, chapter) => current + Time2String(chapter) + ";"); text = text.Substring(0, text.Length - 1); File.WriteAllText(filename, text); } - public void SaveTimecodes(string filename) => File.WriteAllLines(filename, Chapters.Select(Time2String).ToArray()); + public void SaveTimecodes(string filename) => File.WriteAllLines(filename, Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(Time2String).ToArray()); public void SaveXml(string filename, string lang, bool autoGenName) { @@ -304,7 +317,7 @@ public void SaveXml(string filename, string lang, bool autoGenName) xmlchap.WriteElementString("EditionFlagDefault", "0"); xmlchap.WriteElementString("EditionUID", Convert.ToString(rndb.Next(1, int.MaxValue))); var name = ChapterName.GetChapterName("Chapter"); - foreach (var item in Chapters) + foreach (var item in Chapters.Where(c => c.Time != TimeSpan.MinValue)) { xmlchap.WriteStartElement("ChapterAtom"); xmlchap.WriteStartElement("ChapterDisplay"); @@ -332,7 +345,7 @@ public void SaveCue(string sourceFileName, string fileName, bool autoGenName) cueBuilder.AppendLine($"FILE \"{sourceFileName}\" WAVE"); int index = 0; var name = ChapterName.GetChapterName("Chapter"); - foreach (var chapter in Chapters) + foreach (var chapter in Chapters.Where(c=>c.Time != TimeSpan.MinValue)) { cueBuilder.AppendLine($" TRACK {++index:D2} AUDIO"); cueBuilder.AppendLine($" TITLE \"{(autoGenName ? name(): chapter.Name)}\""); @@ -348,7 +361,7 @@ public void SaveJsonChapter(string fileName, bool autoGenName) jsonBuilder.Append("\"sourceName\":"); jsonBuilder.Append(SourceType == "MPLS" ? $"\"{SourceName}.m2ts\"," : "\"undefined\","); jsonBuilder.Append("\"chapter\":"); - jsonBuilder.Append("["); + jsonBuilder.Append("[["); TimeSpan baseTime = TimeSpan.Zero; Chapter prevChapter = null; @@ -359,6 +372,11 @@ public void SaveJsonChapter(string fileName, bool autoGenName) { baseTime = prevChapter.Time;//update base time name = ChapterName.GetChapterName("Chapter"); + string initChapterName = autoGenName ? name() : prevChapter.Name; + jsonBuilder.Remove(jsonBuilder.Length - 1, 1); + jsonBuilder.Append("],["); + jsonBuilder.Append($"{{\"name\":\"{initChapterName}\",\"time\":0}},"); + continue; } TimeSpan time = chapter.Time - baseTime; string chapterName = (autoGenName ? name() : chapter.Name); @@ -366,7 +384,7 @@ public void SaveJsonChapter(string fileName, bool autoGenName) prevChapter = chapter; } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); - jsonBuilder.Append("]"); + jsonBuilder.Append("]]"); jsonBuilder.Append("}"); File.WriteAllText(fileName, jsonBuilder.ToString()); } From e5cf844ff8490bd350735680f9c41a682885a045 Mon Sep 17 00:00:00 2001 From: tautcony Date: Wed, 25 Jan 2017 12:56:59 +0800 Subject: [PATCH 08/31] Add .travis.yml --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..591084a --- /dev/null +++ b/.travis.yml @@ -0,0 +1,5 @@ +language: csharp +solution: Time_Shift.sln +install: + - nuget restore Time_Shift.sln + From 0d7e98cbb20803c3c5f3a71b4f26821d561e2a7d Mon Sep 17 00:00:00 2001 From: tautcony Date: Thu, 26 Jan 2017 10:49:11 +0800 Subject: [PATCH 09/31] Improve save type loading. --- Time_Shift/Forms/Form1.Designer.cs | 22 +-- Time_Shift/Forms/Form1.cs | 58 +++++--- Time_Shift/Forms/Form1.resx | 212 ++++++++++++++--------------- 3 files changed, 151 insertions(+), 141 deletions(-) diff --git a/Time_Shift/Forms/Form1.Designer.cs b/Time_Shift/Forms/Form1.Designer.cs index d43ab98..dab5d8f 100644 --- a/Time_Shift/Forms/Form1.Designer.cs +++ b/Time_Shift/Forms/Form1.Designer.cs @@ -67,13 +67,13 @@ private void InitializeComponent() this.createZonestMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.creatZonesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ShiftForwardToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.InsertSplitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.panel1 = new System.Windows.Forms.Panel(); this.textBoxExpression = new System.Windows.Forms.TextBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.tsTips = new System.Windows.Forms.ToolStripStatusLabel(); this.tsProgressBar1 = new System.Windows.Forms.ToolStripProgressBar(); this.tsBtnExpand = new System.Windows.Forms.ToolStripDropDownButton(); - this.InsertSplitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loadMenuStrip.SuspendLayout(); this.deviationMenuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); @@ -358,14 +358,6 @@ private void InitializeComponent() this.savingType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.savingType, "savingType"); this.savingType.FormattingEnabled = true; - this.savingType.Items.AddRange(new object[] { - resources.GetString("savingType.Items"), - resources.GetString("savingType.Items1"), - resources.GetString("savingType.Items2"), - resources.GetString("savingType.Items3"), - resources.GetString("savingType.Items4"), - resources.GetString("savingType.Items5"), - resources.GetString("savingType.Items6")}); this.savingType.Name = "savingType"; this.savingType.TabStop = false; this.savingType.SelectedIndexChanged += new System.EventHandler(this.savingType_SelectedIndexChanged); @@ -423,6 +415,12 @@ private void InitializeComponent() resources.ApplyResources(this.ShiftForwardToolStripMenuItem, "ShiftForwardToolStripMenuItem"); this.ShiftForwardToolStripMenuItem.Click += new System.EventHandler(this.ShiftForwardToolStripMenuItem_Click); // + // InsertSplitToolStripMenuItem + // + this.InsertSplitToolStripMenuItem.Name = "InsertSplitToolStripMenuItem"; + resources.ApplyResources(this.InsertSplitToolStripMenuItem, "InsertSplitToolStripMenuItem"); + this.InsertSplitToolStripMenuItem.Click += new System.EventHandler(this.InsertSplitToolStripMenuItem_Click); + // // panel1 // this.panel1.Controls.Add(this.cbPostFix); @@ -477,12 +475,6 @@ private void InitializeComponent() this.tsBtnExpand.ShowDropDownArrow = false; this.tsBtnExpand.Click += new System.EventHandler(this.btnExpand_Click); // - // InsertSplitToolStripMenuItem - // - this.InsertSplitToolStripMenuItem.Name = "InsertSplitToolStripMenuItem"; - resources.ApplyResources(this.InsertSplitToolStripMenuItem, "InsertSplitToolStripMenuItem"); - this.InsertSplitToolStripMenuItem.Click += new System.EventHandler(this.InsertSplitToolStripMenuItem_Click); - // // Form1 // this.AllowDrop = true; diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index c741f3f..15a9fa0 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -31,6 +31,7 @@ using System.Windows.Forms; using ChapterTool.Properties; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using ChapterTool.Util.ChapterData; using System.Text.RegularExpressions; using static ChapterTool.Util.CTLogger; @@ -80,17 +81,17 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) switch (keyData) { case Keys.Control | Keys.S: - SaveFile(savingType.SelectedIndex); + SaveFile(SelectedSaveType); return true; case Keys.Alt | Keys.S: if (comboBox2.SelectedIndex + 1 < comboBox2.Items.Count) { - SaveFile(savingType.SelectedIndex); + SaveFile(SelectedSaveType); ++comboBox2.SelectedIndex; comboBox2_SelectionChangeCommitted(null, EventArgs.Empty); if (comboBox2.SelectedIndex + 1 == comboBox2.Items.Count) { - SaveFile(savingType.SelectedIndex); + SaveFile(SelectedSaveType); } } return true; @@ -172,7 +173,7 @@ private void Form1_Load(object sender, EventArgs e) Log(string.Format(Resources.Log_Load_Position_Successful, saved)); } } - + LoadSaveType(); LanguageSelectionContainer.LoadLang(xmlLang); InsertAccuracyItems(); SetDefault(); @@ -719,10 +720,11 @@ private void appendToolStripMenuItem_Click(object sender, EventArgs e) #endregion #region Save File - private void btnSave_Click(object sender, EventArgs e) => SaveFile(savingType.SelectedIndex); + private void btnSave_Click(object sender, EventArgs e) => SaveFile((SaveTypeEnum)savingType.SelectedIndex); private string _customSavingPath = string.Empty; + private SaveTypeEnum SelectedSaveType => (SaveTypeEnum) savingType.SelectedIndex; private void btnSave_MouseUp(object sender, MouseEventArgs e) { @@ -771,7 +773,7 @@ private void SaveInfoLog(string savePath) } } - private string GeneRateSavePath(int saveType) + private string GeneRateSavePath(SaveTypeEnum saveType) { var rootPath = string.IsNullOrWhiteSpace(_customSavingPath) ? Path.GetDirectoryName(FilePath) : _customSavingPath; var fileName = Path.GetFileNameWithoutExtension(FilePath); @@ -782,17 +784,39 @@ private string GeneRateSavePath(int saveType) if (ext == ".mpls" || ext == ".ifo") savePath += $"__{_info.SourceName}"; - string[] saveingTypeSuffix = { ".txt", ".xml", ".qpf", ".TimeCodes.txt", ".TsMuxeR_Meta.txt", ".cue" , ".json" }; int index = 1; - while (File.Exists($"{savePath}_{index}{saveingTypeSuffix[saveType]}")) ++index; - savePath += $"_{index}{saveingTypeSuffix[saveType]}"; + while (File.Exists($"{savePath}_{index}{SaveTypeSuffix[saveType]}")) ++index; + savePath += $"_{index}{SaveTypeSuffix[saveType]}"; return savePath; } + [SuppressMessage("ReSharper", "InconsistentNaming")] + private enum SaveTypeEnum + { + TXT, XML, QPF, TimeCodes, TsmuxerMeta, CUE, JSON + } + + private static readonly Dictionary SaveTypeSuffix = new Dictionary + { + [SaveTypeEnum.TXT] = ".txt", + [SaveTypeEnum.XML] = ".xml", + [SaveTypeEnum.QPF] = ".qpf", + [SaveTypeEnum.TimeCodes] = ".TimeCodes.txt", + [SaveTypeEnum.TsmuxerMeta] = ".TsMuxeR_Meta.txt", + [SaveTypeEnum.CUE] = ".cue", + [SaveTypeEnum.JSON] = ".json" + }; + + private void LoadSaveType() + { + foreach (var type in Enum.GetNames(typeof(SaveTypeEnum))) + savingType.Items.Add(type); + } + private static readonly Regex RLang = new Regex(@"\((?.+)\)", RegexOptions.Compiled); - private void SaveFile(int saveType) + private void SaveFile(SaveTypeEnum saveType) { if (!IsPathValid) return;//防止保存先于载入 UpdataGridView(); @@ -804,26 +828,26 @@ private void SaveFile(int saveType) { switch (saveType) { - case 0: //TXT + case SaveTypeEnum.TXT: _info.SaveText(savePath, AutoGenName); break; - case 1: //XML + case SaveTypeEnum.XML: string key = RLang.Match(xmlLang.Items[xmlLang.SelectedIndex].ToString()).Groups["lang"].ToString(); _info.SaveXml(savePath, string.IsNullOrWhiteSpace(key) ? "" : LanguageSelectionContainer.Languages[key], AutoGenName); break; - case 2: //QPF + case SaveTypeEnum.QPF: _info.SaveQpfile(savePath); break; - case 3: //Time Codes + case SaveTypeEnum.TimeCodes: _info.SaveTimecodes(savePath); break; - case 4: //Tsmuxer + case SaveTypeEnum.TsmuxerMeta: _info.SaveTsmuxerMeta(savePath); break; - case 5: //CUE + case SaveTypeEnum.CUE: _info.SaveCue(Path.GetFileName(FilePath), savePath, AutoGenName); break; - case 6: //JSON + case SaveTypeEnum.JSON: _info.SaveJsonChapter(savePath, AutoGenName); break; } diff --git a/Time_Shift/Forms/Form1.resx b/Time_Shift/Forms/Form1.resx index ddcede7..91fee50 100644 --- a/Time_Shift/Forms/Form1.resx +++ b/Time_Shift/Forms/Form1.resx @@ -121,18 +121,6 @@ 1058, 20 - - 124, 22 - - - 重新载入 - - - 124, 22 - - - 追加合并 - 125, 48 @@ -174,6 +162,18 @@ 14 + + 124, 22 + + + 重新载入 + + + 124, 22 + + + 追加合并 + Flat @@ -255,6 +255,9 @@ 11 + + 489, 18 + Flat @@ -273,9 +276,6 @@ 不使用章节名 - - 489, 18 - 将章节名重新从Chapter 01开始标记 @@ -342,12 +342,6 @@ 10, 15 - - 124, 22 - - - 误差范围 - 125, 26 @@ -372,6 +366,9 @@ 帧数取整 + + 489, 18 + 右键菜单可设置误差范围 @@ -387,6 +384,12 @@ 9 + + 124, 22 + + + 误差范围 + 501, 7 @@ -504,12 +507,6 @@ 590, 18 - - 124, 22 - - - 合并章节 - 125, 26 @@ -543,6 +540,12 @@ 8 + + 124, 22 + + + 合并章节 + 175, 15 @@ -615,39 +618,15 @@ True - - # - - - 21 - True - - 时间点 - - - 57 - True - - 章节名 - - - 57 - True - - 帧数 - - - 45 - 12, 83 @@ -669,29 +648,44 @@ 7 - - Flat + + True + + + # - - OGM + + 21 + + + True + + + 时间点 - - XML + + 57 - - QPF + + True + + + 章节名 - - Time Codes + + 57 - - TsMuxeR Meta + + True + + + 帧数 - - CUE + + 45 - - JSON + + Flat 62, 4 @@ -825,33 +819,33 @@ 755, 18 + + 137, 70 + + + createZonestMenuStrip + + + System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + - 152, 22 + 136, 22 生成Zones - 152, 22 + 136, 22 向前平移 - 152, 22 + 136, 22 插入分隔条 - - 153, 92 - - - createZonestMenuStrip - - - System.Windows.Forms.ContextMenuStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - 303, 37 @@ -897,6 +891,30 @@ 937, 20 + + 0, 511 + + + 580, 22 + + + 33 + + + statusStrip1 + + + statusStrip1 + + + System.Windows.Forms.StatusStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 4 + 443, 17 @@ -926,30 +944,6 @@ toolStripDropDownButton1 - - 0, 511 - - - 580, 22 - - - 33 - - - statusStrip1 - - - statusStrip1 - - - System.Windows.Forms.StatusStrip, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - $this - - - 4 - True @@ -1099,6 +1093,12 @@ System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + InsertSplitToolStripMenuItem + + + System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + tsTips @@ -1117,12 +1117,6 @@ System.Windows.Forms.ToolStripDropDownButton, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - InsertSplitToolStripMenuItem - - - System.Windows.Forms.ToolStripMenuItem, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Form1 From b8cadd1e7c171f869b0c51cad7a86faa6c3c38ab Mon Sep 17 00:00:00 2001 From: tautcony Date: Thu, 26 Jan 2017 10:49:29 +0800 Subject: [PATCH 10/31] Improve split row display. --- Time_Shift/Forms/Form1.cs | 8 +++++++- Time_Shift/Util/ChapterInfo.cs | 9 +-------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index 15a9fa0..898a8c4 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -239,6 +239,8 @@ private void SetDefault() _xplGroup = null; _bdmvGroup = null; + splitRowInsrted = false; + dataGridView1.Rows.Clear(); } #endregion @@ -944,6 +946,9 @@ private void GetChapterInfoFromXml(XmlDocument doc) #endregion #region Grid View + + private bool splitRowInsrted = false; + private void UpdataGridView(int fpsIndex = 0, bool updateFrameInfo = true) { if (!IsPathValid || _info == null) return; @@ -967,7 +972,7 @@ private void UpdataGridView(int fpsIndex = 0, bool updateFrameInfo = true) } SKIP: - bool clearRows = _info.Chapters.Count != dataGridView1.Rows.Count; + bool clearRows = _info.Chapters.Count != dataGridView1.Rows.Count || splitRowInsrted; if (clearRows) dataGridView1.Rows.Clear(); for (var i = 0; i < _info.Chapters.Count; i++) { @@ -1595,6 +1600,7 @@ private void InsertSplitToolStripMenuItem_Click(object sender, EventArgs e) DataGridViewRow row = dataGridView1.SelectedRows[0]; Chapter split = new Chapter("Split line", TimeSpan.MinValue, -1); _info.Chapters.Insert(row.Index, split); + splitRowInsrted = true; UpdataGridView(); } } diff --git a/Time_Shift/Util/ChapterInfo.cs b/Time_Shift/Util/ChapterInfo.cs index c335354..d0b063e 100644 --- a/Time_Shift/Util/ChapterInfo.cs +++ b/Time_Shift/Util/ChapterInfo.cs @@ -44,8 +44,6 @@ public class ChapterInfo public double FramesPerSecond { get; set; } public TimeSpan Duration { get; set; } public List Chapters { get; set; } = new List(); - //public TimeSpan Offset { get; set; } = TimeSpan.Zero; - //public bool Mul1K1 { get; set; } public Expression Expr { get; set; } = Expression.Empty; @@ -77,6 +75,7 @@ public DataGridViewRow GetRow(int index, bool autoGenName) if (Chapters[index].Number == -1) { row.DefaultCellStyle.BackColor = Color.Black; + row.Height = 3; for (int i = 0; i < 4; ++i) row.Cells.Add(new DataGridViewTextBoxCell {Value = ""}); return row; @@ -98,12 +97,6 @@ public void EditRow(DataGridViewRow row, bool autoGenName) { var item = Chapters[row.Index]; row.Tag = item; - if (item.Number == -1) - { - row.DefaultCellStyle.BackColor = Color.Black; - for(int i = 0; i < 4; ++i) row.Cells[i].Value = ""; - return; - } row.DefaultCellStyle.BackColor = (item.Number-1)%2 == 0 ? EVEN_COLOR : ODD_COLOR; row.Cells[0].Value = $"{item.Number:D2}"; row.Cells[1].Value = item.Time2String(this); From 3a3303f48824f87ab21718d4e69fb864db557f41 Mon Sep 17 00:00:00 2001 From: tautcony Date: Sat, 4 Feb 2017 18:55:48 +0800 Subject: [PATCH 11/31] Make log work correctly after throw exceptions. --- Time_Shift/Forms/Form1.cs | 123 +++++++++++++++--------- Time_Shift/Util/ChapterData/CueData.cs | 18 ++-- Time_Shift/Util/ChapterData/FlacData.cs | 2 +- 3 files changed, 90 insertions(+), 53 deletions(-) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index 898a8c4..6aa8b2a 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -99,6 +99,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) btnLoad_Click(null, EventArgs.Empty); return true; case Keys.Control | Keys.R: + case Keys.F5: UpdataGridView(); return true; case Keys.PageDown: @@ -239,7 +240,7 @@ private void SetDefault() _xplGroup = null; _bdmvGroup = null; - splitRowInsrted = false; + _splitRowInsrted = false; dataGridView1.Rows.Clear(); } @@ -473,28 +474,34 @@ private bool Loadfile() private void LoadMpls(out MplsData rawMpls, bool display = true, string customPath = "") { - MplsData.OnLog += Log; - if (string.IsNullOrEmpty(customPath)) - customPath = FilePath; - rawMpls = new MplsData(customPath); - MplsData.OnLog -= Log; - Log(Resources.Log_MPLS_Load_Success); - Log(string.Format(Resources.Log_MPLS_Clip_Count, rawMpls.ChapterClips.Count)); - if (display) - { - comboBox2.Enabled = comboBox2.Visible = rawMpls.ChapterClips.Count >= 1; - if (!comboBox2.Enabled) return; - comboBox2.Items.Clear(); + try + { + MplsData.OnLog += Log; + if (string.IsNullOrEmpty(customPath)) + customPath = FilePath; + rawMpls = new MplsData(customPath); + Log(Resources.Log_MPLS_Load_Success); + Log(string.Format(Resources.Log_MPLS_Clip_Count, rawMpls.ChapterClips.Count)); + if (display) + { + comboBox2.Enabled = comboBox2.Visible = rawMpls.ChapterClips.Count >= 1; + if (!comboBox2.Enabled) return; + comboBox2.Items.Clear(); + } + foreach (var item in rawMpls.ChapterClips) + { + if (display) comboBox2.Items.Add($"{item.Name}__{item.TimeStamp.Count}"); + Log($" |+{item.Name} Duration[{MplsData.Pts2Time(item.Length).Time2String()}]{{{MplsData.Pts2Time(item.Length).TotalSeconds}}}"); + Log(string.Format(Resources.Log_TimeStamp_Count, item.TimeStamp.Count)); + } + if (!display) return; + comboBox2.SelectedIndex = ClipSeletIndex; + GetChapterInfoFromMpls(ClipSeletIndex); } - foreach(var item in rawMpls.ChapterClips) + finally { - if (display) comboBox2.Items.Add($"{item.Name}__{item.TimeStamp.Count}"); - Log($" |+{item.Name} Duration[{MplsData.Pts2Time(item.Length).Time2String()}]{{{MplsData.Pts2Time(item.Length).TotalSeconds}}}"); - Log(string.Format(Resources.Log_TimeStamp_Count, item.TimeStamp.Count)); + MplsData.OnLog -= Log; } - if (!display) return; - comboBox2.SelectedIndex = ClipSeletIndex; - GetChapterInfoFromMpls(ClipSeletIndex); } private void LoadIfo() @@ -576,23 +583,32 @@ private void LoadMp4() { Knuckleball.ChapterList.OnLog += Log; var mp4 = new Mp4Data(FilePath); - Knuckleball.ChapterList.OnLog -= Log; _info = mp4.Chapter; } catch (Exception exception) { Notification.ShowError(Resources.Message_Unable_To_Read_Mp4_File, exception); } + finally + { + Knuckleball.ChapterList.OnLog -= Log; + } } private void LoadOgm() { - OgmData.OnLog += Log; - _info = OgmData.GetChapterInfo(File.ReadAllBytes(FilePath).GetUTF8String()); - OgmData.OnLog -= Log; - _info.UpdataInfo((int)numericUpDown1.Value); - tsProgressBar1.Value = 33; - tsTips.Text = Resources.Tips_Load_Success; + try + { + OgmData.OnLog += Log; + _info = OgmData.GetChapterInfo(File.ReadAllBytes(FilePath).GetUTF8String()); + _info.UpdataInfo((int)numericUpDown1.Value); + tsProgressBar1.Value = 33; + tsTips.Text = Resources.Tips_Load_Success; + } + finally + { + OgmData.OnLog -= Log; + } } private void LoadXml() @@ -604,11 +620,10 @@ private void LoadXml() private void LoadMatroska() { - MatroskaData.OnLog += Log; - var matroska = new MatroskaData(); - MatroskaData.OnLog -= Log; try { + MatroskaData.OnLog += Log; + var matroska = new MatroskaData(); GetChapterInfoFromXml(matroska.GetXml(FilePath)); } catch (Exception exception) @@ -624,6 +639,10 @@ private void LoadMatroska() } FilePath = string.Empty; } + finally + { + MatroskaData.OnLog -= Log; + } } private void LoadCue() @@ -659,16 +678,22 @@ private async void LoadBDMVAsync() { tsTips.Text = Resources.Tips_Loading; Application.DoEvents(); - BDMVData.OnLog += Log; - _bdmvGroup = await BDMVData.GetChapterAsync(FilePath); - BDMVData.OnLog -= Log; - if (_bdmvGroup == null || _bdmvGroup.Count == 0) + try { - _bdmvGroup = null; - tsTips.Text = Resources.Tips_Load_Fail; - return; + BDMVData.OnLog += Log; + _bdmvGroup = await BDMVData.GetChapterAsync(FilePath); + if (_bdmvGroup == null || _bdmvGroup.Count == 0) + { + _bdmvGroup = null; + tsTips.Text = Resources.Tips_Load_Fail; + return; + } + _info = _bdmvGroup.First(); + } + finally + { + BDMVData.OnLog -= Log; } - _info = _bdmvGroup.First(); } catch (Exception exception) { @@ -909,11 +934,17 @@ private void combineToolStripMenuItem_Click(object sender, EventArgs e) #region GeneRate Chapter Info private void GetChapterInfoFromMpls(int index) { - MplsData.OnLog += Log; - _info = _rawMpls.ToChapterInfo(index, CombineChapter); - MplsData.OnLog -= Log; - tsTips.Text = _info.Chapters.Count < 2 ? Resources.Tips_Chapter_Not_find : Resources.Tips_Load_Success; - _info.UpdataInfo(_chapterNameTemplate); + try + { + MplsData.OnLog += Log; + _info = _rawMpls.ToChapterInfo(index, CombineChapter); + tsTips.Text = _info.Chapters.Count < 2 ? Resources.Tips_Chapter_Not_find : Resources.Tips_Load_Success; + _info.UpdataInfo(_chapterNameTemplate); + } + finally + { + MplsData.OnLog -= Log; + } } private void GetChapterInfoFromIFO(int index) @@ -947,7 +978,7 @@ private void GetChapterInfoFromXml(XmlDocument doc) #region Grid View - private bool splitRowInsrted = false; + private bool _splitRowInsrted; private void UpdataGridView(int fpsIndex = 0, bool updateFrameInfo = true) { @@ -972,7 +1003,7 @@ private void UpdataGridView(int fpsIndex = 0, bool updateFrameInfo = true) } SKIP: - bool clearRows = _info.Chapters.Count != dataGridView1.Rows.Count || splitRowInsrted; + bool clearRows = _info.Chapters.Count != dataGridView1.Rows.Count || _splitRowInsrted; if (clearRows) dataGridView1.Rows.Clear(); for (var i = 0; i < _info.Chapters.Count; i++) { @@ -1600,7 +1631,7 @@ private void InsertSplitToolStripMenuItem_Click(object sender, EventArgs e) DataGridViewRow row = dataGridView1.SelectedRows[0]; Chapter split = new Chapter("Split line", TimeSpan.MinValue, -1); _info.Chapters.Insert(row.Index, split); - splitRowInsrted = true; + _splitRowInsrted = true; UpdataGridView(); } } diff --git a/Time_Shift/Util/ChapterData/CueData.cs b/Time_Shift/Util/ChapterData/CueData.cs index b77f6ce..d1aa38d 100644 --- a/Time_Shift/Util/ChapterData/CueData.cs +++ b/Time_Shift/Util/ChapterData/CueData.cs @@ -280,12 +280,18 @@ private static string GetCueFromTak(string takPath) private static string GetCueFromFlac(string flacPath, Action log = null) { - FlacData.OnLog += log; - var info = FlacData.GetMetadataFromFlac(flacPath); - FlacData.OnLog -= log; - if (info.VorbisComment.ContainsKey("cuesheet")) - return info.VorbisComment["cuesheet"]; - return string.Empty; + try + { + FlacData.OnLog += log; + var info = FlacData.GetMetadataFromFlac(flacPath); + if (info.VorbisComment.ContainsKey("cuesheet")) + return info.VorbisComment["cuesheet"]; + return string.Empty; + } + finally + { + FlacData.OnLog -= log; + } } public int Count { get; } = 1; diff --git a/Time_Shift/Util/ChapterData/FlacData.cs b/Time_Shift/Util/ChapterData/FlacData.cs index cf7a134..4d09bad 100644 --- a/Time_Shift/Util/ChapterData/FlacData.cs +++ b/Time_Shift/Util/ChapterData/FlacData.cs @@ -63,7 +63,7 @@ private enum BlockType public static FlacInfo GetMetadataFromFlac(string flacPath) { - using (var fs = File.Open(flacPath, FileMode.Open, FileAccess.Read)) + using (var fs = File.Open(flacPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (fs.Length < SizeThreshold) return new FlacInfo(); FlacInfo info = new FlacInfo {TrueLength = fs.Length}; From 8c2e5d6a4a5dd8bfbe040d4a51351b5a4956f040 Mon Sep 17 00:00:00 2001 From: tautcony Date: Tue, 28 Feb 2017 14:13:41 +0800 Subject: [PATCH 12/31] Improve preview form display. --- Time_Shift/Forms/FormPreview.Designer.cs | 1 - Time_Shift/Forms/FormPreview.cs | 43 +++++++++++++----------- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/Time_Shift/Forms/FormPreview.Designer.cs b/Time_Shift/Forms/FormPreview.Designer.cs index 370ea44..5c239c3 100644 --- a/Time_Shift/Forms/FormPreview.Designer.cs +++ b/Time_Shift/Forms/FormPreview.Designer.cs @@ -58,7 +58,6 @@ private void InitializeComponent() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "FormPreview"; this.Text = "Preview"; - this.Activated += new System.EventHandler(this.FormPreview_Activated); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormPreview_FormClosing); this.Load += new System.EventHandler(this.FormPreview_Load); this.ResumeLayout(false); diff --git a/Time_Shift/Forms/FormPreview.cs b/Time_Shift/Forms/FormPreview.cs index 8f387a4..dc5e189 100644 --- a/Time_Shift/Forms/FormPreview.cs +++ b/Time_Shift/Forms/FormPreview.cs @@ -20,26 +20,37 @@ using System; using System.Linq; using System.Drawing; -using System.Reflection; using System.Windows.Forms; namespace ChapterTool.Forms { public partial class FormPreview : Form { - private Point _mainPos; - private readonly Form1 _mainWindow; + private readonly Form1 _mainForm; - public FormPreview(string text, Form1 mainWindow) + protected override void WndProc(ref Message m) { - InitializeComponent(); - cTextBox1.Text = text; - _mainWindow = mainWindow; - _mainPos = mainWindow.Location; - ScrollBarSet(); - Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); + base.WndProc(ref m); + if (m.Msg == 0x84 && (int)m.Result == 1) + m.Result = (IntPtr)(-1); + } + + protected override CreateParams CreateParams + { + get + { + var p = base.CreateParams; + if (TopMost) p.ExStyle |= 8; + return p; + } + } - _mainWindow.Move += Form1_Move; + public FormPreview(Form1 mainForm) + { + InitializeComponent(); + _mainForm = mainForm; + _mainForm.Move += Form1_Move; + Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } private void ScrollBarSet() @@ -64,8 +75,7 @@ public void UpdateText(string text) private void FormPreview_Load(object sender, EventArgs e) { - _mainPos.X = _mainPos.X - Size.Width; - Location = _mainPos; + Form1_Move(this, null); } private void FormPreview_FormClosing(object sender, FormClosingEventArgs e) @@ -74,14 +84,9 @@ private void FormPreview_FormClosing(object sender, FormClosingEventArgs e) Hide(); } - private void FormPreview_Activated(object sender, EventArgs e) - { - //_mainWindow.Activate(); - } - private void Form1_Move(object sender, EventArgs e) { - this.Location = new Point(_mainWindow.Location.X - Width, _mainWindow.Location.Y); + Location = new Point(_mainForm.Location.X - Width, _mainForm.Location.Y); } } } From ac4839ebf35a1a9964d1fbc4a6082e30d8e191e3 Mon Sep 17 00:00:00 2001 From: tautcony Date: Tue, 28 Feb 2017 14:15:24 +0800 Subject: [PATCH 13/31] Improve file saving. --- Time_Shift/Forms/Form1.cs | 45 +++++++++++++++++----------------- Time_Shift/Util/ChapterInfo.cs | 20 +++++++-------- Time_Shift/Util/ToolKits.cs | 6 +++++ 3 files changed, 37 insertions(+), 34 deletions(-) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index 6aa8b2a..fc5cc59 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -856,26 +856,26 @@ private void SaveFile(SaveTypeEnum saveType) switch (saveType) { case SaveTypeEnum.TXT: - _info.SaveText(savePath, AutoGenName); + _info.GetText(AutoGenName).SaveAs(savePath); break; case SaveTypeEnum.XML: string key = RLang.Match(xmlLang.Items[xmlLang.SelectedIndex].ToString()).Groups["lang"].ToString(); _info.SaveXml(savePath, string.IsNullOrWhiteSpace(key) ? "" : LanguageSelectionContainer.Languages[key], AutoGenName); break; case SaveTypeEnum.QPF: - _info.SaveQpfile(savePath); + _info.GetTimecodes().SaveAs(savePath); break; case SaveTypeEnum.TimeCodes: - _info.SaveTimecodes(savePath); + _info.GetTimecodes().SaveAs(savePath); break; case SaveTypeEnum.TsmuxerMeta: - _info.SaveTsmuxerMeta(savePath); + _info.GetTimecodes().SaveAs(savePath); break; case SaveTypeEnum.CUE: - _info.SaveCue(Path.GetFileName(FilePath), savePath, AutoGenName); + _info.GetCue(Path.GetFileName(FilePath), AutoGenName).SaveAs(savePath); break; case SaveTypeEnum.JSON: - _info.SaveJsonChapter(savePath, AutoGenName); + _info.GetJson(AutoGenName).SaveAs(savePath); break; } tsProgressBar1.Value = 100; @@ -1477,7 +1477,10 @@ private void btnPreview_Click(object sender, EventArgs e) if (!IsPathValid) return; if (_previewForm == null) { - _previewForm = new FormPreview(_info.GetText(AutoGenName), this); + _previewForm = new FormPreview(this) + { + TopMost = true + }; } _previewForm.UpdateText(_info.GetText(AutoGenName)); _previewForm.Show(); @@ -1512,8 +1515,10 @@ private static void OpenFile(string path) private void InsertMpls() { - var targetPath = Path.GetDirectoryName(FilePath) + "\\..\\STREAM"; - Debug.Assert(targetPath != null); + var basePath = Path.GetDirectoryName(FilePath); + Debug.Assert(basePath != null); + var targetPath = Path.Combine(basePath, "\\..\\STREAM"); + if (!Directory.Exists(targetPath)) return; combineMenuStrip.Items.Add(new ToolStripSeparator()); var fileLine = comboBox2.Text; @@ -1545,8 +1550,11 @@ private void InsertIfo() private void InsertXpl() { - var targetPath = Path.GetDirectoryName(FilePath) + "\\..\\HVDVD_TS"; - Debug.Assert(targetPath != null); + var basePath = Path.GetDirectoryName(FilePath); + Debug.Assert(basePath != null); + var targetPath = Path.Combine(basePath, "\\..\\HVDVD_TS"); + if (!Directory.Exists(targetPath)) return; + combineMenuStrip.Items.Add(new ToolStripSeparator()); var file = Path.GetFileName(_info.SourceName); ToolStripMenuItem fMenuItem = new ToolStripMenuItem(string.Format(Resources.Menu_Open_File, file)); @@ -1560,18 +1568,9 @@ private void InsertXpl() private void contextMenuStrip2_Opening(object sender, System.ComponentModel.CancelEventArgs e) { - if (_rawMpls != null) - { - InsertMpls(); - } - else if (_ifoGroup != null) - { - InsertIfo(); - } - else if (_xplGroup != null) - { - InsertXpl(); - } + if (_rawMpls != null) InsertMpls(); + else if (_ifoGroup != null) InsertIfo(); + else if (_xplGroup != null) InsertXpl(); } private void contextMenuStrip2_Closed(object sender, ToolStripDropDownClosedEventArgs e) diff --git a/Time_Shift/Util/ChapterInfo.cs b/Time_Shift/Util/ChapterInfo.cs index d0b063e..b1f0540 100644 --- a/Time_Shift/Util/ChapterInfo.cs +++ b/Time_Shift/Util/ChapterInfo.cs @@ -214,9 +214,7 @@ public string GetText(bool autoGenName) return lines.ToString(); } - public void SaveText(string filename, bool autoGenName) => File.WriteAllText(filename, GetText(autoGenName), Encoding.UTF8); - - public void SaveQpfile(string filename) => File.WriteAllLines(filename, Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(c => c.FramsInfo.ToString().Replace("*", "I").Replace("K", "I")).ToArray()); + public string[] GetQpfile() => Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(c => c.FramsInfo.ToString().Replace("*", "I").Replace("K", "I")).ToArray(); public static void Chapter2Qpfile(string ipath, string opath, double fps, string tcfile = "") { @@ -285,17 +283,17 @@ public static void Chapter2Qpfile(string ipath, string opath, double fps, string File.WriteAllLines(opath, olines); } - public void SaveCelltimes(string filename) => File.WriteAllLines(filename, Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(c => ((long) Math.Round(c.Time.TotalSeconds*FramesPerSecond)).ToString()).ToArray()); + public string[] GetCelltimes() => Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(c => ((long) Math.Round(c.Time.TotalSeconds*FramesPerSecond)).ToString()).ToArray(); - public void SaveTsmuxerMeta(string filename) + public string GetTsmuxerMeta() { string text = $"--custom-{Environment.NewLine}chapters="; text = Chapters.Where(c => c.Time != TimeSpan.MinValue).Aggregate(text, (current, chapter) => current + Time2String(chapter) + ";"); text = text.Substring(0, text.Length - 1); - File.WriteAllText(filename, text); + return text; } - public void SaveTimecodes(string filename) => File.WriteAllLines(filename, Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(Time2String).ToArray()); + public string[] GetTimecodes() => Chapters.Where(c => c.Time != TimeSpan.MinValue).Select(Time2String).ToArray(); public void SaveXml(string filename, string lang, bool autoGenName) { @@ -329,7 +327,7 @@ public void SaveXml(string filename, string lang, bool autoGenName) xmlchap.Close(); } - public void SaveCue(string sourceFileName, string fileName, bool autoGenName) + public StringBuilder GetCue(string sourceFileName, bool autoGenName) { StringBuilder cueBuilder = new StringBuilder(); cueBuilder.AppendLine("REM Generate By ChapterTool"); @@ -344,10 +342,10 @@ public void SaveCue(string sourceFileName, string fileName, bool autoGenName) cueBuilder.AppendLine($" TITLE \"{(autoGenName ? name(): chapter.Name)}\""); cueBuilder.AppendLine($" INDEX 01 {chapter.Time.ToCueTimeStamp()}"); } - File.WriteAllText(fileName, cueBuilder.ToString()); + return cueBuilder; } - public void SaveJsonChapter(string fileName, bool autoGenName) + public StringBuilder GetJson(bool autoGenName) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{"); @@ -379,7 +377,7 @@ public void SaveJsonChapter(string fileName, bool autoGenName) jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]]"); jsonBuilder.Append("}"); - File.WriteAllText(fileName, jsonBuilder.ToString()); + return jsonBuilder; } } } diff --git a/Time_Shift/Util/ToolKits.cs b/Time_Shift/Util/ToolKits.cs index 617689d..b21e0c0 100644 --- a/Time_Shift/Util/ToolKits.cs +++ b/Time_Shift/Util/ToolKits.cs @@ -154,6 +154,12 @@ public static void LoadColor(this Form1 window) window.TextFrontColor = ColorTranslator.FromHtml(matchesOfJson[5].Groups["hex"].Value); } + public static void SaveAs(this string[] chapter, string path) => File.WriteAllLines(path, chapter, Encoding.UTF8); + + public static void SaveAs(this string chapter, string path) => File.WriteAllText(path, chapter, Encoding.UTF8); + + public static void SaveAs(this object chapter, string path) => File.WriteAllText(path, chapter.ToString(), Encoding.UTF8); + public static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); From 97a0764f7bbd6db9c7c69a837124140e9de8408e Mon Sep 17 00:00:00 2001 From: tautcony Date: Tue, 28 Feb 2017 14:16:00 +0800 Subject: [PATCH 14/31] Improve flac data in integer reading. --- Time_Shift/Util/ChapterData/FlacData.cs | 127 ++++++++++++++++-------- 1 file changed, 85 insertions(+), 42 deletions(-) diff --git a/Time_Shift/Util/ChapterData/FlacData.cs b/Time_Shift/Util/ChapterData/FlacData.cs index 4d09bad..ac47921 100644 --- a/Time_Shift/Util/ChapterData/FlacData.cs +++ b/Time_Shift/Util/ChapterData/FlacData.cs @@ -18,12 +18,12 @@ // // **************************************************************************** using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; +using System.Diagnostics; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace ChapterTool.Util.ChapterData { @@ -34,7 +34,7 @@ public class FlacInfo public double CompressRate => TrueLength / (double)RawLength; public bool HasCover { get; set; } public string Encoder { get; set; } - public Dictionary VorbisComment { get; set; } + public Dictionary VorbisComment { get; } public FlacInfo() { @@ -76,7 +76,7 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) //24-bit Length while (fs.Position < fs.Length) { - uint blockHeader = fs.ReadUInt(); + uint blockHeader = fs.BEInt32(); bool lastMetadataBlock = blockHeader >> 31 == 0x1; BlockType blockType = (BlockType)((blockHeader >> 24) & 0x7f); int length = (int) (blockHeader & 0xffffff); @@ -111,10 +111,10 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) private static void ParseStreamInfo(Stream fs, ref FlacInfo info) { - long minBlockSize = fs.ReadUShort(); - long maxBlockSize = fs.ReadUShort(); - long minFrameSize = fs.ReadInt24(); - long maxFrameSize = fs.ReadInt24(); + long minBlockSize = fs.BEInt16(); + long maxBlockSize = fs.BEInt16(); + long minFrameSize = fs.BEInt24(); + long maxFrameSize = fs.BEInt24(); var buffer = fs.ReadBytes(8); BitReader br = new BitReader(buffer); int sampleRate = (int) br.GetBits(20); @@ -134,15 +134,15 @@ private static void ParseStreamInfo(Stream fs, ref FlacInfo info) private static void ParseVorbisComment(Stream fs, ref FlacInfo info) { //only here in flac use little-endian - int vendorLength = (int) fs.ReadUInt(true); + int vendorLength = (int) fs.LEInt32(); var vendorRawStringData = fs.ReadBytes(vendorLength); var vendor = Encoding.UTF8.GetString(vendorRawStringData, 0, vendorLength); info.Encoder = vendor; OnLog?.Invoke($" | Vendor: {vendor}"); - int userCommentListLength = (int) fs.ReadUInt(true); + int userCommentListLength = (int) fs.LEInt32(); for (int i = 0; i < userCommentListLength; ++i) { - int commentLength = (int) fs.ReadUInt(true); + int commentLength = (int) fs.LEInt32(); var commentRawStringData = fs.ReadBytes(commentLength); var comment = Encoding.UTF8.GetString(commentRawStringData, 0, commentLength); var spilterIndex = comment.IndexOf('='); @@ -154,58 +154,93 @@ private static void ParseVorbisComment(Stream fs, ref FlacInfo info) } } + private static readonly string[] PictureTypeName = + { + "Other", "32x32 pixels 'file icon'", "Other file icon", + "Cover (front)", "Cover (back)", "Leaflet page", + "Media", "Lead artist/lead performer/soloist", "Artist/performer", + "Conductor", "Band/Orchestra", "Composer", + "Lyricist/text writer", "Recording Location", "During recording", + "During performance", "Movie/video screen capture", "A bright coloured fish", + "Illustration", "Band/artist logotype", "Publisher/Studio logotype", + "Reserved" + }; + private static void ParsePicture(Stream fs, ref FlacInfo info) { - int pictureType = (int) fs.ReadUInt(); - int mimeStringLength = (int) fs.ReadUInt(); + int pictureType = (int) fs.BEInt32(); + int mimeStringLength = (int) fs.BEInt32(); string mimeType = Encoding.ASCII.GetString(fs.ReadBytes(mimeStringLength), 0, mimeStringLength); - int descriptionLength = (int) fs.ReadUInt(); + int descriptionLength = (int) fs.BEInt32(); string description = Encoding.UTF8.GetString(fs.ReadBytes(descriptionLength), 0, descriptionLength); - int pictureWidth = (int) fs.ReadUInt(); - int pictureHeight = (int) fs.ReadUInt(); - int colorDepth = (int) fs.ReadUInt(); - int indexedColorCount = (int) fs.ReadUInt(); - int pictureDataLength = (int) fs.ReadUInt(); + int pictureWidth = (int) fs.BEInt32(); + int pictureHeight = (int) fs.BEInt32(); + int colorDepth = (int) fs.BEInt32(); + int indexedColorCount = (int) fs.BEInt32(); + int pictureDataLength = (int) fs.BEInt32(); fs.Seek(pictureDataLength, SeekOrigin.Current); info.TrueLength -= pictureDataLength; info.HasCover = true; - OnLog?.Invoke($" | picture type: {mimeType}"); + if (pictureType > 20) pictureType = 21; + OnLog?.Invoke($" | picture type: {PictureTypeName[pictureType]}"); + OnLog?.Invoke($" | picture format type: {mimeType}"); + if (descriptionLength > 0) + OnLog?.Invoke($" | description: {description}"); OnLog?.Invoke($" | attribute: {pictureWidth}px*{pictureHeight}px@{colorDepth}-bit"); + if (indexedColorCount != 0) + OnLog?.Invoke($" | indexed-color color: {indexedColorCount}"); } + } - private static ushort ReadUShort(this Stream fs) + internal static class Utils + { + public static byte[] ReadBytes(this Stream fs, int length) { - var buffer = fs.ReadBytes(2).Reverse().ToArray(); - return BitConverter.ToUInt16(buffer, 0); + var ret = new byte[length]; + fs.Read(ret, 0, length); + return ret; } - private static int ReadInt24(this Stream fs) + #region int reader + public static uint BEInt32(this Stream fs) { - var buffer = fs.ReadBytes(3); - int ret = 0; - for (int i = 0; i < 3; ++i) - { - ret |= buffer[i] << ((2 - i) * 8); - } - return ret; + var b = fs.ReadBytes(4); + return b[3] + ((uint)b[2] << 8) + ((uint)b[1] << 16) + ((uint)b[0] << 24); } - private static uint ReadUInt(this Stream fs, bool littleEndian = false) + public static uint LEInt32(this Stream fs) { - var buffer = fs.ReadBytes(4); - if (!littleEndian) buffer = buffer.Reverse().ToArray(); - return BitConverter.ToUInt32(buffer, 0); + var b = fs.ReadBytes(4); + return b[0] + ((uint)b[1] << 8) + ((uint)b[2] << 16) + ((uint)b[3] << 24); } - private static byte[] ReadBytes(this Stream fs, int length) + public static int BEInt24(this Stream fs) { - var ret = new byte[length]; - fs.Read(ret, 0, length); - return ret; + var b = fs.ReadBytes(3); + return b[2] + (b[1] << 8) + (b[0] << 16); + } + + public static int LEInt24(this Stream fs) + { + var b = fs.ReadBytes(3); + return b[0] + (b[1] << 8) + (b[2] << 16); + } + + public static int BEInt16(this Stream fs) + { + var b = fs.ReadBytes(2); + return b[1] + (b[0] << 8); + } + + public static int LEInt16(this Stream fs) + { + var b = fs.ReadBytes(2); + return b[0] + (b[1] << 8); } + #endregion } - public class BitReader + internal class BitReader { private readonly byte[] _buffer; private int _bytePosition; @@ -242,12 +277,20 @@ private void Next() ++_bytePosition; } + public void Skip(int length) + { + for (int i = 0; i < length; ++i) + { + Next(); + } + } + public long GetBits(int length) { long ret = 0; for (int i = 0; i < length; ++i) { - ret |= ((long)(_buffer[_bytePosition] >> (7 - _bitPositionInByte) & 1) << (length - 1 - i)); + ret |= ((long) (_buffer[_bytePosition] >> (7 - _bitPositionInByte)) & 1) << (length - 1 - i); Next(); } return ret; From 77953d2c0790af169833b9f39ee04f5b3f919bc6 Mon Sep 17 00:00:00 2001 From: tautcony Date: Tue, 28 Feb 2017 14:33:50 +0800 Subject: [PATCH 15/31] Format code. --- Time_Shift/Util/ChapterData/FlacData.cs | 50 ++++++++++++------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/Time_Shift/Util/ChapterData/FlacData.cs b/Time_Shift/Util/ChapterData/FlacData.cs index ac47921..b70923c 100644 --- a/Time_Shift/Util/ChapterData/FlacData.cs +++ b/Time_Shift/Util/ChapterData/FlacData.cs @@ -67,7 +67,7 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) { if (fs.Length < SizeThreshold) return new FlacInfo(); FlacInfo info = new FlacInfo {TrueLength = fs.Length}; - var header = Encoding.ASCII.GetString(fs.ReadBytes(4), 0, 4); + var header = Encoding.ASCII.GetString(fs.ReadBytes(4), 0, 4); if (header != "fLaC") throw new InvalidDataException($"Except an flac but get an {header}"); //METADATA_BLOCK_HEADER @@ -76,10 +76,10 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) //24-bit Length while (fs.Position < fs.Length) { - uint blockHeader = fs.BEInt32(); + uint blockHeader = fs.BEInt32(); bool lastMetadataBlock = blockHeader >> 31 == 0x1; - BlockType blockType = (BlockType)((blockHeader >> 24) & 0x7f); - int length = (int) (blockHeader & 0xffffff); + BlockType blockType = (BlockType)((blockHeader >> 24) & 0x7f); + int length = (int) (blockHeader & 0xffffff); info.TrueLength -= length; OnLog?.Invoke($"|+{blockType} with Length: {length}"); switch (blockType) @@ -115,14 +115,14 @@ private static void ParseStreamInfo(Stream fs, ref FlacInfo info) long maxBlockSize = fs.BEInt16(); long minFrameSize = fs.BEInt24(); long maxFrameSize = fs.BEInt24(); - var buffer = fs.ReadBytes(8); - BitReader br = new BitReader(buffer); - int sampleRate = (int) br.GetBits(20); - int channelCount = (int) br.GetBits(3)+1; - int bitPerSample = (int) br.GetBits(5)+1; - int totalSample = (int) br.GetBits(36); - var md5 = fs.ReadBytes(16); - info.RawLength = channelCount * bitPerSample / 8 * totalSample; + var buffer = fs.ReadBytes(8); + BitReader br = new BitReader(buffer); + int sampleRate = (int) br.GetBits(20); + int channelCount = (int) br.GetBits(3)+1; + int bitPerSample = (int) br.GetBits(5)+1; + int totalSample = (int) br.GetBits(36); + var md5 = fs.ReadBytes(16); + info.RawLength = channelCount * bitPerSample / 8 * totalSample; OnLog?.Invoke($" | minimum block size: {minBlockSize}, maximum block size: {maxBlockSize}"); OnLog?.Invoke($" | minimum frame size: {minFrameSize}, maximum frame size: {maxFrameSize}"); OnLog?.Invoke($" | Sample rate: {sampleRate}Hz, bits per sample: {bitPerSample}-bit"); @@ -142,14 +142,14 @@ private static void ParseVorbisComment(Stream fs, ref FlacInfo info) int userCommentListLength = (int) fs.LEInt32(); for (int i = 0; i < userCommentListLength; ++i) { - int commentLength = (int) fs.LEInt32(); + int commentLength = (int) fs.LEInt32(); var commentRawStringData = fs.ReadBytes(commentLength); - var comment = Encoding.UTF8.GetString(commentRawStringData, 0, commentLength); - var spilterIndex = comment.IndexOf('='); - var key = comment.Substring(0, spilterIndex); - var value = comment.Substring(spilterIndex + 1, comment.Length - 1 - spilterIndex); - info.VorbisComment[key] = value; - var summary = value.Length > 25 ? value.Substring(0, 25) + "..." : value; + var comment = Encoding.UTF8.GetString(commentRawStringData, 0, commentLength); + var spilterIndex = comment.IndexOf('='); + var key = comment.Substring(0, spilterIndex); + var value = comment.Substring(spilterIndex + 1, comment.Length - 1 - spilterIndex); + info.VorbisComment[key] = value; + var summary = value.Length > 25 ? value.Substring(0, 25) + "..." : value; OnLog?.Invoke($" | [{key}] = '{summary.Replace('\n', ' ')}'"); } } @@ -169,18 +169,18 @@ private static void ParseVorbisComment(Stream fs, ref FlacInfo info) private static void ParsePicture(Stream fs, ref FlacInfo info) { int pictureType = (int) fs.BEInt32(); - int mimeStringLength = (int) fs.BEInt32(); + int mimeStringLength = (int) fs.BEInt32(); string mimeType = Encoding.ASCII.GetString(fs.ReadBytes(mimeStringLength), 0, mimeStringLength); int descriptionLength = (int) fs.BEInt32(); string description = Encoding.UTF8.GetString(fs.ReadBytes(descriptionLength), 0, descriptionLength); - int pictureWidth = (int) fs.BEInt32(); - int pictureHeight = (int) fs.BEInt32(); - int colorDepth = (int) fs.BEInt32(); + int pictureWidth = (int) fs.BEInt32(); + int pictureHeight = (int) fs.BEInt32(); + int colorDepth = (int) fs.BEInt32(); int indexedColorCount = (int) fs.BEInt32(); int pictureDataLength = (int) fs.BEInt32(); fs.Seek(pictureDataLength, SeekOrigin.Current); - info.TrueLength -= pictureDataLength; - info.HasCover = true; + info.TrueLength -= pictureDataLength; + info.HasCover = true; if (pictureType > 20) pictureType = 21; OnLog?.Invoke($" | picture type: {PictureTypeName[pictureType]}"); OnLog?.Invoke($" | picture format type: {mimeType}"); From f12938e762b07084549b176023547d1e70696feb Mon Sep 17 00:00:00 2001 From: tautcony Date: Mon, 6 Mar 2017 13:11:24 +0800 Subject: [PATCH 16/31] Remove useless code. --- Time_Shift/Forms/FormPreview.cs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/Time_Shift/Forms/FormPreview.cs b/Time_Shift/Forms/FormPreview.cs index dc5e189..76d8c45 100644 --- a/Time_Shift/Forms/FormPreview.cs +++ b/Time_Shift/Forms/FormPreview.cs @@ -28,19 +28,14 @@ public partial class FormPreview : Form { private readonly Form1 _mainForm; - protected override void WndProc(ref Message m) - { - base.WndProc(ref m); - if (m.Msg == 0x84 && (int)m.Result == 1) - m.Result = (IntPtr)(-1); - } + internal const int WS_EX_TOPMOST = 8; protected override CreateParams CreateParams { get { var p = base.CreateParams; - if (TopMost) p.ExStyle |= 8; + if (TopMost) p.ExStyle |= WS_EX_TOPMOST; return p; } } From 061264c6729f3aaab8fce70e43a971051686f833 Mon Sep 17 00:00:00 2001 From: tautcony Date: Mon, 6 Mar 2017 13:11:40 +0800 Subject: [PATCH 17/31] Improve BDMV title display. --- Time_Shift/Forms/Form1.cs | 9 ++++++-- Time_Shift/Util/ChapterData/BDMVData.cs | 28 ++++++++++++++++++++----- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index fc5cc59..d60cfbb 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -239,6 +239,7 @@ private void SetDefault() _fullIfoChapter = null; _xplGroup = null; _bdmvGroup = null; + _bdvmTitle = null; _splitRowInsrted = false; @@ -671,6 +672,8 @@ private void LoadWebVTT() tsTips.Text = Resources.Tips_Load_Success; } + private string _bdvmTitle; + private async void LoadBDMVAsync() { SetDefault(); @@ -681,7 +684,9 @@ private async void LoadBDMVAsync() try { BDMVData.OnLog += Log; - _bdmvGroup = await BDMVData.GetChapterAsync(FilePath); + var ret = await BDMVData.GetChapterAsync(FilePath); + _bdvmTitle = ret.Key; + _bdmvGroup = ret.Value; if (_bdmvGroup == null || _bdmvGroup.Count == 0) { _bdmvGroup = null; @@ -803,7 +808,7 @@ private void SaveInfoLog(string savePath) private string GeneRateSavePath(SaveTypeEnum saveType) { var rootPath = string.IsNullOrWhiteSpace(_customSavingPath) ? Path.GetDirectoryName(FilePath) : _customSavingPath; - var fileName = Path.GetFileNameWithoutExtension(FilePath); + var fileName = _bdvmTitle ?? Path.GetFileNameWithoutExtension(FilePath); Debug.Assert(rootPath != null && fileName != null); var savePath = Path.Combine(rootPath, fileName); diff --git a/Time_Shift/Util/ChapterData/BDMVData.cs b/Time_Shift/Util/ChapterData/BDMVData.cs index 03ba0b6..e00ff6e 100644 --- a/Time_Shift/Util/ChapterData/BDMVData.cs +++ b/Time_Shift/Util/ChapterData/BDMVData.cs @@ -13,19 +13,37 @@ public static class BDMVData private static readonly Regex RDiskInfo = new Regex(@"(?\d)\) (?\d+\.mpls), (?:(?:(?\d+:\d+:\d+)[\n\s\b]*(?.+\.m2ts))|(?:(?.+\.m2ts), (?\d+:\d+:\d+)))", RegexOptions.Compiled); - public static async Task> GetChapterAsync(string location) + public static async Task>> GetChapterAsync(string location) { var list = new List(); - string path = Path.Combine(Path.Combine(location, "BDMV"), "PLAYLIST"); + string bdmvTitle = null; + string path = Path.Combine(location, "BDMV", "PLAYLIST"); if (!Directory.Exists(path)) { throw new FileNotFoundException("Blu-Ray disc structure not found."); } + + var metaPath = Path.Combine(location, "BDMV", "META", "DL"); + if (Directory.Exists(metaPath)) + { + var xmlFile = Directory.GetFiles(metaPath).FirstOrDefault(file => file.ToLower().EndsWith(".xml")); + if (xmlFile != null) + { + var xmlText = File.ReadAllText(xmlFile); + var title = Regex.Match(xmlText, @"(?[^<]*)</di:name>"); + if (title.Success) + { + bdmvTitle = title.Groups["title"].Value; + OnLog?.Invoke($"Disc Title: {bdmvTitle}"); + } + } + } + var eac3toPath = RegistryStorage.Load(name: "eac3toPath"); if (string.IsNullOrEmpty(eac3toPath) || !File.Exists(eac3toPath)) { eac3toPath = Notification.InputBox("请输入eac3to的地址", "注意不要带上多余的引号", "C:\\eac3to\\eac3to.exe"); - if (string.IsNullOrEmpty(eac3toPath)) return list; + if (string.IsNullOrEmpty(eac3toPath)) return new KeyValuePair<string, List<ChapterInfo>>(bdmvTitle, list); RegistryStorage.Save(name: "eac3toPath",value: eac3toPath); } var workingPath = Directory.GetParent(location).FullName; @@ -35,7 +53,7 @@ public static async Task<List<ChapterInfo>> GetChapterAsync(string location) { throw new Exception("May be the path is too complex or directory contains nonAscii characters"); } - OnLog?.Invoke("Disc Info:\r\n" + text.Replace('\b', '\uFEFF')); + OnLog?.Invoke("\r\nDisc Info:\r\n" + text.Replace('\b', '\uFEFF')); foreach (Match match in RDiskInfo.Matches(text)) { @@ -79,7 +97,7 @@ public static async Task<List<ChapterInfo>> GetChapterAsync(string location) toBeRemove.ForEach(item => list.Remove(item)); if(File.Exists(chapterPath)) File.Delete(chapterPath); if(File.Exists(logPath)) File.Delete(logPath); - return list; + return new KeyValuePair<string, List<ChapterInfo>>(bdmvTitle, list); } } } From 6822fb752fa56e5f2f56c5d95a65dc14180d1818 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 11 Mar 2017 18:54:46 +0800 Subject: [PATCH 18/31] Improve the chapter name generator. --- Time_Shift/Forms/Form1.cs | 2 +- Time_Shift/SharpDvdInfo/DvdInfoContainer.cs | 2 +- Time_Shift/Util/ChapterData/BDMVData.cs | 2 +- Time_Shift/Util/ChapterInfo.cs | 10 +++++----- Time_Shift/Util/ChapterName.cs | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index d60cfbb..0fae21f 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -1042,7 +1042,7 @@ private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelE _info.UpdataInfo(newInitialTime); if ((_rawMpls != null || _ifoGroup != null) && string.IsNullOrWhiteSpace(_chapterNameTemplate)) { - var name = ChapterName.GetChapterName("Chapter"); + var name = ChapterName.GetChapterName(); _info.Chapters.ForEach(item => item.Name = name()); } Application.DoEvents(); diff --git a/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs b/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs index 1ecc527..940fb53 100644 --- a/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs +++ b/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs @@ -284,7 +284,7 @@ public List<ChapterInfo> GetChapterInfo() foreach (var titleInfo in Titles) { - var chapterName = ChapterName.GetChapterName("Chapter"); + var chapterName = ChapterName.GetChapterName(); var index = 1; var tmp = new ChapterInfo { diff --git a/Time_Shift/Util/ChapterData/BDMVData.cs b/Time_Shift/Util/ChapterData/BDMVData.cs index e00ff6e..d89e0fa 100644 --- a/Time_Shift/Util/ChapterData/BDMVData.cs +++ b/Time_Shift/Util/ChapterData/BDMVData.cs @@ -91,7 +91,7 @@ public static async Task<KeyValuePair<string, List<ChapterInfo>>> GetChapterAsyn } current.Chapters = OgmData.GetChapterInfo(File.ReadAllBytes(chapterPath).GetUTF8String()).Chapters; if (current.Chapters.First().Name != "") continue; - var chapterName = ChapterName.GetChapterName("Chapter"); + var chapterName = ChapterName.GetChapterName(); current.Chapters.ForEach(chapter => chapter.Name = chapterName()); } toBeRemove.ForEach(item => list.Remove(item)); diff --git a/Time_Shift/Util/ChapterInfo.cs b/Time_Shift/Util/ChapterInfo.cs index b1f0540..74c7e90 100644 --- a/Time_Shift/Util/ChapterInfo.cs +++ b/Time_Shift/Util/ChapterInfo.cs @@ -203,7 +203,7 @@ public void UpdataInfo(string chapterNameTemplate) public string GetText(bool autoGenName) { var lines = new StringBuilder(); - var name = ChapterName.GetChapterName("Chapter"); + var name = ChapterName.GetChapterName(); foreach (var item in Chapters.Where(c => c.Time != TimeSpan.MinValue)) { lines.Append($"CHAPTER{item.Number:D2}={Time2String(item)}{Environment.NewLine}"); @@ -307,7 +307,7 @@ public void SaveXml(string filename, string lang, bool autoGenName) xmlchap.WriteElementString("EditionFlagHidden", "0"); xmlchap.WriteElementString("EditionFlagDefault", "0"); xmlchap.WriteElementString("EditionUID", Convert.ToString(rndb.Next(1, int.MaxValue))); - var name = ChapterName.GetChapterName("Chapter"); + var name = ChapterName.GetChapterName(); foreach (var item in Chapters.Where(c => c.Time != TimeSpan.MinValue)) { xmlchap.WriteStartElement("ChapterAtom"); @@ -335,7 +335,7 @@ public StringBuilder GetCue(string sourceFileName, bool autoGenName) cueBuilder.AppendLine($"FILE \"{sourceFileName}\" WAVE"); int index = 0; - var name = ChapterName.GetChapterName("Chapter"); + var name = ChapterName.GetChapterName(); foreach (var chapter in Chapters.Where(c=>c.Time != TimeSpan.MinValue)) { cueBuilder.AppendLine($" TRACK {++index:D2} AUDIO"); @@ -356,13 +356,13 @@ public StringBuilder GetJson(bool autoGenName) TimeSpan baseTime = TimeSpan.Zero; Chapter prevChapter = null; - var name = ChapterName.GetChapterName("Chapter"); + var name = ChapterName.GetChapterName(); foreach (Chapter chapter in Chapters) { if (chapter.Time == TimeSpan.MinValue && prevChapter != null) { baseTime = prevChapter.Time;//update base time - name = ChapterName.GetChapterName("Chapter"); + name = ChapterName.GetChapterName(); string initChapterName = autoGenName ? name() : prevChapter.Name; jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("],["); diff --git a/Time_Shift/Util/ChapterName.cs b/Time_Shift/Util/ChapterName.cs index 593a17a..2805711 100644 --- a/Time_Shift/Util/ChapterName.cs +++ b/Time_Shift/Util/ChapterName.cs @@ -28,11 +28,11 @@ public class ChapterName private const string ChapterFormat = "Chapter"; - public static readonly Func<string, Func<string>> GetChapterName = chapterFormat => + public static Func<string> GetChapterName(string chapterFormat = ChapterFormat) { var index = 1; return () => $"{chapterFormat} {index++:D2}"; - }; + } public ChapterName(int index) { From 08a2fd0b4deed9fc3f6c188172a6f7941ebc9e61 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 11 Mar 2017 18:55:29 +0800 Subject: [PATCH 19/31] Change string to StringBuilder in TaskAsync. --- Time_Shift/Util/ChapterData/BDMVData.cs | 19 ++++++++++--------- Time_Shift/Util/TaskAsync.cs | 11 ++++++----- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/Time_Shift/Util/ChapterData/BDMVData.cs b/Time_Shift/Util/ChapterData/BDMVData.cs index d89e0fa..286650c 100644 --- a/Time_Shift/Util/ChapterData/BDMVData.cs +++ b/Time_Shift/Util/ChapterData/BDMVData.cs @@ -48,12 +48,13 @@ public static async Task<KeyValuePair<string, List<ChapterInfo>>> GetChapterAsyn } var workingPath = Directory.GetParent(location).FullName; location = location.Substring(location.LastIndexOf('\\') + 1); - string text = await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\"", workingPath); + string text = (await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\"", workingPath)).ToString(); if (text.Contains("HD DVD / Blu-Ray disc structure not found.")) { + OnLog?.Invoke(text); throw new Exception("May be the path is too complex or directory contains nonAscii characters"); } - OnLog?.Invoke("\r\nDisc Info:\r\n" + text.Replace('\b', '\uFEFF')); + OnLog?.Invoke("\r\nDisc Info:\r\n" + text); foreach (Match match in RDiskInfo.Matches(text)) { @@ -65,28 +66,28 @@ public static async Task<KeyValuePair<string, List<ChapterInfo>>> GetChapterAsyn if (string.IsNullOrEmpty(file)) file = match.Groups["fn2"].Value; OnLog?.Invoke($"+ {index}) {mpls} -> [{file}] - [{time}]"); - ChapterInfo chapterInfo = new ChapterInfo + list.Add(new ChapterInfo { Duration = TimeSpan.Parse(time), SourceIndex = index, SourceName = file - }; - list.Add(chapterInfo); + }); } - var toBeRemove = new List<ChapterInfo>(); + var toBeRemove = new List<ChapterInfo>(); var chapterPath = Path.Combine(workingPath, "chapters.txt"); - var logPath = Path.Combine(workingPath, "chapters - Log.txt"); + var logPath = Path.Combine(workingPath, "chapters - Log.txt"); foreach (ChapterInfo current in list) { - text = await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\" {current.SourceIndex})", workingPath); + text = (await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\" {current.SourceIndex})", workingPath)).ToString(); if (!text.Contains("Chapters")) { toBeRemove.Add(current); continue; } - text = await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\" {current.SourceIndex}) chapters.txt", workingPath); + text = (await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\" {current.SourceIndex}) chapters.txt", workingPath)).ToString(); if (!text.Contains("Creating file \"chapters.txt\"...") && !text.Contains("Done!")) { + OnLog?.Invoke(text); throw new Exception("Error creating chapters file."); } current.Chapters = OgmData.GetChapterInfo(File.ReadAllBytes(chapterPath).GetUTF8String()).Chapters; diff --git a/Time_Shift/Util/TaskAsync.cs b/Time_Shift/Util/TaskAsync.cs index bf0c765..4dffebf 100644 --- a/Time_Shift/Util/TaskAsync.cs +++ b/Time_Shift/Util/TaskAsync.cs @@ -1,12 +1,13 @@ using System; using System.Diagnostics; +using System.Text; using System.Threading.Tasks; namespace ChapterTool.Util { public static class TaskAsync { - public static async Task<string> RunProcessAsync(string fileName, string args, string workingDirectory = "") + public static async Task<StringBuilder> RunProcessAsync(string fileName, string args, string workingDirectory = "") { using (var process = new Process { @@ -27,12 +28,12 @@ public static async Task<string> RunProcessAsync(string fileName, string args, s } } - private static Task<string> RunProcessAsync(Process process) + private static Task<StringBuilder> RunProcessAsync(Process process) { - var tcs = new TaskCompletionSource<string>(); - var ret = string.Empty; + var tcs = new TaskCompletionSource<StringBuilder>(); + var ret = new StringBuilder(); process.Exited += (sender, args) => tcs.SetResult(ret); - process.OutputDataReceived += (sender, args) => ret += args.Data + "\r\n"; + process.OutputDataReceived += (sender, args) => ret.AppendLine(args.Data?.Trim('\b', ' ')); //process.ErrorDataReceived += (s, ea) => Debug.WriteLine("ERR: " + ea.Data); if (!process.Start()) From 27efa112a68c35a9e175e8c766d928ce9c8ddf02 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 11 Mar 2017 18:55:51 +0800 Subject: [PATCH 20/31] Code format. --- Time_Shift/Forms/Form1.cs | 16 ++++++++-------- Time_Shift/Util/ChapterData/XplData.cs | 10 +++++----- Time_Shift/Util/ToolKits.cs | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index 0fae21f..c060a46 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -165,7 +165,7 @@ private void Form1_Load(object sender, EventArgs e) TargetHeight[1] = Height; Text = $@"[VCB-Studio] ChapterTool v{Assembly.GetExecutingAssembly().GetName().Version}"; InitialLog(); - if (!IsRunningOnMono()) + if (!IsRunningOnMono) { Point saved = String2Point(RegistryStorage.Load(@"Software\ChapterTool", "location")); if (saved != new Point(-32000, -32000)) @@ -183,11 +183,11 @@ private void Form1_Load(object sender, EventArgs e) ExtensionPanelShow = false; savingType.SelectedIndex = 0; btnTrans.Text = Environment.TickCount % 2 == 0 ? "↺" : "↻"; - if (!IsRunningOnMono()) folderBrowserDialog1.SelectedPath = RegistryStorage.Load(); + if (!IsRunningOnMono) folderBrowserDialog1.SelectedPath = RegistryStorage.Load(); Log(Updater.CheckUpdateWeekly("ChapterTool") ? Resources.Log_Update_Checked : Resources.Log_Update_Skiped); if (string.IsNullOrEmpty(FilePath)) return; if (Loadfile()) UpdataGridView(); - if (!IsRunningOnMono()) RegistryStorage.Save(Resources.Message_How_Can_You_Find_Here, @"Software\ChapterTool", string.Empty); + if (!IsRunningOnMono) RegistryStorage.Save(Resources.Message_How_Can_You_Find_Here, @"Software\ChapterTool", string.Empty); } @@ -206,11 +206,11 @@ private static void InitialLog() ? Resources.Log_Wu_Zong : $"{Environment.UserName}{Resources.Log_Hello}"); Log($"{Environment.OSVersion}"); - if (!IsRunningOnMono()) Log(NativeMethods.IsUserAnAdmin() ? Resources.Log_With_Admin : Resources.Log_Without_Admin); + if (!IsRunningOnMono) Log(NativeMethods.IsUserAnAdmin() ? Resources.Log_With_Admin : Resources.Log_Without_Admin); if (Environment.GetLogicalDrives().Length > 10) Log(Resources.Log_Hard_Drive_Plz); - if (!IsRunningOnMono()) using (var registryKey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0")) + if (!IsRunningOnMono) using (var registryKey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0")) { Log((string)registryKey?.GetValue("ProcessorNameString")); } @@ -219,7 +219,7 @@ private static void InitialLog() { Log($"{screen.DeviceName}{Resources.Log_Resolution}{screen.Bounds.Width}*{screen.Bounds.Height}"); } - if (!IsRunningOnMono()) Log(string.Format(Resources.Log_Boot_Count, RegistryStorage.RegistryAddCount(@"Software\ChapterTool\Statistics", @"Count"))); + if (!IsRunningOnMono) Log(string.Format(Resources.Log_Boot_Count, RegistryStorage.RegistryAddCount(@"Software\ChapterTool\Statistics", @"Count"))); } private void SetDefault() @@ -253,7 +253,7 @@ private void SetDefault() private void AddCommand() { - if (IsRunningOnMono()) return; + if (IsRunningOnMono) return; _systemMenu = new SystemMenu(this); _systemMenu.AddCommand(Resources.Update_Check, Updater.CheckUpdate, true); } @@ -264,7 +264,7 @@ protected override void WndProc(ref Message msg) // Let it know all messages so it can handle WM_SYSCOMMAND // (This method is inlined) - if (IsRunningOnMono()) return; + if (IsRunningOnMono) return; _systemMenu.HandleMessage(ref msg); } diff --git a/Time_Shift/Util/ChapterData/XplData.cs b/Time_Shift/Util/ChapterData/XplData.cs index e0c1189..3e02086 100644 --- a/Time_Shift/Util/ChapterData/XplData.cs +++ b/Time_Shift/Util/ChapterData/XplData.cs @@ -20,7 +20,7 @@ public static IEnumerable<ChapterInfo> GetStreams(string location) { ChapterInfo pgc = new ChapterInfo { - SourceName = title.Element(ns + "PrimaryAudioVideoClip")?.Attribute("src").Value, + SourceName = title.Element(ns + "PrimaryAudioVideoClip")?.Attribute("src")?.Value ?? "", SourceType = "HD-DVD", FramesPerSecond = 24D, Chapters = new List<Chapter>() @@ -28,14 +28,14 @@ public static IEnumerable<ChapterInfo> GetStreams(string location) int tickBaseDivisor = (int?)title.Attribute("tickBaseDivisor") ?? 1; //optional pgc.Duration = GetTimeSpan((string)title.Attribute("titleDuration"), timeBase, tickBase, tickBaseDivisor); var titleName = Path.GetFileNameWithoutExtension(location); - if (title.Attribute("id") != null) titleName = title.Attribute("id").Value; //optional - if (title.Attribute("displayName") != null) titleName = title.Attribute("displayName").Value; //optional + if (title.Attribute("id") != null) titleName = title.Attribute("id")?.Value??""; //optional + if (title.Attribute("displayName") != null) titleName = title.Attribute("displayName")?.Value ?? ""; //optional pgc.Title = titleName; foreach (XElement chapter in title.Element(ns + "ChapterList").Elements(ns + "Chapter")) { var chapterName = string.Empty; - if (chapter.Attribute("id") != null) chapterName = chapter.Attribute("id").Value; //optional - if (chapter.Attribute("displayName") != null) chapterName = chapter.Attribute("displayName").Value; //optional + if (chapter.Attribute("id") != null) chapterName = chapter.Attribute("id")?.Value ?? ""; //optional + if (chapter.Attribute("displayName") != null) chapterName = chapter.Attribute("displayName")?.Value ?? ""; //optional pgc.Chapters.Add(new Chapter { Name = chapterName, diff --git a/Time_Shift/Util/ToolKits.cs b/Time_Shift/Util/ToolKits.cs index b21e0c0..8f9a55e 100644 --- a/Time_Shift/Util/ToolKits.cs +++ b/Time_Shift/Util/ToolKits.cs @@ -196,7 +196,7 @@ private static bool RunElevated(string fileName) private static readonly Lazy<bool> IsRunningOnMonoValue = new Lazy<bool>(() => Type.GetType("Mono.Runtime") != null); - public static bool IsRunningOnMono() => IsRunningOnMonoValue.Value; + public static bool IsRunningOnMono => IsRunningOnMonoValue.Value; } public static class RegistryStorage From 41a80582eb4336a52ff8469b2ef9d9f951eeb5e3 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 11 Mar 2017 20:48:40 +0800 Subject: [PATCH 21/31] Enable dpiAware. --- Time_Shift/App.config | 9 +++++ Time_Shift/Time_Shift.csproj | 5 +++ Time_Shift/app.manifest | 75 ++++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 Time_Shift/App.config create mode 100644 Time_Shift/app.manifest diff --git a/Time_Shift/App.config b/Time_Shift/App.config new file mode 100644 index 0000000..7997d60 --- /dev/null +++ b/Time_Shift/App.config @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="utf-8"?> +<configuration> + <startup> + <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/> + </startup> + <appSettings> + <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" /> + </appSettings> +</configuration> diff --git a/Time_Shift/Time_Shift.csproj b/Time_Shift/Time_Shift.csproj index b9aa5d2..78d4c43 100644 --- a/Time_Shift/Time_Shift.csproj +++ b/Time_Shift/Time_Shift.csproj @@ -88,6 +88,9 @@ <PlatformTarget>x64</PlatformTarget> <OutputPath>bin\x64\Release\</OutputPath> </PropertyGroup> + <PropertyGroup> + <ApplicationManifest>app.manifest</ApplicationManifest> + </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.VisualStudio.DebuggerVisualizers, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> @@ -229,6 +232,8 @@ </ItemGroup> <ItemGroup> <Content Include="Images\about.ico" /> + <None Include="App.config" /> + <None Include="app.manifest" /> <None Include="Images\arrow_drop_down.png" /> <None Include="Images\arrow_drop_up.png" /> <Content Include="Images\Ct.ico" /> diff --git a/Time_Shift/app.manifest b/Time_Shift/app.manifest new file mode 100644 index 0000000..e830149 --- /dev/null +++ b/Time_Shift/app.manifest @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="utf-8"?> +<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> + <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> + <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> + <security> + <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> + <!-- UAC 清单选项 + 如果想要更改 Windows 用户帐户控制级别,请使用 + 以下节点之一替换 requestedExecutionLevel 节点。n + <requestedExecutionLevel level="asInvoker" uiAccess="false" /> + <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> + <requestedExecutionLevel level="highestAvailable" uiAccess="false" /> + + 指定 requestedExecutionLevel 元素将禁用文件和注册表虚拟化。 + 如果你的应用程序需要此虚拟化来实现向后兼容性,则删除此 + 元素。 + --> + <requestedExecutionLevel level="asInvoker" uiAccess="false" /> + </requestedPrivileges> + </security> + </trustInfo> + + <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> + <application> + <!-- 设计此应用程序与其一起工作且已针对此应用程序进行测试的 + Windows 版本的列表。取消评论适当的元素,Windows 将 + 自动选择最兼容的环境。 --> + + <!-- Windows Vista --> + <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />--> + + <!-- Windows 7 --> + <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />--> + + <!-- Windows 8 --> + <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />--> + + <!-- Windows 8.1 --> + <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />--> + + <!-- Windows 10 --> + <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />--> + + </application> + </compatibility> + + <!-- 指示该应用程序可以感知 DPI 且 Windows 在 DPI 较高时将不会对其进行 + 自动缩放。Windows Presentation Foundation (WPF)应用程序自动感知 DPI,无需 + 选择加入。选择加入此设置的 Windows 窗体应用程序(目标设定为 .NET Framework 4.6 )还应 + 在其 app.config 中将 "EnableWindowsFormsHighDpiAutoResizing" 设置设置为 "true"。--> + + <application xmlns="urn:schemas-microsoft-com:asm.v3"> + <windowsSettings> + <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware> + </windowsSettings> + </application> + + + <!-- 启用 Windows 公共控件和对话框的主题(Windows XP 和更高版本) --> + <!-- + <dependency> + <dependentAssembly> + <assemblyIdentity + type="win32" + name="Microsoft.Windows.Common-Controls" + version="6.0.0.0" + processorArchitecture="*" + publicKeyToken="6595b64144ccf1df" + language="*" + /> + </dependentAssembly> + </dependency> + --> + +</assembly> From eaa07b38e200021196d195c2d471a3f4313613b9 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 11 Mar 2017 20:49:01 +0800 Subject: [PATCH 22/31] Improve runtime check. --- Time_Shift/Program.cs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Time_Shift/Program.cs b/Time_Shift/Program.cs index a6dfc01..a1482af 100644 --- a/Time_Shift/Program.cs +++ b/Time_Shift/Program.cs @@ -15,8 +15,13 @@ static void Main(string[] args) Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); + if (!IsSupportedRuntimeVersion()) + { + var ret = Util.Notification.ShowInfo(Resources.Message_Need_Newer_dotNet); + System.Diagnostics.Process.Start("http://dotnetsocial.cloudapp.net/GetDotnet?tfm=.NETFramework,Version=v4.6"); + if (ret == DialogResult.Yes) Util.RegistryStorage.Save("False", name: "DoVersionCheck"); + } - CheckDotNetVersion(); if (args.Length == 0) { Application.Run(new Forms.Form1()); @@ -28,21 +33,20 @@ static void Main(string[] args) } } - private static void CheckDotNetVersion() + private static bool IsSupportedRuntimeVersion() { - var doCheck = Util.RegistryStorage.Load(name: "DoVersionCheck"); - if (doCheck == "False") return; - int dotNetVersion; - var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"); - if (key == null) dotNetVersion = 0; - else dotNetVersion = (int)(key.GetValue("Release")); //https://msdn.microsoft.com/en-us/library/hh925568 - if (dotNetVersion >= 394802) return; - var ret = Util.Notification.ShowInfo(Resources.Message_Need_Newer_dotNet); - if (ret == DialogResult.Yes) + const int minSupportedRelease = 394802; + if (Util.RegistryStorage.Load(name: "DoVersionCheck") == "False") return true; + using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full")) { - Util.RegistryStorage.Save("False", name: "DoVersionCheck"); + if (key?.GetValue("Release") != null) + { + var releaseKey = (int)key.GetValue("Release"); + if (releaseKey >= minSupportedRelease) return true; + } } + return false; } } } From 4e44e68940e3892faa0cf46a2422315b1f10cd2c Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 11 Mar 2017 20:49:11 +0800 Subject: [PATCH 23/31] Rename logger. --- Time_Shift/Forms/Form1.cs | 2 +- Time_Shift/Forms/FormAbout.cs | 4 ++-- Time_Shift/Forms/FormLog.cs | 4 ++-- Time_Shift/Time_Shift.csproj | 2 +- Time_Shift/Util/{CTLogger.cs => Logger.cs} | 6 ++---- 5 files changed, 8 insertions(+), 10 deletions(-) rename Time_Shift/Util/{CTLogger.cs => Logger.cs} (79%) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index c060a46..989997f 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -34,7 +34,7 @@ using System.Diagnostics.CodeAnalysis; using ChapterTool.Util.ChapterData; using System.Text.RegularExpressions; -using static ChapterTool.Util.CTLogger; +using static ChapterTool.Util.Logger; using static ChapterTool.Util.ToolKits; diff --git a/Time_Shift/Forms/FormAbout.cs b/Time_Shift/Forms/FormAbout.cs index 4102c43..b675804 100644 --- a/Time_Shift/Forms/FormAbout.cs +++ b/Time_Shift/Forms/FormAbout.cs @@ -75,7 +75,7 @@ private void CloseForm() Opacity -= 0.02; Thread.Sleep(20); } - CTLogger.Log("关于窗口被关闭"); + Logger.Log("关于窗口被关闭"); Close(); } @@ -105,7 +105,7 @@ private void button5_Click(object sender, EventArgs e) { //Thread.Sleep(20000); WindowState = FormWindowState.Minimized; - CTLogger.Log("关于窗口被最小化"); + Logger.Log("关于窗口被最小化"); } private void Form2_FormClosing(object sender, FormClosingEventArgs e) diff --git a/Time_Shift/Forms/FormLog.cs b/Time_Shift/Forms/FormLog.cs index 3b42b00..f9dce90 100644 --- a/Time_Shift/Forms/FormLog.cs +++ b/Time_Shift/Forms/FormLog.cs @@ -24,7 +24,7 @@ private void InitForm() private void frmLog_Activated(object sender, EventArgs e) { - txtLog.Text = CTLogger.LogText; + txtLog.Text = Logger.LogText; } private void txtLog_TextChanged(object sender, EventArgs e) @@ -62,7 +62,7 @@ private void btnRefresh_Click(object sender, EventArgs e) { try { - txtLog.Text = CTLogger.LogText; + txtLog.Text = Logger.LogText; } catch (Exception exception) { diff --git a/Time_Shift/Time_Shift.csproj b/Time_Shift/Time_Shift.csproj index 78d4c43..1776023 100644 --- a/Time_Shift/Time_Shift.csproj +++ b/Time_Shift/Time_Shift.csproj @@ -146,7 +146,7 @@ <Compile Include="Controls\cTextBox.cs"> <SubType>Component</SubType> </Compile> - <Compile Include="Util\CTLogger.cs" /> + <Compile Include="Util\Logger.cs" /> <Compile Include="Forms\Form1.cs"> <SubType>Form</SubType> </Compile> diff --git a/Time_Shift/Util/CTLogger.cs b/Time_Shift/Util/Logger.cs similarity index 79% rename from Time_Shift/Util/CTLogger.cs rename to Time_Shift/Util/Logger.cs index 5066e7c..0185159 100644 --- a/Time_Shift/Util/CTLogger.cs +++ b/Time_Shift/Util/Logger.cs @@ -7,15 +7,13 @@ namespace ChapterTool.Util { - public delegate void LogLineAddedEventHandler(string lineAdded, DateTime actionDate); - // ReSharper disable once InconsistentNaming - public static class CTLogger + public static class Logger { private static readonly StringBuilder LogContext = new StringBuilder(); public static string LogText => LogContext.ToString(); - public static event LogLineAddedEventHandler LogLineAdded; + public static event Action<string, DateTime> LogLineAdded; public static void Log(string message) { From 660c050b32b67d88b3b70074f4649efa9853c94c Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 1 Apr 2017 13:05:03 +0800 Subject: [PATCH 24/31] Remove extra space. --- Time_Shift/App.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Time_Shift/App.config b/Time_Shift/App.config index 7997d60..75881a4 100644 --- a/Time_Shift/App.config +++ b/Time_Shift/App.config @@ -4,6 +4,6 @@ <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/> </startup> <appSettings> - <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" /> + <add key="EnableWindowsFormsHighDpiAutoResizing" value="true"/> </appSettings> </configuration> From 324c0a180fcde728050e0de95b7e15bc78d4b063 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 1 Apr 2017 13:05:25 +0800 Subject: [PATCH 25/31] Add function `ReadStreamPerCharacter` --- Time_Shift/Util/ToolKits.cs | 57 ++++++++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/Time_Shift/Util/ToolKits.cs b/Time_Shift/Util/ToolKits.cs index 8f9a55e..e4880b4 100644 --- a/Time_Shift/Util/ToolKits.cs +++ b/Time_Shift/Util/ToolKits.cs @@ -22,13 +22,15 @@ using System.Text; using System.Linq; using System.Drawing; +using Microsoft.Win32; +using System.Reflection; using ChapterTool.Forms; using System.Diagnostics; +using System.Windows.Forms; using System.Security.Principal; using System.Collections.Generic; -using System.Text.RegularExpressions; using ChapterTool.Util.ChapterData; -using Microsoft.Win32; +using System.Text.RegularExpressions; namespace ChapterTool.Util { @@ -131,7 +133,7 @@ public static void SaveColor(this List<Color> colorList) var json = new StringBuilder("["); colorList.ForEach(item => json.AppendFormat($"\"#{item.R:X2}{item.G:X2}{item.B:X2}\",")); json[json.Length - 1] = ']'; - var path = $"{Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)}\\{ColorProfile}"; + var path = $"{Path.GetDirectoryName(Application.ExecutablePath)}\\{ColorProfile}"; File.WriteAllText(path, json.ToString()); } @@ -170,7 +172,7 @@ public static bool IsAdministrator() public static bool RunAsAdministrator() { if (NativeMethods.IsUserAnAdmin()) return true; - if (!RunElevated(System.Reflection.Assembly.GetExecutingAssembly().Location)) return false; + if (!RunElevated(Application.ExecutablePath)) return false; Environment.Exit(0); return true; } @@ -197,6 +199,53 @@ private static bool RunElevated(string fileName) private static readonly Lazy<bool> IsRunningOnMonoValue = new Lazy<bool>(() => Type.GetType("Mono.Runtime") != null); public static bool IsRunningOnMono => IsRunningOnMonoValue.Value; + + /// <summary> + /// Creates a DataReceivedEventArgs instance with the given Data. + /// </summary> + /// <param name="argData"></param> + /// <returns></returns> + public static DataReceivedEventArgs GetDataReceivedEventArgs(Object argData) + { + DataReceivedEventArgs eventArgs = (DataReceivedEventArgs)System.Runtime.Serialization.FormatterServices + .GetUninitializedObject(typeof(DataReceivedEventArgs)); + + FieldInfo f = typeof(DataReceivedEventArgs).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)[0]; + f.SetValue(eventArgs, argData); + + return eventArgs; + } + + /// <summary> + /// Reads a Process's standard output stream character by character and calls the user defined method for each line + /// </summary> + /// <param name="argProcess"></param> + /// <param name="argHandler"></param> + public static void ReadStreamPerCharacter(Process argProcess, DataReceivedEventHandler argHandler) + { + var reader = argProcess.StandardOutput; + var line = new StringBuilder(); + while (true) + { + if (reader.EndOfStream) break; + var c = (char) reader.Read(); + switch (c) + { + case '\r': + if ((char) reader.Peek() == '\n') reader.Read();// consume the next character + argHandler(argProcess, GetDataReceivedEventArgs(line.ToString())); + line.Length = 0; + break; + case '\n': + argHandler(argProcess, GetDataReceivedEventArgs(line.ToString())); + line.Length = 0; + break; + default: + line.Append(c); + break; + } + } + } } public static class RegistryStorage From f8c93b09525fdc69a690948d81484a8e46ae6add Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 1 Apr 2017 13:06:07 +0800 Subject: [PATCH 26/31] Add a serializable matroska chapter class. --- Time_Shift/Time_Shift.csproj | 5 +- Time_Shift/Util/ChapterData/MatroskaData.cs | 31 ++++---- .../Serializable/MatroskaChapters.cs | 72 +++++++++++++++++++ Time_Shift/Util/ChapterData/XmlData.cs | 59 +++++++++++++++ 4 files changed, 153 insertions(+), 14 deletions(-) create mode 100644 Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs diff --git a/Time_Shift/Time_Shift.csproj b/Time_Shift/Time_Shift.csproj index 1776023..26b0007 100644 --- a/Time_Shift/Time_Shift.csproj +++ b/Time_Shift/Time_Shift.csproj @@ -136,6 +136,7 @@ <Compile Include="SharpDvdInfo\Model\VideoProperties.cs" /> <Compile Include="SharpDvdInfo\Model\VmgmInfo.cs" /> <Compile Include="Util\ChapterData\FlacData.cs" /> + <Compile Include="Util\ChapterData\Serializable\MatroskaChapters.cs" /> <Compile Include="Util\Expression.cs" /> <Compile Include="Util\TaskAsync.cs" /> <Compile Include="Util\Chapter.cs" /> @@ -232,7 +233,9 @@ </ItemGroup> <ItemGroup> <Content Include="Images\about.ico" /> - <None Include="App.config" /> + <None Include="App.config"> + <SubType>Designer</SubType> + </None> <None Include="app.manifest" /> <None Include="Images\arrow_drop_down.png" /> <None Include="Images\arrow_drop_up.png" /> diff --git a/Time_Shift/Util/ChapterData/MatroskaData.cs b/Time_Shift/Util/ChapterData/MatroskaData.cs index 4c98e98..1e6261f 100644 --- a/Time_Shift/Util/ChapterData/MatroskaData.cs +++ b/Time_Shift/Util/ChapterData/MatroskaData.cs @@ -54,7 +54,8 @@ public MatroskaData() mkvToolnixPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); } } - _mkvextractPath = mkvToolnixPath + "\\mkvextract.exe"; + if (mkvToolnixPath != null) + _mkvextractPath = Path.Combine(mkvToolnixPath, "mkvextract.exe"); if (!File.Exists(_mkvextractPath)) { OnLog?.Invoke($"Mkvextract Path: {_mkvextractPath}"); @@ -65,7 +66,7 @@ public MatroskaData() public XmlDocument GetXml(string path) { string arg = $"chapters \"{path}\""; - string xmlresult = RunMkvextract(arg, _mkvextractPath); + var xmlresult = RunMkvextract(arg, _mkvextractPath); if (string.IsNullOrEmpty(xmlresult)) throw new Exception("No Chapter Found"); _result.LoadXml(xmlresult); return _result; @@ -73,16 +74,18 @@ public XmlDocument GetXml(string path) private static string RunMkvextract(string arguments, string program) { - Process process = new Process + var process = new Process { StartInfo = { FileName = program, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, StandardOutputEncoding = System.Text.Encoding.UTF8 } }; process.Start(); - string output = process.StandardOutput.ReadToEnd(); + var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); process.Close(); return output; } + + /// <summary> /// Returns the path from MKVToolnix. /// It tries to find it via the registry keys. @@ -92,13 +95,13 @@ private static string RunMkvextract(string arguments, string program) private static string GetMkvToolnixPathViaRegistry() { RegistryKey regMkvToolnix = null; - string valuePath = string.Empty; - bool subKeyFound = false; - bool valueFound = false; + var valuePath = string.Empty; + var subKeyFound = false; + var valueFound = false; // First check for Installed MkvToolnix // First check Win32 registry - RegistryKey regUninstall = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); + var regUninstall = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); if (regUninstall == null) { throw new Exception("Failed to create a RegistryKey variable"); @@ -112,7 +115,8 @@ private static string GetMkvToolnixPathViaRegistry() // if sub key was found, try to get the executable path if (subKeyFound) { - foreach (string valueName in regMkvToolnix.GetValueNames().Where(valueName => valueName.ToLower().Equals("DisplayIcon".ToLower()))) + if (regMkvToolnix == null) throw new Exception($"Failed to open key {nameof(regMkvToolnix)}"); + foreach (var valueName in regMkvToolnix.GetValueNames().Where(valueName => valueName.ToLower().Equals("DisplayIcon".ToLower()))) { valueFound = true; valuePath = (string)regMkvToolnix.GetValue(valueName); @@ -125,7 +129,7 @@ private static string GetMkvToolnixPathViaRegistry() { subKeyFound = false; regUninstall = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"); - + if (regUninstall == null) throw new Exception($"Failed to open key {nameof(regUninstall)}"); if (regUninstall.GetSubKeyNames().Any(subKeyName => subKeyName.ToLower().Equals("MKVToolNix".ToLower()))) { subKeyFound = true; @@ -135,7 +139,8 @@ private static string GetMkvToolnixPathViaRegistry() // if sub key was found, try to get the executable path if (subKeyFound) { - foreach (string valueName in regMkvToolnix.GetValueNames().Where(valueName => valueName.ToLower().Equals("DisplayIcon".ToLower()))) + if (regMkvToolnix == null) throw new Exception($"Failed to open key {nameof(regMkvToolnix)}"); + foreach (var valueName in regMkvToolnix.GetValueNames().Where(valueName => valueName.ToLower().Equals("DisplayIcon".ToLower()))) { valueFound = true; valuePath = (string)regMkvToolnix.GetValue(valueName); @@ -148,7 +153,7 @@ private static string GetMkvToolnixPathViaRegistry() // let's try the CURRENT_USER registry if (!valueFound) { - RegistryKey regSoftware = Registry.CurrentUser.OpenSubKey("Software"); + var regSoftware = Registry.CurrentUser.OpenSubKey("Software"); subKeyFound = false; if (regSoftware != null && regSoftware.GetSubKeyNames().Any(subKey => subKey.ToLower().Equals("mkvmergeGUI".ToLower()))) { @@ -162,7 +167,7 @@ private static string GetMkvToolnixPathViaRegistry() throw new Exception("Couldn't find MKVToolNix in your system!\r\nPlease download and install it or provide a manual path!"); } RegistryKey regGui = null; - bool foundGuiKey = false; + var foundGuiKey = false; if (regMkvToolnix != null && regMkvToolnix.GetSubKeyNames().Any(subKey => subKey.ToLower().Equals("GUI".ToLower()))) { foundGuiKey = true; diff --git a/Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs b/Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs new file mode 100644 index 0000000..f39ac40 --- /dev/null +++ b/Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs @@ -0,0 +1,72 @@ +using System; +using System.Xml.Serialization; + +namespace ChapterTool.Util.ChapterData.Serializable +{ + [Serializable] + public class Chapters + { + [XmlElement("EditionEntry")] + public EditionEntry[] EditionEntry { get; set; } + } + + [Serializable] + public class EditionEntry + { + public string EditionUID { get; set; } + public string EditionFlagHidden { get; set; } + public string EditionManaged { get; set; } + public string EditionFlagDefault { get; set; } + [XmlElement("ChapterAtom")] + public ChapterAtom[] ChapterAtom { get; set; } + } + + [Serializable] + public class ChapterAtom + { + public string ChapterTimeStart { get; set; } + public string ChapterTimeEnd { get; set; } + public string ChapterUID { get; set; } + public string ChapterSegmentUID { get; set; } + public string ChapterSegmentEditionUID { get; set; } + public string ChapterPhysicalEquiv { get; set; } + public ChapterTrack ChapterTrack { get; set; } + public string ChapterFlagHidden { get; set; } + public string ChapterFlagEnabled { get; set; } + public ChapterDisplay ChapterDisplay { get; set; } + [XmlElement("ChapterProcess")] + public ChapterProcess[] ChapterProcess { get; set; } + [XmlElement("ChapterAtom")] + public ChapterAtom[] SubChapterAtom { get; set; } + } + + [Serializable] + public class ChapterTrack + { + public string ChapterTrackNumber { get; set; } + } + + [Serializable] + public class ChapterDisplay + { + public string ChapterString { get; set; } + public string ChapterLanguage { get; set; } + public string ChapterCountry { get; set; } + } + + [Serializable] + public class ChapterProcess + { + public string ChapterProcessCodecID { get; set; } + public string ChapterProcessPrivate { get; set; } + [XmlElement("ChapterProcessCommand")] + public ChapterProcessCommand[] ChapterProcessCommand { get; set; } + } + + [Serializable] + public class ChapterProcessCommand + { + public string ChapterProcessTime { get; set; } + public string ChapterProcessData { get; set; } + } +} \ No newline at end of file diff --git a/Time_Shift/Util/ChapterData/XmlData.cs b/Time_Shift/Util/ChapterData/XmlData.cs index a32dc4e..2f3826a 100644 --- a/Time_Shift/Util/ChapterData/XmlData.cs +++ b/Time_Shift/Util/ChapterData/XmlData.cs @@ -19,9 +19,12 @@ // **************************************************************************** using System; +using System.IO; using System.Xml; using System.Linq; +using System.Xml.Serialization; using System.Collections.Generic; +using ChapterTool.Util.ChapterData.Serializable; namespace ChapterTool.Util.ChapterData { @@ -111,5 +114,61 @@ private static IEnumerable<Chapter> PraseChapterAtom(XmlNode chapterAtom, int in yield return endChapter; } } + + public static Chapters Deserializer(string filePath) + { + using (var reader = new StreamReader(filePath)) + { + return (Chapters)new XmlSerializer(typeof(Chapters)).Deserialize(reader); + } + } + + public static IEnumerable<ChapterInfo> ToChapterInfo(this Chapters chapters) + { + var index = 0; + foreach (var entry in chapters.EditionEntry) + { + var info = new ChapterInfo(); + foreach (var atom in entry.ChapterAtom) + { + info.Chapters.AddRange(ToChapter(atom, ++index)); + } + yield return info; + } + } + + private static IEnumerable<Chapter> ToChapter(ChapterAtom atom, int index) + { + if (atom.ChapterTimeStart != null) + { + var startChapter = new Chapter + { + Number = index, + Time = ToolKits.RTimeFormat.Match(atom.ChapterTimeStart).Value.ToTimeSpan(), + Name = atom.ChapterDisplay.ChapterString ?? "" + }; + yield return startChapter; + } + + if (atom.SubChapterAtom != null) + foreach (var chapterAtom in atom.SubChapterAtom) + { + foreach (var chapter in ToChapter(chapterAtom, index)) + { + yield return chapter; + } + } + + if (atom.ChapterTimeEnd != null) + { + var endChapter = new Chapter + { + Number = index, + Time = ToolKits.RTimeFormat.Match(atom.ChapterTimeEnd).Value.ToTimeSpan(), + Name = atom.ChapterDisplay.ChapterString ?? "" + }; + yield return endChapter; + } + } } } \ No newline at end of file From b6ce2fc7c3193c7799dbed2b54f113a3d6b73ea4 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Sat, 1 Apr 2017 15:09:28 +0800 Subject: [PATCH 27/31] Fix typo. --- Time_Shift/Util/ChapterData/MplsData.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Time_Shift/Util/ChapterData/MplsData.cs b/Time_Shift/Util/ChapterData/MplsData.cs index 6bf9412..89a87a1 100644 --- a/Time_Shift/Util/ChapterData/MplsData.cs +++ b/Time_Shift/Util/ChapterData/MplsData.cs @@ -210,7 +210,7 @@ public ChapterInfo ToChapterInfo(int index, bool combineChapter) if (selectedTimeStamp.Count < 2) return info; int offset = selectedTimeStamp.First(); /** - * the begin time stamp of the chapter isn't the begin of the video + * the beginning time stamp of the chapter not always the beginning of the video * eg: Hidan no Aria AA, There are 24 black frames at the begining of each even episode * Which results that the first time stamp should be the 00:00:01.001 */ @@ -232,14 +232,14 @@ public ChapterInfo ToChapterInfo(int index, bool combineChapter) public class Clip { - public string Name { get; set; } + public string Name { get; set; } public List<int> TimeStamp { get; } = new List<int>(); - public int Fps { get; set; } - public int Length { get; set; } - public int RelativeTimeIn { get; set; } + public int Fps { get; set; } + public int Length { get; set; } + public int RelativeTimeIn { get; set; } public int RelativeTimeOut { get; set; } - public int TimeIn { get; set; } - public int TimeOut { get; set; } + public int TimeIn { get; set; } + public int TimeOut { get; set; } public override string ToString() => $"{Name} - {MplsData.Pts2Time(Length)}"; } From 350c62812989667e236d0f05537a2038ad8d7bf5 Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Tue, 18 Apr 2017 10:58:29 +0800 Subject: [PATCH 28/31] Format code. --- Time_Shift/Forms/Form1.cs | 6 +- Time_Shift/Util/ChapterData/BDMVData.cs | 2 +- Time_Shift/Util/ChapterData/FlacData.cs | 60 ++++++++-------- .../Serializable/MatroskaChapters.cs | 4 +- Time_Shift/Util/ToolKits.cs | 69 +++++++++---------- 5 files changed, 69 insertions(+), 72 deletions(-) diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index 989997f..5e3f552 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -601,7 +601,7 @@ private void LoadOgm() try { OgmData.OnLog += Log; - _info = OgmData.GetChapterInfo(File.ReadAllBytes(FilePath).GetUTF8String()); + _info = OgmData.GetChapterInfo(File.ReadAllBytes(FilePath).GetUTFString()); _info.UpdataInfo((int)numericUpDown1.Value); tsProgressBar1.Value = 33; tsTips.Text = Resources.Tips_Load_Success; @@ -666,7 +666,7 @@ private void LoadCue() private void LoadWebVTT() { - _info = VTTData.GetChapterInfo(File.ReadAllBytes(FilePath).GetUTF8String()); + _info = VTTData.GetChapterInfo(File.ReadAllBytes(FilePath).GetUTFString()); _info.UpdataInfo((int)numericUpDown1.Value); tsProgressBar1.Value = 33; tsTips.Text = Resources.Tips_Load_Success; @@ -1374,7 +1374,7 @@ private string LoadChapterName() string chapterPath = openFileDialog1.FileName; Log(string.Format(Resources.Log_Chapter_Name_Template, chapterPath)); - return File.ReadAllBytes(chapterPath).GetUTF8String(); + return File.ReadAllBytes(chapterPath).GetUTFString(); } cbChapterName.CheckState = CheckState.Unchecked; return string.Empty; diff --git a/Time_Shift/Util/ChapterData/BDMVData.cs b/Time_Shift/Util/ChapterData/BDMVData.cs index 286650c..56c4ea8 100644 --- a/Time_Shift/Util/ChapterData/BDMVData.cs +++ b/Time_Shift/Util/ChapterData/BDMVData.cs @@ -90,7 +90,7 @@ public static async Task<KeyValuePair<string, List<ChapterInfo>>> GetChapterAsyn OnLog?.Invoke(text); throw new Exception("Error creating chapters file."); } - current.Chapters = OgmData.GetChapterInfo(File.ReadAllBytes(chapterPath).GetUTF8String()).Chapters; + current.Chapters = OgmData.GetChapterInfo(File.ReadAllBytes(chapterPath).GetUTFString()).Chapters; if (current.Chapters.First().Name != "") continue; var chapterName = ChapterName.GetChapterName(); current.Chapters.ForEach(chapter => chapter.Name = chapterName()); diff --git a/Time_Shift/Util/ChapterData/FlacData.cs b/Time_Shift/Util/ChapterData/FlacData.cs index b70923c..7f714e9 100644 --- a/Time_Shift/Util/ChapterData/FlacData.cs +++ b/Time_Shift/Util/ChapterData/FlacData.cs @@ -66,7 +66,7 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) using (var fs = File.Open(flacPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (fs.Length < SizeThreshold) return new FlacInfo(); - FlacInfo info = new FlacInfo {TrueLength = fs.Length}; + var info = new FlacInfo {TrueLength = fs.Length}; var header = Encoding.ASCII.GetString(fs.ReadBytes(4), 0, 4); if (header != "fLaC") throw new InvalidDataException($"Except an flac but get an {header}"); @@ -76,10 +76,10 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) //24-bit Length while (fs.Position < fs.Length) { - uint blockHeader = fs.BEInt32(); - bool lastMetadataBlock = blockHeader >> 31 == 0x1; - BlockType blockType = (BlockType)((blockHeader >> 24) & 0x7f); - int length = (int) (blockHeader & 0xffffff); + var blockHeader = fs.BEInt32(); + var lastMetadataBlock = blockHeader >> 31 == 0x1; + var blockType = (BlockType)((blockHeader >> 24) & 0x7f); + var length = blockHeader & 0xffffff; info.TrueLength -= length; OnLog?.Invoke($"|+{blockType} with Length: {length}"); switch (blockType) @@ -111,38 +111,38 @@ public static FlacInfo GetMetadataFromFlac(string flacPath) private static void ParseStreamInfo(Stream fs, ref FlacInfo info) { - long minBlockSize = fs.BEInt16(); - long maxBlockSize = fs.BEInt16(); - long minFrameSize = fs.BEInt24(); - long maxFrameSize = fs.BEInt24(); + var minBlockSize = fs.BEInt16(); + var maxBlockSize = fs.BEInt16(); + var minFrameSize = fs.BEInt24(); + var maxFrameSize = fs.BEInt24(); var buffer = fs.ReadBytes(8); - BitReader br = new BitReader(buffer); - int sampleRate = (int) br.GetBits(20); - int channelCount = (int) br.GetBits(3)+1; - int bitPerSample = (int) br.GetBits(5)+1; - int totalSample = (int) br.GetBits(36); + var br = new BitReader(buffer); + var sampleRate = br.GetBits(20); + var channelCount = br.GetBits(3)+1; + var bitPerSample = br.GetBits(5)+1; + var totalSample = br.GetBits(36); var md5 = fs.ReadBytes(16); info.RawLength = channelCount * bitPerSample / 8 * totalSample; OnLog?.Invoke($" | minimum block size: {minBlockSize}, maximum block size: {maxBlockSize}"); OnLog?.Invoke($" | minimum frame size: {minFrameSize}, maximum frame size: {maxFrameSize}"); OnLog?.Invoke($" | Sample rate: {sampleRate}Hz, bits per sample: {bitPerSample}-bit"); OnLog?.Invoke($" | Channel count: {channelCount}"); - string md5String = md5.Aggregate("", (current, item) => current + $"{item:X2}"); + var md5String = md5.Aggregate("", (current, item) => current + $"{item:X2}"); OnLog?.Invoke($" | MD5: {md5String}"); } private static void ParseVorbisComment(Stream fs, ref FlacInfo info) { //only here in flac use little-endian - int vendorLength = (int) fs.LEInt32(); + var vendorLength = (int) fs.LEInt32(); var vendorRawStringData = fs.ReadBytes(vendorLength); - var vendor = Encoding.UTF8.GetString(vendorRawStringData, 0, vendorLength); - info.Encoder = vendor; + var vendor = Encoding.UTF8.GetString(vendorRawStringData, 0, vendorLength); + info.Encoder = vendor; OnLog?.Invoke($" | Vendor: {vendor}"); - int userCommentListLength = (int) fs.LEInt32(); + var userCommentListLength = fs.LEInt32(); for (int i = 0; i < userCommentListLength; ++i) { - int commentLength = (int) fs.LEInt32(); + var commentLength = (int) fs.LEInt32(); var commentRawStringData = fs.ReadBytes(commentLength); var comment = Encoding.UTF8.GetString(commentRawStringData, 0, commentLength); var spilterIndex = comment.IndexOf('='); @@ -168,16 +168,16 @@ private static void ParseVorbisComment(Stream fs, ref FlacInfo info) private static void ParsePicture(Stream fs, ref FlacInfo info) { - int pictureType = (int) fs.BEInt32(); - int mimeStringLength = (int) fs.BEInt32(); - string mimeType = Encoding.ASCII.GetString(fs.ReadBytes(mimeStringLength), 0, mimeStringLength); - int descriptionLength = (int) fs.BEInt32(); - string description = Encoding.UTF8.GetString(fs.ReadBytes(descriptionLength), 0, descriptionLength); - int pictureWidth = (int) fs.BEInt32(); - int pictureHeight = (int) fs.BEInt32(); - int colorDepth = (int) fs.BEInt32(); - int indexedColorCount = (int) fs.BEInt32(); - int pictureDataLength = (int) fs.BEInt32(); + var pictureType = fs.BEInt32(); + var mimeStringLength = (int) fs.BEInt32(); + var mimeType = Encoding.ASCII.GetString(fs.ReadBytes(mimeStringLength), 0, mimeStringLength); + var descriptionLength = (int) fs.BEInt32(); + var description = Encoding.UTF8.GetString(fs.ReadBytes(descriptionLength), 0, descriptionLength); + var pictureWidth = fs.BEInt32(); + var pictureHeight = fs.BEInt32(); + var colorDepth = fs.BEInt32(); + var indexedColorCount = fs.BEInt32(); + var pictureDataLength = fs.BEInt32(); fs.Seek(pictureDataLength, SeekOrigin.Current); info.TrueLength -= pictureDataLength; info.HasCover = true; diff --git a/Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs b/Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs index f39ac40..f285581 100644 --- a/Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs +++ b/Time_Shift/Util/ChapterData/Serializable/MatroskaChapters.cs @@ -17,7 +17,7 @@ public class EditionEntry public string EditionFlagHidden { get; set; } public string EditionManaged { get; set; } public string EditionFlagDefault { get; set; } - [XmlElement("ChapterAtom")] + [XmlElement("ChapterAtom")] public ChapterAtom[] ChapterAtom { get; set; } } @@ -51,7 +51,7 @@ public class ChapterDisplay { public string ChapterString { get; set; } public string ChapterLanguage { get; set; } - public string ChapterCountry { get; set; } + public string ChapterCountry { get; set; } } [Serializable] diff --git a/Time_Shift/Util/ToolKits.cs b/Time_Shift/Util/ToolKits.cs index e4880b4..87f5009 100644 --- a/Time_Shift/Util/ToolKits.cs +++ b/Time_Shift/Util/ToolKits.cs @@ -20,7 +20,6 @@ using System; using System.IO; using System.Text; -using System.Linq; using System.Drawing; using Microsoft.Win32; using System.Reflection; @@ -66,10 +65,10 @@ public static TimeSpan ToTimeSpan(this string input) if (string.IsNullOrWhiteSpace(input)) return TimeSpan.Zero; var timeMatch = RTimeFormat.Match(input); if (!timeMatch.Success) return TimeSpan.Zero; - int hour = int.Parse(timeMatch.Groups["Hour"].Value); - int minute = int.Parse(timeMatch.Groups["Minute"].Value); - int second = int.Parse(timeMatch.Groups["Second"].Value); - int millisecond = int.Parse(timeMatch.Groups["Millisecond"].Value); + var hour = int.Parse(timeMatch.Groups["Hour"].Value); + var minute = int.Parse(timeMatch.Groups["Minute"].Value); + var second = int.Parse(timeMatch.Groups["Second"].Value); + var millisecond = int.Parse(timeMatch.Groups["Millisecond"].Value); return new TimeSpan(0, hour, minute, second, millisecond); } @@ -91,8 +90,8 @@ public static Point String2Point(string input) var rpos = new Regex(@"{X=(?<x>.+),Y=(?<y>.+)}", RegexOptions.Compiled); var result = rpos.Match(input); if (!result.Success) return new Point(-32000, -32000); - int x = int.Parse(result.Groups["x"].Value); - int y = int.Parse(result.Groups["y"].Value); + var x = int.Parse(result.Groups["x"].Value); + var y = int.Parse(result.Groups["y"].Value); return new Point(x, y); } @@ -102,14 +101,21 @@ public static Point String2Point(string input) /// <param name="frame"></param> /// <returns></returns> public static int ConvertFr2Index(double frame) - => Enumerable.Range(0, 8).First(index => Math.Abs(frame - (double)MplsData.FrameRate[index]) < 1e-5); + { + for (int i = 0; i < MplsData.FrameRate.Length; ++i) + { + if (Math.Abs(frame - (double)MplsData.FrameRate[i]) < 1e-5) + return i; + } + return 0; + } /// <summary> - /// 读取带或不带BOM头的UTF-8文本 + /// 读取带或不带BOM头的UTF文本 /// </summary> - /// <param name="buffer">UTF-8文本的字节串</param> + /// <param name="buffer">UTF文本的字节串</param> /// <returns></returns> - public static string GetUTF8String(this byte[] buffer) + public static string GetUTFString(this byte[] buffer) { if (buffer == null) return null; if (buffer.Length <= 3) return Encoding.UTF8.GetString(buffer); @@ -133,7 +139,7 @@ public static void SaveColor(this List<Color> colorList) var json = new StringBuilder("["); colorList.ForEach(item => json.AppendFormat($"\"#{item.R:X2}{item.G:X2}{item.B:X2}\",")); json[json.Length - 1] = ']'; - var path = $"{Path.GetDirectoryName(Application.ExecutablePath)}\\{ColorProfile}"; + var path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath) ?? "", ColorProfile); File.WriteAllText(path, json.ToString()); } @@ -144,8 +150,8 @@ public static void SaveColor(this List<Color> colorList) public static void LoadColor(this Form1 window) { if (!File.Exists(ColorProfile)) return; - string json = File.ReadAllText(ColorProfile); - Regex rcolor = new Regex("\"(?<hex>.+?)\"", RegexOptions.Compiled); + var json = File.ReadAllText(ColorProfile); + var rcolor = new Regex("\"(?<hex>.+?)\"", RegexOptions.Compiled); var matchesOfJson = rcolor.Matches(json); if (matchesOfJson.Count < 6) return; window.BackChange = ColorTranslator.FromHtml(matchesOfJson[0].Groups["hex"].Value); @@ -162,12 +168,7 @@ public static void LoadColor(this Form1 window) public static void SaveAs(this object chapter, string path) => File.WriteAllText(path, chapter.ToString(), Encoding.UTF8); - public static bool IsAdministrator() - { - WindowsIdentity identity = WindowsIdentity.GetCurrent(); - WindowsPrincipal principal = new WindowsPrincipal(identity); - return principal.IsInRole(WindowsBuiltInRole.Administrator); - } + public static bool IsAdministrator() => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); public static bool RunAsAdministrator() { @@ -179,14 +180,13 @@ public static bool RunAsAdministrator() private static bool RunElevated(string fileName) { - ProcessStartInfo processInfo = new ProcessStartInfo - { - Verb = "runas", - FileName = fileName - }; try { - Process.Start(processInfo); + Process.Start(new ProcessStartInfo + { + Verb = "runas", + FileName = fileName + }); return true; } catch (System.ComponentModel.Win32Exception) @@ -205,13 +205,11 @@ private static bool RunElevated(string fileName) /// </summary> /// <param name="argData"></param> /// <returns></returns> - public static DataReceivedEventArgs GetDataReceivedEventArgs(Object argData) + public static DataReceivedEventArgs GetDataReceivedEventArgs(object argData) { - DataReceivedEventArgs eventArgs = (DataReceivedEventArgs)System.Runtime.Serialization.FormatterServices - .GetUninitializedObject(typeof(DataReceivedEventArgs)); - - FieldInfo f = typeof(DataReceivedEventArgs).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)[0]; - f.SetValue(eventArgs, argData); + var eventArgs = (DataReceivedEventArgs)System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(DataReceivedEventArgs)); + var fileds = typeof(DataReceivedEventArgs).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)[0]; + fileds.SetValue(eventArgs, argData); return eventArgs; } @@ -225,20 +223,19 @@ public static void ReadStreamPerCharacter(Process argProcess, DataReceivedEventH { var reader = argProcess.StandardOutput; var line = new StringBuilder(); - while (true) + while (!reader.EndOfStream) { - if (reader.EndOfStream) break; var c = (char) reader.Read(); switch (c) { case '\r': if ((char) reader.Peek() == '\n') reader.Read();// consume the next character argHandler(argProcess, GetDataReceivedEventArgs(line.ToString())); - line.Length = 0; + line.Clear(); break; case '\n': argHandler(argProcess, GetDataReceivedEventArgs(line.ToString())); - line.Length = 0; + line.Clear(); break; default: line.Append(c); From 9a94f799bef67ce0fc3dee36d492341671ef602c Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Tue, 18 Apr 2017 12:23:52 +0800 Subject: [PATCH 29/31] Use `var` if possible. --- Time_Shift/Controls/HiLightTextBox.cs | 4 +- Time_Shift/Controls/cTextBox.cs | 4 +- Time_Shift/Forms/Form1.cs | 62 +++++++-------- Time_Shift/Forms/FormAbout.cs | 4 +- Time_Shift/Knuckleball/Chapter.cs | 2 +- Time_Shift/Knuckleball/ChapterList.cs | 24 +++--- Time_Shift/Knuckleball/IntPtrExtensions.cs | 4 +- Time_Shift/Knuckleball/MP4File.cs | 4 +- Time_Shift/Program.cs | 2 +- Time_Shift/SharpDvdInfo/DvdInfoContainer.cs | 84 ++++++++++----------- Time_Shift/Util/ChapterData/BDMVData.cs | 10 +-- Time_Shift/Util/ChapterData/CueData.cs | 16 ++-- Time_Shift/Util/ChapterData/FlacData.cs | 8 +- Time_Shift/Util/ChapterData/IfoData.cs | 54 ++++++------- Time_Shift/Util/ChapterData/IfoParser.cs | 16 ++-- Time_Shift/Util/ChapterData/Mp4Data.cs | 4 +- Time_Shift/Util/ChapterData/MplsData.cs | 42 +++++------ Time_Shift/Util/ChapterData/OgmData.cs | 8 +- Time_Shift/Util/ChapterData/VTTData.cs | 2 +- Time_Shift/Util/ChapterData/XmlData.cs | 13 ++-- Time_Shift/Util/ChapterData/XplData.cs | 20 ++--- Time_Shift/Util/ChapterInfo.cs | 30 ++++---- Time_Shift/Util/ChapterName.cs | 2 +- Time_Shift/Util/CueSharp.cs | 52 ++++++------- Time_Shift/Util/Expression.cs | 14 ++-- Time_Shift/Util/LanguageHelper.cs | 8 +- Time_Shift/Util/Logger.cs | 2 +- Time_Shift/Util/Notification.cs | 11 ++- Time_Shift/Util/SystemMenu.cs | 4 +- Time_Shift/Util/ToolKits.cs | 10 +-- Time_Shift/Util/Updater.cs | 20 ++--- 31 files changed, 269 insertions(+), 271 deletions(-) diff --git a/Time_Shift/Controls/HiLightTextBox.cs b/Time_Shift/Controls/HiLightTextBox.cs index 78dc8fb..eff3e45 100644 --- a/Time_Shift/Controls/HiLightTextBox.cs +++ b/Time_Shift/Controls/HiLightTextBox.cs @@ -39,7 +39,7 @@ public void AddPattern(Pattern pattern) protected override void OnTextChanged(EventArgs e) { - BackgroundWorker worker = new BackgroundWorker(); + var worker = new BackgroundWorker(); worker.DoWork += HighLight; worker.RunWorkerAsync(Rtf); worker.RunWorkerCompleted += (sender, args) => Rtf = args.Result as string; @@ -51,7 +51,7 @@ private void HighLight(object sender, DoWorkEventArgs e) { try { - RichTextBox text = new RichTextBox + var text = new RichTextBox { Rtf = e.Argument as string, SelectionStart = 0 diff --git a/Time_Shift/Controls/cTextBox.cs b/Time_Shift/Controls/cTextBox.cs index 702616f..e0efa58 100644 --- a/Time_Shift/Controls/cTextBox.cs +++ b/Time_Shift/Controls/cTextBox.cs @@ -45,8 +45,8 @@ protected override void OnKeyDown(KeyEventArgs e) } else if (e.Alt && e.KeyCode == Keys.A) { - int totalLine = GetLineFromCharIndex(Text.Length); - int charIndex = GetFirstCharIndexFromLine(totalLine / 2); + var totalLine = GetLineFromCharIndex(Text.Length); + var charIndex = GetFirstCharIndexFromLine(totalLine / 2); Select(charIndex, Text.Length); } e.Handled = true; diff --git a/Time_Shift/Forms/Form1.cs b/Time_Shift/Forms/Form1.cs index 5e3f552..7d0e3d3 100644 --- a/Time_Shift/Forms/Form1.cs +++ b/Time_Shift/Forms/Form1.cs @@ -139,7 +139,7 @@ private bool SwitchByHotKey(int index) private void SwitchByHotKey(Keys keyData) { - Keys numKey = keyData ^ Keys.Control; + var numKey = keyData ^ Keys.Control; Debug.WriteLine(numKey); if (numKey < Keys.D0 || numKey > Keys.D9) return; if (!SwitchByHotKey((numKey - Keys.D1 + 10) % 10)) //shift D0 to 9 @@ -150,9 +150,9 @@ private void SwitchByHotKey(Keys keyData) private void SwitchTypeByHotKey(Keys keyData) { - Keys numKey = keyData ^ Keys.Alt; + var numKey = keyData ^ Keys.Alt; Debug.WriteLine(numKey); - int index = numKey - Keys.D0; + var index = numKey - Keys.D0; if (index < 0 || index > savingType.Items.Count) return; savingType.SelectedIndex = index - 1; } @@ -167,7 +167,7 @@ private void Form1_Load(object sender, EventArgs e) InitialLog(); if (!IsRunningOnMono) { - Point saved = String2Point(RegistryStorage.Load(@"Software\ChapterTool", "location")); + var saved = String2Point(RegistryStorage.Load(@"Software\ChapterTool", "location")); if (saved != new Point(-32000, -32000)) { Location = saved; @@ -279,7 +279,7 @@ private void progressBar1_Click(object sender, EventArgs e) Log(string.Format(Resources.Log_About_Form_Click, _poi[0])); if (_poi[0] >= _poi[1]) { - FormAbout version = new FormAbout(); + var version = new FormAbout(); Log(Resources.Log_About_Form_Opened); version.Show(); _poi[0] = 00; @@ -370,8 +370,8 @@ private enum FileType private static readonly Lazy<string> MainFilter = new Lazy<string>(() => { Func<IEnumerable<string>, string> getType = enumerable => enumerable.Aggregate(string.Empty, (current, type) => current + $"*.{type};"); - StringBuilder ret = new StringBuilder(Resources.File_Filter_All_Support); - string types = getType(SupportTypes.SelectMany(supportType => supportType.Value)); + var ret = new StringBuilder(Resources.File_Filter_All_Support); + var types = getType(SupportTypes.SelectMany(supportType => supportType.Value)); ret.Append($" ({types.TrimEnd(';')})|{types}"); foreach (var supportType in SupportTypes) { @@ -521,7 +521,7 @@ private void LoadIfo() foreach (var item in _ifoGroup) { comboBox2.Items.Add($"{item.SourceName}__{item.Chapters.Count}"); - int index = 0; + var index = 0; item.Chapters.ForEach(chapter => chapter.Number = ++index); Log($" |+{item.SourceName} Duration[{item.Duration.Time2String()}]"); Log(string.Format(Resources.Log_TimeStamp_Count, item.Chapters.Count)); @@ -560,7 +560,7 @@ private void LoadXpl() foreach (var item in _xplGroup) { comboBox2.Items.Add($"{item.Title}__{item.Chapters.Count}"); - int index = 0; + var index = 0; item.Chapters.ForEach(chapter => chapter.Number = ++index); } _info = _xplGroup.First(); @@ -731,11 +731,11 @@ private void reloadToolStripMenuItem_Click(object sender, EventArgs e) private void appendToolStripMenuItem_Click(object sender, EventArgs e) { if (_rawMpls == null) return; - string dir = Path.GetDirectoryName(FilePath); + var dir = Path.GetDirectoryName(FilePath); openFileDialog1.Filter = @"appendable file(mpls file)|*.mpls"; openFileDialog1.InitialDirectory = dir; if (openFileDialog1.ShowDialog() != DialogResult.OK) return; - string newFile = openFileDialog1.FileName; + var newFile = openFileDialog1.FileName; LoadMpls(out MplsData appendMpls, false, newFile); _rawMpls.EntireClip.TimeStamp.AddRange(appendMpls.EntireClip.TimeStamp.Select(stamp=>stamp+ _rawMpls.EntireClip.Length)); _rawMpls.EntireClip.Length += appendMpls.EntireClip.Length; @@ -816,7 +816,7 @@ private string GeneRateSavePath(SaveTypeEnum saveType) if (ext == ".mpls" || ext == ".ifo") savePath += $"__{_info.SourceName}"; - int index = 1; + var index = 1; while (File.Exists($"{savePath}_{index}{SaveTypeSuffix[saveType]}")) ++index; savePath += $"_{index}{SaveTypeSuffix[saveType]}"; @@ -864,7 +864,7 @@ private void SaveFile(SaveTypeEnum saveType) _info.GetText(AutoGenName).SaveAs(savePath); break; case SaveTypeEnum.XML: - string key = RLang.Match(xmlLang.Items[xmlLang.SelectedIndex].ToString()).Groups["lang"].ToString(); + var key = RLang.Match(xmlLang.Items[xmlLang.SelectedIndex].ToString()).Groups["lang"].ToString(); _info.SaveXml(savePath, string.IsNullOrWhiteSpace(key) ? "" : LanguageSelectionContainer.Languages[key], AutoGenName); break; case SaveTypeEnum.QPF: @@ -966,7 +966,7 @@ private void GetChapterInfoFromXml(XmlDocument doc) if (comboBox2.Enabled) { comboBox2.Items.Clear(); - int i = 1; + var i = 1; foreach (var item in _xmlGroup) { var name = $"Edition {i++:D2}"; @@ -1008,7 +1008,7 @@ private void UpdataGridView(int fpsIndex = 0, bool updateFrameInfo = true) } SKIP: - bool clearRows = _info.Chapters.Count != dataGridView1.Rows.Count || _splitRowInsrted; + var clearRows = _info.Chapters.Count != dataGridView1.Rows.Count || _splitRowInsrted; if (clearRows) dataGridView1.Rows.Clear(); for (var i = 0; i < _info.Chapters.Count; i++) { @@ -1038,7 +1038,7 @@ private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelE _info.Chapters.Remove(e.Row.Tag as Chapter); _info.UpdataInfo((int)numericUpDown1.Value); if (_info.Chapters.Count < 1 || e.Row.Index != 0) return; - TimeSpan newInitialTime = _info.Chapters.First().Time; + var newInitialTime = _info.Chapters.First().Time; _info.UpdataInfo(newInitialTime); if ((_rawMpls != null || _ifoGroup != null) && string.IsNullOrWhiteSpace(_chapterNameTemplate)) { @@ -1089,7 +1089,7 @@ private void GetFramInfo(int index = 0) if (Round) { var rounded = Round ? Math.Round(frams, MidpointRounding.AwayFromZero) : frams; - bool accuracy = Math.Abs(frams - rounded) < settingAccuracy; + var accuracy = Math.Abs(frams - rounded) < settingAccuracy; chapter.FramsInfo = $"{rounded}{(accuracy ? " K" : " *")}"; } else @@ -1107,7 +1107,7 @@ private int GetAutofps(decimal accuracy) item.IsAccuracy(fps, accuracy, _info.Expr))).ToList(); result[0] = 0; result[5] = 0; //skip two invalid frame rate. result.ForEach(count => Log(string.Format(Resources.Log_FPS_Detect_Count, count))); - int autofpsCode = result.IndexOf(result.Max()); + var autofpsCode = result.IndexOf(result.Max()); _info.FramesPerSecond = (double) MplsData.FrameRate[autofpsCode]; Log(string.Format(Resources.Log_FPS_Detect_Result, MplsData.FrameRate[autofpsCode])); return autofpsCode == 0 ? 1 : autofpsCode; @@ -1126,7 +1126,7 @@ private void FrameShiftForward() if (fpsIndex < 1) return; var shiftFramesString = Notification.InputBox("向前平移N帧,小于0的将被删除", "请输入所需平移的帧数", "0"); if (!int.TryParse(shiftFramesString, out int shiftFrames)) return; - TimeSpan shiftTime = TimeSpan.FromTicks((long) Math.Round(shiftFrames/MplsData.FrameRate[fpsIndex]*TimeSpan.TicksPerSecond)); + var shiftTime = TimeSpan.FromTicks((long) Math.Round(shiftFrames/MplsData.FrameRate[fpsIndex]*TimeSpan.TicksPerSecond)); _info.UpdataInfo(shiftTime); _info.Chapters = _info.Chapters.SkipWhile(item => item.Time < TimeSpan.Zero).ToList(); UpdataGridView(); @@ -1277,9 +1277,9 @@ private void Form1_FormClosing(object sender, FormClosingEventArgs e) { RegistryStorage.Save(Location.ToString(), @"Software\ChapterTool", "Location"); if (_poi[0] <= 0 || _poi[0] >= 3 || _poi[1] != 10) return; - Point origin = Location; - Random forward = new Random(); - int forward2 = forward.Next(1, 5); + var origin = Location; + var forward = new Random(); + var forward2 = forward.Next(1, 5); if (forward2 % 2 == 0 || Environment.OSVersion.Version.Major == 5) { for(var i = 0; i < 100; ++i) @@ -1371,7 +1371,7 @@ private string LoadChapterName() { if (openFileDialog1.ShowDialog() == DialogResult.OK) { - string chapterPath = openFileDialog1.FileName; + var chapterPath = openFileDialog1.FileName; Log(string.Format(Resources.Log_Chapter_Name_Template, chapterPath)); return File.ReadAllBytes(chapterPath).GetUTFString(); @@ -1529,7 +1529,7 @@ private void InsertMpls() var fileLine = comboBox2.Text; foreach (var file in fileLine.Substring(0, fileLine.LastIndexOf('_') - 1).Split('&')) { - ToolStripMenuItem fMenuItem = new ToolStripMenuItem(string.Format(Resources.Menu_Open_File, $"{file}.m2ts")); + var fMenuItem = new ToolStripMenuItem(string.Format(Resources.Menu_Open_File, $"{file}.m2ts")); fMenuItem.Click += (sender, args) => { var targetFile = $"{targetPath}\\{file}.m2ts"; @@ -1544,7 +1544,7 @@ private void InsertIfo() combineMenuStrip.Items.Add(new ToolStripSeparator()); var fileLine = comboBox2.Text; var file = fileLine.Substring(0, fileLine.LastIndexOf('_') - 1) + ".VOB"; - ToolStripMenuItem fMenuItem = new ToolStripMenuItem(string.Format(Resources.Menu_Open_File, file)); + var fMenuItem = new ToolStripMenuItem(string.Format(Resources.Menu_Open_File, file)); fMenuItem.Click += (sender, args) => { var targetFile = Path.GetDirectoryName(FilePath) + $"\\{file}"; @@ -1562,7 +1562,7 @@ private void InsertXpl() combineMenuStrip.Items.Add(new ToolStripSeparator()); var file = Path.GetFileName(_info.SourceName); - ToolStripMenuItem fMenuItem = new ToolStripMenuItem(string.Format(Resources.Menu_Open_File, file)); + var fMenuItem = new ToolStripMenuItem(string.Format(Resources.Menu_Open_File, file)); fMenuItem.Click += (sender, args) => { var targetFile = $"{targetPath}\\{file}"; @@ -1597,7 +1597,7 @@ private void creatZonesToolStripMenuItem_Click(object sender, EventArgs e) foreach (DataGridViewRow row in dataGridView1.SelectedRows) { var rowIndex = dataGridView1.Rows.IndexOf(row); - int nextRowIndex = rowIndex + 1; + var nextRowIndex = rowIndex + 1; //todo: make last time stamp use the length of clip info. if (rowIndex >= dataGridView1.RowCount - 1) { @@ -1610,8 +1610,8 @@ private void creatZonesToolStripMenuItem_Click(object sender, EventArgs e) var endFrames = int.Parse(nextRow.Substring(0, nextRow.IndexOf(' '))); zoneRange.Add(new KeyValuePair<int, int>(beginFrames, endFrames - 1)); } - string zones = zoneRange.OrderBy(item => item.Key).Aggregate(string.Empty, (current, zone) => current + $"/{zone.Key},{zone.Value},"); - string ret = "--zones " + zones.TrimStart('/'); + var zones = zoneRange.OrderBy(item => item.Key).Aggregate(string.Empty, (current, zone) => current + $"/{zone.Key},{zone.Value},"); + var ret = "--zones " + zones.TrimStart('/'); var result = Notification.ShowInfo($"{ret}\n{Resources.Zones_Copy_To_Clip_Board}"); if (result == DialogResult.Yes) { @@ -1632,8 +1632,8 @@ private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEvent private void InsertSplitToolStripMenuItem_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count != 1) return; - DataGridViewRow row = dataGridView1.SelectedRows[0]; - Chapter split = new Chapter("Split line", TimeSpan.MinValue, -1); + var row = dataGridView1.SelectedRows[0]; + var split = new Chapter("Split line", TimeSpan.MinValue, -1); _info.Chapters.Insert(row.Index, split); _splitRowInsrted = true; UpdataGridView(); diff --git a/Time_Shift/Forms/FormAbout.cs b/Time_Shift/Forms/FormAbout.cs index b675804..d22b7ad 100644 --- a/Time_Shift/Forms/FormAbout.cs +++ b/Time_Shift/Forms/FormAbout.cs @@ -49,7 +49,7 @@ private static string AssemblyProduct { get { - object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); + var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); return attributes.Length == 0 ? string.Empty : ((AssemblyProductAttribute)attributes[0]).Product; } } @@ -96,7 +96,7 @@ private void Form2_MouseDown(object sender, MouseEventArgs e) private void Form2_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; - Point mousePos = MousePosition; + var mousePos = MousePosition; mousePos.Offset(_startPoint.X, _startPoint.Y); Location = mousePos; } diff --git a/Time_Shift/Knuckleball/Chapter.cs b/Time_Shift/Knuckleball/Chapter.cs index fc14e37..2e8c668 100644 --- a/Time_Shift/Knuckleball/Chapter.cs +++ b/Time_Shift/Knuckleball/Chapter.cs @@ -101,7 +101,7 @@ public override int GetHashCode() /// is the same as this instance; otherwise, <see langword="false"/>.</returns> public override bool Equals(object obj) { - Chapter other = obj as Chapter; + var other = obj as Chapter; if (other == null) { return false; diff --git a/Time_Shift/Knuckleball/ChapterList.cs b/Time_Shift/Knuckleball/ChapterList.cs index 51b92da..180e169 100644 --- a/Time_Shift/Knuckleball/ChapterList.cs +++ b/Time_Shift/Knuckleball/ChapterList.cs @@ -203,7 +203,7 @@ public void Insert(int index, Chapter item) /// <see langword="false"/> if <paramref name="item"/> is not found in the original<see cref="ChapterList"/>.</returns> public bool Remove(Chapter item) { - bool isRemoved = chapters.Remove(item); + var isRemoved = chapters.Remove(item); IsDirty = IsDirty || isRemoved; if (isRemoved) { @@ -221,7 +221,7 @@ public bool Remove(Chapter item) /// or <paramref name="index"/> is greater than <see cref="Count"/>.</exception> public void RemoveAt(int index) { - Chapter toRemove = this[index]; + var toRemove = this[index]; hashedIndex.Remove(toRemove.Id); toRemove.Changed -= OnChapterChanged; chapters.RemoveAt(index); @@ -256,19 +256,19 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() /// about the chapters for the file.</returns> internal static ChapterList ReadFromFile(IntPtr fileHandle) { - ChapterList list = new ChapterList(); - IntPtr chapterListPointer = IntPtr.Zero; - int chapterCount = 0; - NativeMethods.MP4ChapterType chapterType = NativeMethods.MP4GetChapters(fileHandle, ref chapterListPointer, ref chapterCount, NativeMethods.MP4ChapterType.Any); + var list = new ChapterList(); + var chapterListPointer = IntPtr.Zero; + var chapterCount = 0; + var chapterType = NativeMethods.MP4GetChapters(fileHandle, ref chapterListPointer, ref chapterCount, NativeMethods.MP4ChapterType.Any); OnLog?.Invoke($"Chapter type: {chapterType}"); if (chapterType != NativeMethods.MP4ChapterType.None && chapterCount != 0) { - IntPtr currentChapterPointer = chapterListPointer; - for (int i = 0; i < chapterCount; ++i) + var currentChapterPointer = chapterListPointer; + for (var i = 0; i < chapterCount; ++i) { - NativeMethods.MP4Chapter currentChapter = currentChapterPointer.ReadStructure<NativeMethods.MP4Chapter>(); - TimeSpan duration = TimeSpan.FromMilliseconds(currentChapter.duration); - string title = GetString(currentChapter.title); + var currentChapter = currentChapterPointer.ReadStructure<NativeMethods.MP4Chapter>(); + var duration = TimeSpan.FromMilliseconds(currentChapter.duration); + var title = GetString(currentChapter.title); OnLog?.Invoke($"{title} {duration}"); list.AddInternal(new Chapter { Duration = duration, Title = title }); currentChapterPointer = IntPtr.Add(currentChapterPointer, Marshal.SizeOf(currentChapter)); @@ -295,7 +295,7 @@ internal static ChapterList ReadFromFile(IntPtr fileHandle) /// <returns></returns> private static string GetString(byte[] bytes) { - string title = Encoding.UTF8.GetString(bytes); + var title = Encoding.UTF8.GetString(bytes); if (bytes[0] == 0xFF && bytes[1] == 0xFE) { title = Encoding.Unicode.GetString(bytes); diff --git a/Time_Shift/Knuckleball/IntPtrExtensions.cs b/Time_Shift/Knuckleball/IntPtrExtensions.cs index bdd79ca..5861cfc 100644 --- a/Time_Shift/Knuckleball/IntPtrExtensions.cs +++ b/Time_Shift/Knuckleball/IntPtrExtensions.cs @@ -141,7 +141,7 @@ public static T ReadEnumValue<T>(this IntPtr value, T defaultValue) } object rawValue; - Type underlyingType = Enum.GetUnderlyingType(typeof(T)); + var underlyingType = Enum.GetUnderlyingType(typeof(T)); if (underlyingType == typeof(byte)) { rawValue = ReadByte(value).Value; @@ -198,7 +198,7 @@ public static byte[] ReadBuffer(this IntPtr value, int bufferLength) return null; } - byte[] buffer = new byte[bufferLength]; + var buffer = new byte[bufferLength]; Marshal.Copy(value, buffer, 0, bufferLength); return buffer; } diff --git a/Time_Shift/Knuckleball/MP4File.cs b/Time_Shift/Knuckleball/MP4File.cs index 56630a3..30adab1 100644 --- a/Time_Shift/Knuckleball/MP4File.cs +++ b/Time_Shift/Knuckleball/MP4File.cs @@ -61,7 +61,7 @@ private MP4File(string fileName) /// </exception> public static MP4File Open(string fileName) { - MP4File file = new MP4File(fileName); + var file = new MP4File(fileName); file.Load(); return file; } @@ -71,7 +71,7 @@ public static MP4File Open(string fileName) /// </summary> public void Load() { - IntPtr fileHandle = NativeMethods.MP4Read(fileName); + var fileHandle = NativeMethods.MP4Read(fileName); if (fileHandle != IntPtr.Zero) { try diff --git a/Time_Shift/Program.cs b/Time_Shift/Program.cs index a1482af..03beb29 100644 --- a/Time_Shift/Program.cs +++ b/Time_Shift/Program.cs @@ -28,7 +28,7 @@ static void Main(string[] args) } else { - string argsFull = string.Join(" ", args.SkipWhile(item => item.StartsWith("--"))); + var argsFull = string.Join(" ", args.SkipWhile(item => item.StartsWith("--"))); Application.Run(new Forms.Form1(argsFull)); } } diff --git a/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs b/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs index 940fb53..9a18576 100644 --- a/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs +++ b/Time_Shift/SharpDvdInfo/DvdInfoContainer.cs @@ -54,11 +54,11 @@ public DvdInfoContainer(string path) if (File.Exists(path)) { _path = Directory.GetParent(path).FullName; - Regex rTitle = new Regex(@"VTS_(\d{2})_0.IFO"); + var rTitle = new Regex(@"VTS_(\d{2})_0.IFO"); var result = rTitle.Match(path); if (!result.Success) throw new Exception("Invalid file"); - byte titleSetNumber = byte.Parse(result.Groups[1].Value); + var titleSetNumber = byte.Parse(result.Groups[1].Value); var list = new TitleInfo { TitleNumber = titleSetNumber, @@ -95,7 +95,7 @@ private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) item.Chapters = new List<TimeSpan>(); var buffer = new byte[192]; - using (FileStream fs = File.OpenRead(Path.Combine(_path, $"VTS_{titleSetNumber:00}_0.IFO"))) + using (var fs = File.OpenRead(Path.Combine(_path, $"VTS_{titleSetNumber:00}_0.IFO"))) { fs.Seek(0x00C8, SeekOrigin.Begin); fs.Read(buffer, 0, 4); @@ -125,13 +125,13 @@ private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) ((int)item.VideoStream.VideoStandard * 8); fs.Read(buffer, 0, 2); - int numAudio = GetBits(buffer, 16, 0); - for (int audioNum = 0; audioNum < numAudio; audioNum++) + var numAudio = GetBits(buffer, 16, 0); + for (var audioNum = 0; audioNum < numAudio; audioNum++) { fs.Read(buffer, 0, 8); - int langMode = GetBits(buffer, 2, 2); - int codingMode = GetBits(buffer, 3, 5); - AudioProperties audioStream = new AudioProperties + var langMode = GetBits(buffer, 2, 2); + var codingMode = GetBits(buffer, 3, 5); + var audioStream = new AudioProperties { CodingMode = (DvdAudioFormat) codingMode, Channels = GetBits(buffer, 3, 8) + 1, @@ -143,8 +143,8 @@ private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) if (langMode == 1) { - char langChar1 = (char) GetBits(buffer, 8, 16); - char langChar2 = (char) GetBits(buffer, 8, 24); + var langChar1 = (char) GetBits(buffer, 8, 16); + var langChar2 = (char) GetBits(buffer, 8, 24); audioStream.Language = LanguageSelectionContainer.LookupISOCode($"{langChar1}{langChar2}"); } @@ -158,12 +158,12 @@ private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) fs.Seek(0x0254, SeekOrigin.Begin); fs.Read(buffer, 0, 2); - int numSubs = GetBits(buffer, 16, 0); - for (int subNum = 0; subNum < numSubs; subNum++) + var numSubs = GetBits(buffer, 16, 0); + for (var subNum = 0; subNum < numSubs; subNum++) { fs.Read(buffer, 0, 6); - int langMode = GetBits(buffer, 2, 0); - SubpictureProperties sub = new SubpictureProperties + var langMode = GetBits(buffer, 2, 0); + var sub = new SubpictureProperties { Format = (DvdSubpictureFormat) GetBits(buffer, 3, 5), StreamId = 0x20 + subNum, @@ -172,10 +172,10 @@ private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) if (langMode == 1) { - char langChar1 = (char)GetBits(buffer, 8, 16); - char langChar2 = (char)GetBits(buffer, 8, 24); + var langChar1 = (char)GetBits(buffer, 8, 16); + var langChar2 = (char)GetBits(buffer, 8, 24); - string langCode = langChar1.ToString(CultureInfo.InvariantCulture) + + var langCode = langChar1.ToString(CultureInfo.InvariantCulture) + langChar2.ToString(CultureInfo.InvariantCulture); sub.Language = LanguageSelectionContainer.LookupISOCode(langCode); @@ -190,43 +190,43 @@ private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) fs.Seek(0xCC, SeekOrigin.Begin); fs.Read(buffer, 0, 4); - int pgciSector = GetBits(buffer, 32, 0); - int pgciAdress = pgciSector * SectorLength; + var pgciSector = GetBits(buffer, 32, 0); + var pgciAdress = pgciSector * SectorLength; fs.Seek(pgciAdress, SeekOrigin.Begin); fs.Read(buffer, 0, 8); fs.Seek(8 * (item.TitleNumberInSet - 1), SeekOrigin.Current); fs.Read(buffer, 0, 8); - int offsetPgc = GetBits(buffer, 32, 32); + var offsetPgc = GetBits(buffer, 32, 32); fs.Seek(pgciAdress + offsetPgc + 2, SeekOrigin.Begin); fs.Read(buffer, 0, 6); - int numCells = GetBits(buffer, 8, 8); + var numCells = GetBits(buffer, 8, 8); - int hour = GetBits(buffer, 8, 16); - int minute = GetBits(buffer, 8, 24); - int second = GetBits(buffer, 8, 32); - int msec = GetBits(buffer, 8, 40); + var hour = GetBits(buffer, 8, 16); + var minute = GetBits(buffer, 8, 24); + var second = GetBits(buffer, 8, 32); + var msec = GetBits(buffer, 8, 40); item.VideoStream.Runtime = DvdTime2TimeSpan(hour, minute, second, msec); fs.Seek(224, SeekOrigin.Current); fs.Read(buffer, 0, 2); - int cellmapOffset = GetBits(buffer, 16, 0); + var cellmapOffset = GetBits(buffer, 16, 0); fs.Seek(pgciAdress + cellmapOffset + offsetPgc, SeekOrigin.Begin); - TimeSpan chapter = new TimeSpan(); + var chapter = new TimeSpan(); item.Chapters.Add(chapter); - for (int i = 0; i < numCells; i++) + for (var i = 0; i < numCells; i++) { fs.Read(buffer, 0, 24); - int chapHour = GetBits(buffer, 8, 4*8); - int chapMinute = GetBits(buffer, 8, 5*8); - int chapSecond = GetBits(buffer, 8, 6*8); - int chapMsec = GetBits(buffer, 8, 7*8); + var chapHour = GetBits(buffer, 8, 4*8); + var chapMinute = GetBits(buffer, 8, 5*8); + var chapSecond = GetBits(buffer, 8, 6*8); + var chapMsec = GetBits(buffer, 8, 7*8); chapter = chapter.Add(DvdTime2TimeSpan(chapHour, chapMinute, chapSecond, chapMsec)); item.Chapters.Add(chapter); @@ -239,8 +239,8 @@ private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) /// </summary> private void GetVmgmInfo() { - byte[] buffer = new byte[12]; - using (FileStream fs = File.OpenRead(Path.Combine(_path, "VIDEO_TS.IFO"))) + var buffer = new byte[12]; + using (var fs = File.OpenRead(Path.Combine(_path, "VIDEO_TS.IFO"))) { fs.Seek(0x20, SeekOrigin.Begin); fs.Read(buffer, 0, 2); @@ -253,12 +253,12 @@ private void GetVmgmInfo() fs.Seek(0xC4, SeekOrigin.Begin); fs.Read(buffer, 0, 4); - int sector = GetBits(buffer, 32, 0); + var sector = GetBits(buffer, 32, 0); fs.Seek(sector * SectorLength, SeekOrigin.Begin); fs.Read(buffer, 0, 8); Vmgm.NumTitles = GetBits(buffer, 16, 0); - for (int i = 0; i < Vmgm.NumTitles; i++) + for (var i = 0; i < Vmgm.NumTitles; i++) { fs.Read(buffer, 0, 12); var info = new TitleInfo @@ -310,12 +310,12 @@ public List<ChapterInfo> GetChapterInfo() /// <returns>resulting <see cref="int"/></returns> public static int GetBits(byte[] buffer, byte length, byte start) { - int result = 0; + var result = 0; //read bytes from left to right and every bit in byte from low to high - BitArray ba = new BitArray(buffer); + var ba = new BitArray(buffer); short j = 0; - int tempResult = 0; + var tempResult = 0; for (int i = start; i < start + length; i++) { if (ba.Get(i)) @@ -342,7 +342,7 @@ public static int GetBits_Effi(byte[] buffer, byte length, byte start) long temp = 0; long mask = 0xffffffffu >> (32 - length); // [b1] {s} [b2] {s+l} [b3] - for (int i = 0; i < Math.Ceiling((start + length) / 8.0); ++i) + for (var i = 0; i < Math.Ceiling((start + length) / 8.0); ++i) { temp |= (uint)buffer[i] << (24 - i*8); } @@ -359,9 +359,9 @@ public static int GetBits_Effi(byte[] buffer, byte length, byte start) /// <returns>Converted time in milliseconds</returns> private static TimeSpan DvdTime2TimeSpan(int hours, int minutes, int seconds, int milliseconds) { - int fpsMask = milliseconds >> 6; + var fpsMask = milliseconds >> 6; milliseconds &= 0x3f; - double fps = fpsMask == 0x01 ? 25D : fpsMask == 0x03 ? (30D / 1.001D) : 0; + var fps = fpsMask == 0x01 ? 25D : fpsMask == 0x03 ? (30D / 1.001D) : 0; hours = BcdToInt(hours); minutes = BcdToInt(minutes); seconds = BcdToInt(seconds); diff --git a/Time_Shift/Util/ChapterData/BDMVData.cs b/Time_Shift/Util/ChapterData/BDMVData.cs index 56c4ea8..502a750 100644 --- a/Time_Shift/Util/ChapterData/BDMVData.cs +++ b/Time_Shift/Util/ChapterData/BDMVData.cs @@ -15,9 +15,9 @@ public static class BDMVData public static async Task<KeyValuePair<string, List<ChapterInfo>>> GetChapterAsync(string location) { - var list = new List<ChapterInfo>(); - string bdmvTitle = null; - string path = Path.Combine(location, "BDMV", "PLAYLIST"); + var list = new List<ChapterInfo>(); + var bdmvTitle = string.Empty; + var path = Path.Combine(location, "BDMV", "PLAYLIST"); if (!Directory.Exists(path)) { throw new FileNotFoundException("Blu-Ray disc structure not found."); @@ -48,7 +48,7 @@ public static async Task<KeyValuePair<string, List<ChapterInfo>>> GetChapterAsyn } var workingPath = Directory.GetParent(location).FullName; location = location.Substring(location.LastIndexOf('\\') + 1); - string text = (await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\"", workingPath)).ToString(); + var text = (await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\"", workingPath)).ToString(); if (text.Contains("HD DVD / Blu-Ray disc structure not found.")) { OnLog?.Invoke(text); @@ -76,7 +76,7 @@ public static async Task<KeyValuePair<string, List<ChapterInfo>>> GetChapterAsyn var toBeRemove = new List<ChapterInfo>(); var chapterPath = Path.Combine(workingPath, "chapters.txt"); var logPath = Path.Combine(workingPath, "chapters - Log.txt"); - foreach (ChapterInfo current in list) + foreach (var current in list) { text = (await TaskAsync.RunProcessAsync(eac3toPath, $"\"{location}\" {current.SourceIndex})", workingPath)).ToString(); if (!text.Contains("Chapters")) diff --git a/Time_Shift/Util/ChapterData/CueData.cs b/Time_Shift/Util/ChapterData/CueData.cs index d1aa38d..93a32a6 100644 --- a/Time_Shift/Util/ChapterData/CueData.cs +++ b/Time_Shift/Util/ChapterData/CueData.cs @@ -44,7 +44,7 @@ public CueData(string path, Action<string> log = null) switch (ext) { case ".cue": - cueData = File.ReadAllBytes(path).GetUTF8String(); + cueData = File.ReadAllBytes(path).GetUTFString(); if (string.IsNullOrEmpty(cueData)) throw new InvalidDataException("Empty cue file"); break; @@ -89,7 +89,7 @@ public static ChapterInfo PraseCue(string context) { var lines = context.Split('\n'); var cue = new ChapterInfo {SourceType = "CUE", Tag = context, TagType = context.GetType()}; - NextState nxState = NextState.NsStart; + var nxState = NextState.NsStart; Chapter chapter = null; foreach (var line in lines) @@ -201,10 +201,10 @@ private static string GetCueSheet(byte[] buffer, string type) { throw new ArgumentException($"Invalid parameter: [{nameof(type)}], which must be 'flac' or 'tak'"); } - int length = buffer.Length; + var length = buffer.Length; //查找 Cuesheet 标记,自动机模型,大小写不敏感 int state = 0, beginPos = 0; - for (int i = 0; i < length; ++i) + for (var i = 0; i < length; ++i) { if (buffer[i] >= 'A' && buffer[i] <= 'Z') buffer[i] = (byte)(buffer[i] - 'A' + 'a'); @@ -231,11 +231,11 @@ private static string GetCueSheet(byte[] buffer, string type) beginPos = i + 2; break; } - int controlCount = type == "flac" ? 3 : type == "tak" ? 6 : 0; - int endPos = 0; + var controlCount = type == "flac" ? 3 : type == "tak" ? 6 : 0; + var endPos = 0; state = 0; //查找终止符 0D 0A ? 00 00 00 (连续 controlCount 个终止符以上) (flac为3, tak为6) - for (int i = beginPos; i < length; ++i) + for (var i = beginPos; i < length; ++i) { switch (buffer[i]) { @@ -253,7 +253,7 @@ private static string GetCueSheet(byte[] buffer, string type) var cueLength = endPos - beginPos + 1; if (cueLength <= 10) return string.Empty; - string cueSheet = Encoding.UTF8.GetString(buffer, beginPos, cueLength); + var cueSheet = Encoding.UTF8.GetString(buffer, beginPos, cueLength); //Debug.WriteLine(cueSheet); return cueSheet; diff --git a/Time_Shift/Util/ChapterData/FlacData.cs b/Time_Shift/Util/ChapterData/FlacData.cs index 7f714e9..67c09e7 100644 --- a/Time_Shift/Util/ChapterData/FlacData.cs +++ b/Time_Shift/Util/ChapterData/FlacData.cs @@ -140,7 +140,7 @@ private static void ParseVorbisComment(Stream fs, ref FlacInfo info) info.Encoder = vendor; OnLog?.Invoke($" | Vendor: {vendor}"); var userCommentListLength = fs.LEInt32(); - for (int i = 0; i < userCommentListLength; ++i) + for (var i = 0; i < userCommentListLength; ++i) { var commentLength = (int) fs.LEInt32(); var commentRawStringData = fs.ReadBytes(commentLength); @@ -264,7 +264,7 @@ public bool GetBit() { if (_bytePosition >= _buffer.Length) throw new IndexOutOfRangeException(nameof(_bytePosition)); - bool ret = ((_buffer[_bytePosition] >> (7 - _bitPositionInByte)) & 1) == 1; + var ret = ((_buffer[_bytePosition] >> (7 - _bitPositionInByte)) & 1) == 1; Next(); return ret; } @@ -279,7 +279,7 @@ private void Next() public void Skip(int length) { - for (int i = 0; i < length; ++i) + for (var i = 0; i < length; ++i) { Next(); } @@ -288,7 +288,7 @@ public void Skip(int length) public long GetBits(int length) { long ret = 0; - for (int i = 0; i < length; ++i) + for (var i = 0; i < length; ++i) { ret |= ((long) (_buffer[_bytePosition] >> (7 - _bitPositionInByte)) & 1) << (length - 1 - i); Next(); diff --git a/Time_Shift/Util/ChapterData/IfoData.cs b/Time_Shift/Util/ChapterData/IfoData.cs index fd349f4..b0da14e 100644 --- a/Time_Shift/Util/ChapterData/IfoData.cs +++ b/Time_Shift/Util/ChapterData/IfoData.cs @@ -31,8 +31,8 @@ public static class IfoData { public static IEnumerable<ChapterInfo> GetStreams(string ifoFile) { - int pgcCount = IfoParser.GetPGCnb(ifoFile); - for (int i = 1; i <= pgcCount; i++) + var pgcCount = IfoParser.GetPGCnb(ifoFile); + for (var i = 1; i <= pgcCount; i++) { yield return GetChapterInfo(ifoFile, i); } @@ -40,11 +40,11 @@ public static IEnumerable<ChapterInfo> GetStreams(string ifoFile) private static ChapterInfo GetChapterInfo(string location, int titleSetNum) { - Regex titleRegex = new Regex(@"^VTS_(\d+)_0\.IFO", RegexOptions.IgnoreCase | RegexOptions.Compiled); + var titleRegex = new Regex(@"^VTS_(\d+)_0\.IFO", RegexOptions.IgnoreCase | RegexOptions.Compiled); var result = titleRegex.Match(location); if (result.Success) titleSetNum = int.Parse(result.Groups[1].Value); - ChapterInfo pgc = new ChapterInfo + var pgc = new ChapterInfo { SourceType = "DVD", }; @@ -52,7 +52,7 @@ private static ChapterInfo GetChapterInfo(string location, int titleSetNum) Debug.Assert(fileName != null); if (fileName.Count(ch => ch == '_') == 2) { - int barIndex = fileName.LastIndexOf('_'); + var barIndex = fileName.LastIndexOf('_'); pgc.Title = pgc.SourceName = $"{fileName.Substring(0, barIndex)}_{titleSetNum}"; } @@ -72,25 +72,25 @@ private static List<Chapter> GetChapters(string ifoFile, int programChain, out T duration = TimeSpan.Zero; fps = 0; - FileStream stream = new FileStream(ifoFile, FileMode.Open, FileAccess.Read, FileShare.Read); + var stream = new FileStream(ifoFile, FileMode.Open, FileAccess.Read, FileShare.Read); - long pcgItPosition = stream.GetPCGIP_Position(); - int programChainPrograms = -1; - TimeSpan programTime = TimeSpan.Zero; + var pcgItPosition = stream.GetPCGIP_Position(); + var programChainPrograms = -1; + var programTime = TimeSpan.Zero; double fpsLocal; if (programChain >= 0) { - uint chainOffset = stream.GetChainOffset(pcgItPosition, programChain); + var chainOffset = stream.GetChainOffset(pcgItPosition, programChain); programTime = stream.ReadTimeSpan(pcgItPosition, chainOffset, out fpsLocal) ?? TimeSpan.Zero; programChainPrograms = stream.GetNumberOfPrograms(pcgItPosition, chainOffset); } else { - int programChains = stream.GetProgramChains(pcgItPosition); - for (int curChain = 1; curChain <= programChains; curChain++) + var programChains = stream.GetProgramChains(pcgItPosition); + for (var curChain = 1; curChain <= programChains; curChain++) { - uint chainOffset = stream.GetChainOffset(pcgItPosition, curChain); - TimeSpan? time = stream.ReadTimeSpan(pcgItPosition, chainOffset, out fpsLocal); + var chainOffset = stream.GetChainOffset(pcgItPosition, curChain); + var time = stream.ReadTimeSpan(pcgItPosition, chainOffset, out fpsLocal); if (time == null) break; if (time.Value <= programTime) continue; @@ -103,26 +103,26 @@ private static List<Chapter> GetChapters(string ifoFile, int programChain, out T chapters.Add(new Chapter { Name = "Chapter 01" ,Time = TimeSpan.Zero}); - uint longestChainOffset = stream.GetChainOffset(pcgItPosition, programChain); - int programMapOffset = IfoParser.ToInt16(stream.GetFileBlock((pcgItPosition + longestChainOffset) + 230, 2)); - int cellTableOffset = IfoParser.ToInt16(stream.GetFileBlock((pcgItPosition + longestChainOffset) + 0xE8, 2)); - for (int currentProgram = 0; currentProgram < programChainPrograms; ++currentProgram) + var longestChainOffset = stream.GetChainOffset(pcgItPosition, programChain); + int programMapOffset = IfoParser.ToInt16(stream.GetFileBlock((pcgItPosition + longestChainOffset) + 230, 2)); + int cellTableOffset = IfoParser.ToInt16(stream.GetFileBlock((pcgItPosition + longestChainOffset) + 0xE8, 2)); + for (var currentProgram = 0; currentProgram < programChainPrograms; ++currentProgram) { - int entryCell = stream.GetFileBlock(((pcgItPosition + longestChainOffset) + programMapOffset) + currentProgram, 1)[0]; - int exitCell = entryCell; + int entryCell = stream.GetFileBlock(((pcgItPosition + longestChainOffset) + programMapOffset) + currentProgram, 1)[0]; + var exitCell = entryCell; if (currentProgram < (programChainPrograms - 1)) - exitCell = stream.GetFileBlock(((pcgItPosition + longestChainOffset) + programMapOffset) + (currentProgram + 1), 1)[0] - 1; + exitCell = stream.GetFileBlock(((pcgItPosition + longestChainOffset) + programMapOffset) + (currentProgram + 1), 1)[0] - 1; - TimeSpan totalTime = TimeSpan.Zero; - for (int currentCell = entryCell; currentCell <= exitCell; currentCell++) + var totalTime = TimeSpan.Zero; + for (var currentCell = entryCell; currentCell <= exitCell; currentCell++) { - int cellStart = cellTableOffset + ((currentCell - 1) * 0x18); - byte[] bytes = stream.GetFileBlock((pcgItPosition + longestChainOffset) + cellStart, 4); - int cellType = bytes[0] >> 6; + var cellStart = cellTableOffset + ((currentCell - 1) * 0x18); + var bytes = stream.GetFileBlock((pcgItPosition + longestChainOffset) + cellStart, 4); + var cellType = bytes[0] >> 6; if (cellType == 0x00 || cellType == 0x01) { bytes = stream.GetFileBlock(((pcgItPosition + longestChainOffset) + cellStart) + 4, 4); - TimeSpan time = IfoParser.ReadTimeSpan(bytes, out fps) ?? TimeSpan.Zero; + var time = IfoParser.ReadTimeSpan(bytes, out fps) ?? TimeSpan.Zero; totalTime += time; } } diff --git a/Time_Shift/Util/ChapterData/IfoParser.cs b/Time_Shift/Util/ChapterData/IfoParser.cs index 7374a3f..755b5e4 100644 --- a/Time_Shift/Util/ChapterData/IfoParser.cs +++ b/Time_Shift/Util/ChapterData/IfoParser.cs @@ -78,15 +78,15 @@ internal static int GetNumberOfPrograms(this FileStream ifoStream, long pcgitPos internal static TimeSpan? ReadTimeSpan(byte[] playbackBytes, out double fps) { var frames = GetFrames(playbackBytes[3]); - int fpsMask = playbackBytes[3] >> 6; + var fpsMask = playbackBytes[3] >> 6; fps = fpsMask == 0x01 ? 25D : fpsMask == 0x03 ? (30D / 1.001D) : 0; if (frames == null) return null; try { - int hours = BcdToInt(playbackBytes[0]); - int minutes = BcdToInt(playbackBytes[1]); - int seconds = BcdToInt(playbackBytes[2]); - TimeSpan ret = new TimeSpan(hours, minutes, seconds); + var hours = BcdToInt(playbackBytes[0]); + var minutes = BcdToInt(playbackBytes[1]); + var seconds = BcdToInt(playbackBytes[2]); + var ret = new TimeSpan(hours, minutes, seconds); if (Math.Abs(fps) > 1e-5) ret += TimeSpan.FromSeconds((double)frames/fps); return ret; @@ -101,11 +101,11 @@ internal static int GetNumberOfPrograms(this FileStream ifoStream, long pcgitPos /// <returns>number of PGS as an integer</returns> public static int GetPGCnb(string fileName) { - FileStream ifoStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); - uint offset = ToInt32(GetFileBlock(ifoStream, 0xCC, 4)); // Read PGC offset + var ifoStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); + var offset = ToInt32(GetFileBlock(ifoStream, 0xCC, 4)); // Read PGC offset ifoStream.Seek(2048 * offset + 0x01, SeekOrigin.Begin); // Move to beginning of PGC //long VTS_PGCITI_start_position = ifoStream.Position - 1; - int nPGCs = ifoStream.ReadByte(); // Number of PGCs + var nPGCs = ifoStream.ReadByte(); // Number of PGCs ifoStream.Close(); return nPGCs; } diff --git a/Time_Shift/Util/ChapterData/Mp4Data.cs b/Time_Shift/Util/ChapterData/Mp4Data.cs index 2c2033d..e715d4f 100644 --- a/Time_Shift/Util/ChapterData/Mp4Data.cs +++ b/Time_Shift/Util/ChapterData/Mp4Data.cs @@ -28,10 +28,10 @@ public class Mp4Data public Mp4Data(string path) { - MP4File file = MP4File.Open(path); + var file = MP4File.Open(path); if (file.Chapters == null) return; Chapter = new ChapterInfo(); - int index = 0; + var index = 0; foreach (var chapterClip in file.Chapters) { Chapter.Chapters.Add(new Chapter(chapterClip.Title, Chapter.Duration, ++index)); diff --git a/Time_Shift/Util/ChapterData/MplsData.cs b/Time_Shift/Util/ChapterData/MplsData.cs index 89a87a1..fb1012f 100644 --- a/Time_Shift/Util/ChapterData/MplsData.cs +++ b/Time_Shift/Util/ChapterData/MplsData.cs @@ -55,7 +55,7 @@ private void ParseMpls() { ParsePlayItem(playItemEntries, out int lengthOfPlayItem, out int itemStartAdress, out int streamCount); - for (int streamOrder = 0; streamOrder < streamCount; streamOrder++) + for (var streamOrder = 0; streamOrder < streamCount; streamOrder++) { ParseStream(itemStartAdress, streamOrder, playItemOrder); } @@ -68,12 +68,12 @@ private void ParseMpls() private void ParseHeader(out int playlistMarkSectionStartAddress, out int playItemNumber, out int playItemEntries) { - string fileType = Encoding.ASCII.GetString(_data, 0, 8); + var fileType = Encoding.ASCII.GetString(_data, 0, 8); if ((fileType != "MPLS0100" && fileType != "MPLS0200") /*|| _data[45] != 1*/) { throw new Exception($"This Playlist has an unknown file type {fileType}."); } - int playlistSectionStartAddress = Byte2Int32(_data, 0x08); + var playlistSectionStartAddress = Byte2Int32(_data, 0x08); playlistMarkSectionStartAddress = Byte2Int32(_data, 0x0c); playItemNumber = Byte2Int16(_data, playlistSectionStartAddress + 0x06); playItemEntries = playlistSectionStartAddress + 0x0a; @@ -81,11 +81,11 @@ private void ParseHeader(out int playlistMarkSectionStartAddress, out int playIt private bool ParsePlayItem(int playItemEntries, out int lengthOfPlayItem, out int itemStartAdress, out int streamCount) { - bool mulitAngle = false; + var mulitAngle = false; lengthOfPlayItem = Byte2Int16(_data, playItemEntries); var bytes = new byte[lengthOfPlayItem + 2]; Array.Copy(_data, playItemEntries, bytes, 0, lengthOfPlayItem + 2); - Clip streamClip = new Clip + var streamClip = new Clip { TimeIn = Byte2Int32(bytes, 0x0e), TimeOut = Byte2Int32(bytes, 0x12) @@ -96,15 +96,15 @@ private bool ParsePlayItem(int playItemEntries, out int lengthOfPlayItem, out in itemStartAdress = playItemEntries + 0x32; streamCount = bytes[0x23] >> 4; - int isMultiAngle = (bytes[0x0c] >> 4) & 0x01; - StringBuilder nameBuilder = new StringBuilder(Encoding.ASCII.GetString(bytes, 0x02, 0x05)); + var isMultiAngle = (bytes[0x0c] >> 4) & 0x01; + var nameBuilder = new StringBuilder(Encoding.ASCII.GetString(bytes, 0x02, 0x05)); //todo: fps info of multi-angle has been skiped too. if (isMultiAngle == 1) //skip multi-angle { mulitAngle = true; int numberOfAngles = bytes[0x22]; - for (int i = 1; i < numberOfAngles; i++) + for (var i = 1; i < numberOfAngles; i++) { nameBuilder.Append("&" + Encoding.ASCII.GetString(bytes, 0x24 + (i - 1) * 0x0a, 0x05)); } @@ -141,7 +141,7 @@ private void ParseStream(int itemStartAdress, int streamOrder, int playItemOrder private void ParsePlaylistMark(int playlistMarkSectionStartAddress) { int playlistMarkNumber = Byte2Int16(_data, playlistMarkSectionStartAddress + 0x04); - int playlistMarkEntries = playlistMarkSectionStartAddress + 0x06; + var playlistMarkEntries = playlistMarkSectionStartAddress + 0x06; var bytelist = new byte[14]; // eg. 0001 yyyy xxxxxxxx FFFF 000000 // 00 mark_id // 01 mark_type @@ -154,9 +154,9 @@ private void ParsePlaylistMark(int playlistMarkSectionStartAddress) Array.Copy(_data, playlistMarkEntries + mark * 14, bytelist, 0, 14); if (0x01 != bytelist[1]) continue;// make sure the playlist mark type is an entry mark int streamFileIndex = Byte2Int16(bytelist, 0x02); - Clip streamClip = ChapterClips[streamFileIndex]; - int timeStamp = Byte2Int32(bytelist, 0x04); - int relativeSeconds = timeStamp - streamClip.TimeIn + streamClip.RelativeTimeIn; + var streamClip = ChapterClips[streamFileIndex]; + var timeStamp = Byte2Int32(bytelist, 0x04); + var relativeSeconds = timeStamp - streamClip.TimeIn + streamClip.RelativeTimeIn; streamClip.TimeStamp.Add(timeStamp); EntireClip.TimeStamp.Add(relativeSeconds); } @@ -186,9 +186,9 @@ public static TimeSpan Pts2Time(int pts) { throw new ArgumentOutOfRangeException($"InvalidArgument=\"{pts}\"的值对于{nameof(pts)}无效"); } - decimal total = pts / 45000M; - decimal secondPart = Math.Floor(total); - decimal millisecondPart = Math.Round((total - secondPart) * 1000M, MidpointRounding.AwayFromZero); + var total = pts / 45000M; + var secondPart = Math.Floor(total); + var millisecondPart = Math.Round((total - secondPart) * 1000M, MidpointRounding.AwayFromZero); return new TimeSpan(0, 0, 0, (int)secondPart, (int)millisecondPart); } @@ -198,8 +198,8 @@ public ChapterInfo ToChapterInfo(int index, bool combineChapter) { throw new IndexOutOfRangeException("Index of Video Clip out of range"); } - Clip selectedClip = combineChapter ? EntireClip : ChapterClips[index]; - ChapterInfo info = new ChapterInfo + var selectedClip = combineChapter ? EntireClip : ChapterClips[index]; + var info = new ChapterInfo { SourceType = "MPLS", SourceName = selectedClip.Name, @@ -208,7 +208,7 @@ public ChapterInfo ToChapterInfo(int index, bool combineChapter) }; var selectedTimeStamp = selectedClip.TimeStamp; if (selectedTimeStamp.Count < 2) return info; - int offset = selectedTimeStamp.First(); + var offset = selectedTimeStamp.First(); /** * the beginning time stamp of the chapter not always the beginning of the video * eg: Hidan no Aria AA, There are 24 black frames at the begining of each even episode @@ -258,7 +258,7 @@ public static void LogStreamAttributes(byte[] stream, string clipName) if (0x01 != streamCodingType && 0x02 != streamCodingType && 0x1b != streamCodingType && 0xea != streamCodingType) { - int offset = 0x90 == streamCodingType || 0x91 == streamCodingType ? 0x0c : 0x0d; + var offset = 0x90 == streamCodingType || 0x91 == streamCodingType ? 0x0c : 0x0d; if (0x92 == streamCodingType) { OnLog?.Invoke($"Stream[{clipName}] CharacterCode: {CharacterCode[stream[0x0c]]}"); @@ -268,8 +268,8 @@ public static void LogStreamAttributes(byte[] stream, string clipName) OnLog?.Invoke($"Stream[{clipName}] Language: {LanguageSelectionContainer.LookupISOCode(language)}"); if (0x0d == offset) { - int channel = stream[0x0c] >> 4; - int sampleRate = stream[0x0c] & 0x0f; + var channel = stream[0x0c] >> 4; + var sampleRate = stream[0x0c] & 0x0f; OnLog?.Invoke($"Stream[{clipName}] Channel: {Channel[channel]}"); OnLog?.Invoke($"Stream[{clipName}] SampleRate: {SampleRate[sampleRate]}"); } diff --git a/Time_Shift/Util/ChapterData/OgmData.cs b/Time_Shift/Util/ChapterData/OgmData.cs index 682979a..d850ef1 100644 --- a/Time_Shift/Util/ChapterData/OgmData.cs +++ b/Time_Shift/Util/ChapterData/OgmData.cs @@ -27,7 +27,7 @@ namespace ChapterTool.Util.ChapterData public static class OgmData { private static readonly Regex RTimeCodeLine = new Regex(@"^\s*CHAPTER\d+\s*=\s*(.*)", RegexOptions.Compiled); - private static readonly Regex RNameLine = new Regex(@"^\s*CHAPTER\d+NAME\s*=\s*(?<chapterName>.*)", RegexOptions.Compiled); + private static readonly Regex RNameLine = new Regex(@"^\s*CHAPTER\d+NAME\s*=\s*(?<chapterName>.*)", RegexOptions.Compiled); public static event Action<string> OnLog; @@ -41,11 +41,11 @@ private enum LineState public static ChapterInfo GetChapterInfo(string text) { - int index = 0; + var index = 0; var info = new ChapterInfo { SourceType = "OGM", Tag = text, TagType = text.GetType() }; var lines = text.Trim(' ', '\t', '\r', '\n').Split('\n'); - LineState state = LineState.LTimeCode; - TimeSpan timeCode = TimeSpan.Zero, initalTime; + var state = LineState.LTimeCode; + TimeSpan timeCode = TimeSpan.Zero, initalTime; if (RTimeCodeLine.Match(lines.First()).Success) { initalTime = ToolKits.RTimeFormat.Match(lines.First()).Value.ToTimeSpan(); diff --git a/Time_Shift/Util/ChapterData/VTTData.cs b/Time_Shift/Util/ChapterData/VTTData.cs index 2e71e31..c28c241 100644 --- a/Time_Shift/Util/ChapterData/VTTData.cs +++ b/Time_Shift/Util/ChapterData/VTTData.cs @@ -35,7 +35,7 @@ public static ChapterInfo GetChapterInfo(string text) { throw new Exception($"ERROR: Empty or invalid file type"); } - int index = 0; + var index = 0; nodes.Skip(1).ToList().ForEach(node => { var lines = node.Split('\n'); diff --git a/Time_Shift/Util/ChapterData/XmlData.cs b/Time_Shift/Util/ChapterData/XmlData.cs index 2f3826a..0f6a001 100644 --- a/Time_Shift/Util/ChapterData/XmlData.cs +++ b/Time_Shift/Util/ChapterData/XmlData.cs @@ -32,7 +32,7 @@ public static class XmlData { public static IEnumerable<ChapterInfo> PraseXml(XmlDocument doc) { - XmlElement root = doc.DocumentElement; + var root = doc.DocumentElement; if (root == null) { throw new ArgumentException("Empty Xml file"); @@ -49,8 +49,8 @@ public static IEnumerable<ChapterInfo> PraseXml(XmlDocument doc) { throw new Exception($"Invalid Xml file.\nEntry Name: {editionEntry.Name}"); } - ChapterInfo buff = new ChapterInfo { SourceType = "XML", Tag = doc, TagType = doc.GetType() }; - int index = 0; + var buff = new ChapterInfo { SourceType = "XML", Tag = doc, TagType = doc.GetType() }; + var index = 0; foreach (XmlNode editionEntryChildNode in ((XmlElement)editionEntry).ChildNodes)//Get all the child nodes in current chapter { if (editionEntryChildNode.Name != "ChapterAtom") continue; @@ -58,7 +58,7 @@ public static IEnumerable<ChapterInfo> PraseXml(XmlDocument doc) } //remove redundancy chapter node. - for (int i = 0; i < buff.Chapters.Count - 1; i++) + for (var i = 0; i < buff.Chapters.Count - 1; i++) { if (buff.Chapters[i].Time == buff.Chapters[i + 1].Time) { @@ -72,8 +72,8 @@ public static IEnumerable<ChapterInfo> PraseXml(XmlDocument doc) private static IEnumerable<Chapter> PraseChapterAtom(XmlNode chapterAtom, int index) { - Chapter startChapter = new Chapter { Number = index }; - Chapter endChapter = new Chapter { Number = index }; + var startChapter = new Chapter { Number = index }; + var endChapter = new Chapter { Number = index }; var innerChapterAtom = new List<Chapter>(); foreach (XmlNode chapterAtomChildNode in ((XmlElement)chapterAtom).ChildNodes) //Get detail info for current chapter node { @@ -149,7 +149,6 @@ private static IEnumerable<Chapter> ToChapter(ChapterAtom atom, int index) }; yield return startChapter; } - if (atom.SubChapterAtom != null) foreach (var chapterAtom in atom.SubChapterAtom) { diff --git a/Time_Shift/Util/ChapterData/XplData.cs b/Time_Shift/Util/ChapterData/XplData.cs index 3e02086..896d361 100644 --- a/Time_Shift/Util/ChapterData/XplData.cs +++ b/Time_Shift/Util/ChapterData/XplData.cs @@ -10,28 +10,28 @@ public static class XplData { public static IEnumerable<ChapterInfo> GetStreams(string location) { - XDocument doc = XDocument.Load(location); + var doc = XDocument.Load(location); XNamespace ns = "http://www.dvdforum.org/2005/HDDVDVideo/Playlist"; - foreach (XElement ts in doc.Element(ns + "Playlist").Elements(ns + "TitleSet")) + foreach (var ts in doc.Element(ns + "Playlist").Elements(ns + "TitleSet")) { var timeBase = GetFps((string)ts.Attribute("timeBase")) ?? 60; //required var tickBase = GetFps((string)ts.Attribute("tickBase")) ?? 24; //optional - foreach (XElement title in ts.Elements(ns + "Title").Where(t => t.Element(ns + "ChapterList") != null)) + foreach (var title in ts.Elements(ns + "Title").Where(t => t.Element(ns + "ChapterList") != null)) { - ChapterInfo pgc = new ChapterInfo + var pgc = new ChapterInfo { SourceName = title.Element(ns + "PrimaryAudioVideoClip")?.Attribute("src")?.Value ?? "", SourceType = "HD-DVD", FramesPerSecond = 24D, Chapters = new List<Chapter>() }; - int tickBaseDivisor = (int?)title.Attribute("tickBaseDivisor") ?? 1; //optional + var tickBaseDivisor = (int?)title.Attribute("tickBaseDivisor") ?? 1; //optional pgc.Duration = GetTimeSpan((string)title.Attribute("titleDuration"), timeBase, tickBase, tickBaseDivisor); var titleName = Path.GetFileNameWithoutExtension(location); if (title.Attribute("id") != null) titleName = title.Attribute("id")?.Value??""; //optional if (title.Attribute("displayName") != null) titleName = title.Attribute("displayName")?.Value ?? ""; //optional pgc.Title = titleName; - foreach (XElement chapter in title.Element(ns + "ChapterList").Elements(ns + "Chapter")) + foreach (var chapter in title.Element(ns + "ChapterList").Elements(ns + "Chapter")) { var chapterName = string.Empty; if (chapter.Attribute("id") != null) chapterName = chapter.Attribute("id")?.Value ?? ""; //optional @@ -70,12 +70,12 @@ public static IEnumerable<ChapterInfo> GetStreams(string location) private static TimeSpan GetTimeSpan(string timeSpan, double timeBase, double tickBase, int tickBaseDivisor) { var colonPosition = timeSpan.LastIndexOf(':'); - TimeSpan ts = TimeSpan.Parse(timeSpan.Substring(0, colonPosition)); - ts = new TimeSpan((long)(ts.TotalSeconds / 60D * timeBase) * TimeSpan.TicksPerSecond); + var ts = TimeSpan.Parse(timeSpan.Substring(0, colonPosition)); + ts = new TimeSpan((long)(ts.TotalSeconds / 60D * timeBase) * TimeSpan.TicksPerSecond); //convert ticks to ticks timebase - decimal newTick = TimeSpan.TicksPerSecond / ((decimal)tickBase / tickBaseDivisor); - decimal ticks = decimal.Parse(timeSpan.Substring(colonPosition + 1)) * newTick; + var newTick = TimeSpan.TicksPerSecond / ((decimal)tickBase / tickBaseDivisor); + var ticks = decimal.Parse(timeSpan.Substring(colonPosition + 1)) * newTick; return ts.Add(new TimeSpan((long)ticks)); } } diff --git a/Time_Shift/Util/ChapterInfo.cs b/Time_Shift/Util/ChapterInfo.cs index 74c7e90..ec7463f 100644 --- a/Time_Shift/Util/ChapterInfo.cs +++ b/Time_Shift/Util/ChapterInfo.cs @@ -76,7 +76,7 @@ public DataGridViewRow GetRow(int index, bool autoGenName) { row.DefaultCellStyle.BackColor = Color.Black; row.Height = 3; - for (int i = 0; i < 4; ++i) + for (var i = 0; i < 4; ++i) row.Cells.Add(new DataGridViewTextBoxCell {Value = ""}); return row; } @@ -146,15 +146,15 @@ public void ChangeFps(double fps) { for (var i = 0; i < Chapters.Count; i++) { - Chapter c = Chapters[i]; - double frames = c.Time.TotalSeconds*FramesPerSecond; + var c = Chapters[i]; + var frames = c.Time.TotalSeconds*FramesPerSecond; Chapters[i] = new Chapter { Name = c.Name, Time = new TimeSpan((long) Math.Round(frames/fps*TimeSpan.TicksPerSecond)) }; } - double totalFrames = Duration.TotalSeconds*FramesPerSecond; + var totalFrames = Duration.TotalSeconds*FramesPerSecond; Duration = new TimeSpan((long) Math.Round(totalFrames/fps*TimeSpan.TicksPerSecond)); FramesPerSecond = fps; } @@ -176,7 +176,7 @@ public void UpdataInfo(TimeSpan shift) /// <param name="shift">位移量</param> public void UpdataInfo(int shift) { - int index = 0; + var index = 0; Chapters.ForEach(item => item.Number = ++index + shift); } @@ -298,8 +298,8 @@ public string GetTsmuxerMeta() public void SaveXml(string filename, string lang, bool autoGenName) { if (string.IsNullOrWhiteSpace(lang)) lang = "und"; - Random rndb = new Random(); - XmlTextWriter xmlchap = new XmlTextWriter(filename, Encoding.UTF8) {Formatting = Formatting.Indented}; + var rndb = new Random(); + var xmlchap = new XmlTextWriter(filename, Encoding.UTF8) {Formatting = Formatting.Indented}; xmlchap.WriteStartDocument(); xmlchap.WriteComment("<!DOCTYPE Tags SYSTEM \"matroskatags.dtd\">"); xmlchap.WriteStartElement("Chapters"); @@ -329,12 +329,12 @@ public void SaveXml(string filename, string lang, bool autoGenName) public StringBuilder GetCue(string sourceFileName, bool autoGenName) { - StringBuilder cueBuilder = new StringBuilder(); + var cueBuilder = new StringBuilder(); cueBuilder.AppendLine("REM Generate By ChapterTool"); cueBuilder.AppendLine($"TITLE \"{Title}\""); cueBuilder.AppendLine($"FILE \"{sourceFileName}\" WAVE"); - int index = 0; + var index = 0; var name = ChapterName.GetChapterName(); foreach (var chapter in Chapters.Where(c=>c.Time != TimeSpan.MinValue)) { @@ -347,30 +347,30 @@ public StringBuilder GetCue(string sourceFileName, bool autoGenName) public StringBuilder GetJson(bool autoGenName) { - StringBuilder jsonBuilder = new StringBuilder(); + var jsonBuilder = new StringBuilder(); jsonBuilder.Append("{"); jsonBuilder.Append("\"sourceName\":"); jsonBuilder.Append(SourceType == "MPLS" ? $"\"{SourceName}.m2ts\"," : "\"undefined\","); jsonBuilder.Append("\"chapter\":"); jsonBuilder.Append("[["); - TimeSpan baseTime = TimeSpan.Zero; + var baseTime = TimeSpan.Zero; Chapter prevChapter = null; var name = ChapterName.GetChapterName(); - foreach (Chapter chapter in Chapters) + foreach (var chapter in Chapters) { if (chapter.Time == TimeSpan.MinValue && prevChapter != null) { baseTime = prevChapter.Time;//update base time name = ChapterName.GetChapterName(); - string initChapterName = autoGenName ? name() : prevChapter.Name; + var initChapterName = autoGenName ? name() : prevChapter.Name; jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("],["); jsonBuilder.Append($"{{\"name\":\"{initChapterName}\",\"time\":0}},"); continue; } - TimeSpan time = chapter.Time - baseTime; - string chapterName = (autoGenName ? name() : chapter.Name); + var time = chapter.Time - baseTime; + var chapterName = (autoGenName ? name() : chapter.Name); jsonBuilder.Append($"{{\"name\":\"{chapterName}\",\"time\":{time.TotalSeconds}}},"); prevChapter = chapter; } diff --git a/Time_Shift/Util/ChapterName.cs b/Time_Shift/Util/ChapterName.cs index 2805711..3bc8b65 100644 --- a/Time_Shift/Util/ChapterName.cs +++ b/Time_Shift/Util/ChapterName.cs @@ -75,7 +75,7 @@ public static IEnumerable<string> Range(int start, int count) private static IEnumerable<string> RangeIterator(int start, int count) { - for (int i = 0; i < count; i++) yield return $"{ChapterFormat} {start + i:D2}"; + for (var i = 0; i < count; i++) yield return $"{ChapterFormat} {start + i:D2}"; } } } \ No newline at end of file diff --git a/Time_Shift/Util/CueSharp.cs b/Time_Shift/Util/CueSharp.cs index 936656e..7e94c8f 100644 --- a/Time_Shift/Util/CueSharp.cs +++ b/Time_Shift/Util/CueSharp.cs @@ -162,9 +162,9 @@ private void ReadCueSheet(string filename, Encoding encoding) /// <param name="file"></param> private void RemoveEmptyLines(ref string[] file) { - int itemsRemoved = 0; + var itemsRemoved = 0; - for (int i = 0; i < file.Length; i++) + for (var i = 0; i < file.Length; i++) { if (file[i].Trim() != "") { @@ -186,10 +186,10 @@ private void ParseCue(string[] file) { //-1 means still global, //all others are track specific - int trackOn = -1; - AudioFile currentFile = new AudioFile(); + var trackOn = -1; + var currentFile = new AudioFile(); - for (int i = 0; i < file.Length; i++) + for (var i = 0; i < file.Length; i++) { file[i] = file[i].Trim(); @@ -380,7 +380,7 @@ private void ParseGarbage(string line, int trackOn) private void ParseIndex(string line, int trackOn) { - int number = 0; + var number = 0; var indexType = line.Substring(0, line.IndexOf(' ')).ToUpper(); @@ -394,9 +394,9 @@ private void ParseIndex(string line, int trackOn) } //extract the minutes, seconds, and frames - int minutes = Convert.ToInt32(tempString.Substring(0, tempString.IndexOf(':'))); - int seconds = Convert.ToInt32(tempString.Substring(tempString.IndexOf(':') + 1, tempString.LastIndexOf(':') - tempString.IndexOf(':') - 1)); - int frames = Convert.ToInt32(tempString.Substring(tempString.LastIndexOf(':') + 1, tempString.Length - tempString.LastIndexOf(':') - 1)); + var minutes = Convert.ToInt32(tempString.Substring(0, tempString.IndexOf(':'))); + var seconds = Convert.ToInt32(tempString.Substring(tempString.IndexOf(':') + 1, tempString.LastIndexOf(':') - tempString.IndexOf(':') - 1)); + var frames = Convert.ToInt32(tempString.Substring(tempString.LastIndexOf(':') + 1, tempString.Length - tempString.LastIndexOf(':') - 1)); if (indexType == "INDEX") { @@ -414,7 +414,7 @@ private void ParseIndex(string line, int trackOn) private void ParseString(string line, int trackOn) { - string category = line.Substring(0, line.IndexOf(' ')).ToUpper(); + var category = line.Substring(0, line.IndexOf(' ')).ToUpper(); line = line.Substring(line.IndexOf(' '), line.Length - line.IndexOf(' ')).Trim(); @@ -509,10 +509,10 @@ private void ParseTrack(string line, int trackOn) /// <remarks >Useage: int[] a = {1,2,3}; a = (int[])ResizeArray(a,5);</remarks> public static Array ResizeArray(Array oldArray, int newSize) { - int oldSize = oldArray.Length; - Type elementType = oldArray.GetType().GetElementType(); - Array newArray = Array.CreateInstance(elementType, newSize); - int preserveLength = Math.Min(oldSize, newSize); + var oldSize = oldArray.Length; + var elementType = oldArray.GetType().GetElementType(); + var newArray = Array.CreateInstance(elementType, newSize); + var preserveLength = Math.Min(oldSize, newSize); if (preserveLength > 0) Array.Copy(oldArray, newArray, preserveLength); return newArray; @@ -587,7 +587,7 @@ public void AddTrack(Track track) /// <param name="trackIndex">The index of the track you wish to remove.</param> public void RemoveTrack(int trackIndex) { - for (int i = trackIndex; i < Tracks.Length - 1; i++) + for (var i = trackIndex; i < Tracks.Length - 1; i++) { Tracks[i] = Tracks[i + 1]; } @@ -649,9 +649,9 @@ public void SaveCue(string filename, Encoding encoding) /// <returns>The entire cuesheet formatted to specification.</returns> public override string ToString() { - StringBuilder output = new StringBuilder(); + var output = new StringBuilder(); - foreach (string comment in Comments) + foreach (var comment in Comments) { output.Append("REM " + comment + Environment.NewLine); } @@ -681,7 +681,7 @@ public override string ToString() output.Append("CDTEXTFILE \"" + CDTextFile.Trim() + "\"" + Environment.NewLine); } - for (int i = 0; i < Tracks.Length; i++) + for (var i = 0; i < Tracks.Length; i++) { output.Append(Tracks[i].ToString()); @@ -706,7 +706,7 @@ public override string ToString() public string CalculateCDDBdiscID() { - int n = 0; + var n = 0; /* For backward compatibility this algorithm must not change */ @@ -751,7 +751,7 @@ private static int cddb_sum(int n) public ChapterInfo ToChapterInfo() { - ChapterInfo info = new ChapterInfo + var info = new ChapterInfo { Title = Title, SourceType = "CUE", @@ -761,7 +761,7 @@ public ChapterInfo ToChapterInfo() foreach (var track in Tracks) { string name = $"{track.Title} [{track.Performer}]"; - TimeSpan time = track.Index01; + var time = track.Index01; info.Chapters.Add(new Chapter(name, time, track.TrackNumber)); } info.Duration = info.Chapters.Last().Time; @@ -1245,7 +1245,7 @@ public void AddIndex(int number, int minutes, int seconds, int frames) public void RemoveIndex(int indexIndex) { - for (int i = indexIndex; i < Indices.Length - 1; i++) + for (var i = indexIndex; i < Indices.Length - 1; i++) { Indices[i] = Indices[i + 1]; } @@ -1264,7 +1264,7 @@ private bool NewFlag(Flags newFlag) public override string ToString() { - StringBuilder output = new StringBuilder(); + var output = new StringBuilder(); //write file if (DataFile.Filename != null && DataFile.Filename.Trim() != "") @@ -1275,7 +1275,7 @@ public override string ToString() output.Append(" TRACK " + TrackNumber.ToString().PadLeft(2, '0') + " " + TrackDataType.ToString().Replace('_', '/')); //write comments - foreach (string comment in Comments) + foreach (var comment in Comments) { output.Append(Environment.NewLine + " REM " + comment); } @@ -1301,7 +1301,7 @@ public override string ToString() output.Append(Environment.NewLine + " FLAGS"); } - foreach (Flags flag in TrackFlags) + foreach (var flag in TrackFlags) { output.Append(" " + flag.ToString().Replace("CH4", "4CH")); } @@ -1319,7 +1319,7 @@ public override string ToString() } //write Indices - for (int j = 0; j < Indices.Length; j++) + for (var j = 0; j < Indices.Length; j++) { output.Append(Environment.NewLine + " INDEX " + this[j].Number.ToString().PadLeft(2, '0') + " " + this[j].Minutes.ToString().PadLeft(2, '0') + ":" + this[j].Seconds.ToString().PadLeft(2, '0') + ":" + this[j].Frames.ToString().PadLeft(2, '0')); } diff --git a/Time_Shift/Util/Expression.cs b/Time_Shift/Util/Expression.cs index 4c33080..fc43007 100644 --- a/Time_Shift/Util/Expression.cs +++ b/Time_Shift/Util/Expression.cs @@ -56,7 +56,7 @@ public Expression(IEnumerable<string> tokens) private static Token ToToken(string token) { - Token ret = new Token {Value = token, TokenType = Token.Symbol.Variable}; + var ret = new Token {Value = token, TokenType = Token.Symbol.Variable}; if (token.Length == 1 && OperatorTokens.Contains(token.First())) { if (token == "(" || token == ")") @@ -184,7 +184,7 @@ private static Token EvalCMathTwoToken(Token func, Token value, Token value2) private static Token GetToken(string expr, ref int pos) { var varRet = new StringBuilder(); - int i = pos; + var i = pos; for (; i < expr.Length; i++) { if (IsSpace(expr[i])) @@ -255,13 +255,13 @@ private static int GetPriority(Token token) public static IEnumerable<Token> BuildPostExpressionStack(string expr) { - var retStack = new Stack<Token>(); - var stack = new Stack<Token>(); + var retStack = new Stack<Token>(); + var stack = new Stack<Token>(); var funcStack = new Stack<Token>(); stack.Push(Token.End); - int pos = 0; - var preToken = Token.End; - bool comment = false; + var pos = 0; + var preToken = Token.End; + var comment = false; while (pos < expr.Length && !comment) { var token = GetToken(expr, ref pos); diff --git a/Time_Shift/Util/LanguageHelper.cs b/Time_Shift/Util/LanguageHelper.cs index a09ec53..e48a28b 100644 --- a/Time_Shift/Util/LanguageHelper.cs +++ b/Time_Shift/Util/LanguageHelper.cs @@ -16,12 +16,12 @@ private static void SetAllLang(string lang) { System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang); - string name = "Form1"; + var name = "Form1"; var frm = (Form)Assembly.Load("CameraTest").CreateInstance(name); if (frm == null) return; - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(); + var resources = new System.ComponentModel.ComponentResourceManager(); resources.ApplyResources(frm, "$this"); AppLang(frm, resources); } @@ -38,7 +38,7 @@ public static void SetLang(string lang, Form form, Type formType) { System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang); if (form == null) return; - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(formType); + var resources = new System.ComponentModel.ComponentResourceManager(formType); resources.ApplyResources(form, "$this"); AppLang(form, resources); } @@ -47,7 +47,7 @@ public static void SetLang(string lang, Control control, Type formType) { //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang); if (control == null) return; - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(formType); + var resources = new System.ComponentModel.ComponentResourceManager(formType); AppLang(control, resources); } diff --git a/Time_Shift/Util/Logger.cs b/Time_Shift/Util/Logger.cs index 0185159..054280c 100644 --- a/Time_Shift/Util/Logger.cs +++ b/Time_Shift/Util/Logger.cs @@ -17,7 +17,7 @@ public static class Logger public static void Log(string message) { - DateTime actionDate = DateTime.Now; + var actionDate = DateTime.Now; string logMessage = $"{actionDate:[yyyy-MM-dd][HH:mm:ss]} {message}"; LogContext.AppendLine(logMessage); OnLogLineAdded(logMessage, actionDate); diff --git a/Time_Shift/Util/Notification.cs b/Time_Shift/Util/Notification.cs index d77c0a9..ec96ce9 100644 --- a/Time_Shift/Util/Notification.cs +++ b/Time_Shift/Util/Notification.cs @@ -52,10 +52,9 @@ public static DialogResult ShowInfo(string argMessage, MessageBoxButtons buttons buttons: buttons, icon: MessageBoxIcon.Information); } - public static string InputBox(string caption, string prompt, string defaultText) { - string localInputText = defaultText; + var localInputText = defaultText; return InputQuery(caption, prompt, ref localInputText) ? localInputText : ""; } @@ -112,11 +111,11 @@ private static bool InputQuery(string caption, string prompt, ref string value) edInput.SelectAll(); - int buttonTop = MulDiv(41, dialogUnits.Height, 8); + var buttonTop = MulDiv(41, dialogUnits.Height, 8); //Command buttons should be 50x14 dlus - Size buttonSize = ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8); + var buttonSize = ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8); - Button bbOk = new Button + var bbOk = new Button { Parent = form, Text = "OK", @@ -126,7 +125,7 @@ private static bool InputQuery(string caption, string prompt, ref string value) bbOk.Location = new Point(MulDiv(38, dialogUnits.Width, 4), buttonTop); bbOk.Size = buttonSize; - Button bbCancel = new Button + var bbCancel = new Button { Parent = form, Text = "Cancel", diff --git a/Time_Shift/Util/SystemMenu.cs b/Time_Shift/Util/SystemMenu.cs index 6f42ba1..4b280d1 100644 --- a/Time_Shift/Util/SystemMenu.cs +++ b/Time_Shift/Util/SystemMenu.cs @@ -69,7 +69,7 @@ public SystemMenu(Form form) /// <param name="separatorBeforeCommand">Indicates whether a separator is inserted before the command.</param> public void AddCommand(string text, Action action, bool separatorBeforeCommand) { - int id = ++lastId; + var id = ++lastId; if (!form.IsHandleCreated) { // The form is not yet created, queue the command for later addition @@ -126,7 +126,7 @@ private void OnHandleCreated(object sender, EventArgs args) // Add all queued commands now if (pendingCommands != null) { - foreach (CommandInfo command in pendingCommands) + foreach (var command in pendingCommands) { if (command.Separator) { diff --git a/Time_Shift/Util/ToolKits.cs b/Time_Shift/Util/ToolKits.cs index 87f5009..45269f8 100644 --- a/Time_Shift/Util/ToolKits.cs +++ b/Time_Shift/Util/ToolKits.cs @@ -74,7 +74,7 @@ public static TimeSpan ToTimeSpan(this string input) public static string ToCueTimeStamp(this TimeSpan input) { - int frames = (int) Math.Round(input.Milliseconds*75/1000F); + var frames = (int) Math.Round(input.Milliseconds*75/1000F); if (frames > 99) frames = 99; return $"{input.Hours*60 + input.Minutes:D2}:{input.Seconds:D2}:{frames:D2}"; } @@ -102,7 +102,7 @@ public static Point String2Point(string input) /// <returns></returns> public static int ConvertFr2Index(double frame) { - for (int i = 0; i < MplsData.FrameRate.Length; ++i) + for (var i = 0; i < MplsData.FrameRate.Length; ++i) { if (Math.Abs(frame - (double)MplsData.FrameRate[i]) < 1e-5) return i; @@ -249,7 +249,7 @@ public static class RegistryStorage { public static string Load(string subKey = @"Software\ChapterTool", string name = "SavingPath") { - string path = string.Empty; + var path = string.Empty; // HKCU_CURRENT_USER\Software\ var registryKey = Registry.CurrentUser.OpenSubKey(subKey); if (registryKey == null) return path; @@ -278,7 +278,7 @@ public static void SetOpenMethod(string programFile, string extension, string ty { Registry.ClassesRoot.CreateSubKey(extension)?.SetValue(typeName, project, RegistryValueKind.String); - RegistryKey subKey = Registry.ClassesRoot.CreateSubKey(project); + var subKey = Registry.ClassesRoot.CreateSubKey(project); subKey = subKey?.CreateSubKey("shell"); subKey = subKey?.CreateSubKey("open"); subKey = subKey?.CreateSubKey("command"); @@ -290,7 +290,7 @@ public static void SetOpenMethod(string programFile, string extension, string ty public static int RegistryAddCount(string subKey, string name, int delta = 1) { var countS = Load(subKey, name); - int count = string.IsNullOrEmpty(countS) ? 0 : int.Parse(countS); + var count = string.IsNullOrEmpty(countS) ? 0 : int.Parse(countS); count += delta; Save(count.ToString(), subKey, name); return count - delta; diff --git a/Time_Shift/Util/Updater.cs b/Time_Shift/Util/Updater.cs index 4cdd7c1..31d1280 100644 --- a/Time_Shift/Util/Updater.cs +++ b/Time_Shift/Util/Updater.cs @@ -34,9 +34,9 @@ public static class Updater { private static void OnResponse(IAsyncResult ar) { - Regex versionRegex = new Regex(@"<meta\s+name\s*=\s*'ChapterTool'\s+content\s*=\s*'(\d+\.\d+\.\d+\.\d+)'\s*>", RegexOptions.Compiled); - Regex baseUrlRegex = new Regex(@"<meta\s+name\s*=\s*'BaseUrl'\s+content\s*=\s*'(.+)'\s*>", RegexOptions.Compiled); - WebRequest webRequest = (WebRequest)ar.AsyncState; + var versionRegex = new Regex(@"<meta\s+name\s*=\s*'ChapterTool'\s+content\s*=\s*'(\d+\.\d+\.\d+\.\d+)'\s*>", RegexOptions.Compiled); + var baseUrlRegex = new Regex(@"<meta\s+name\s*=\s*'BaseUrl'\s+content\s*=\s*'(.+)'\s*>", RegexOptions.Compiled); + var webRequest = (WebRequest)ar.AsyncState; Stream responseStream; try { @@ -50,14 +50,14 @@ private static void OnResponse(IAsyncResult ar) } if (responseStream == null) return; - StreamReader streamReader = new StreamReader(responseStream); - string context = streamReader.ReadToEnd(); - var result = versionRegex.Match(context); - var urlResult = baseUrlRegex.Match(context); + var streamReader = new StreamReader(responseStream); + var context = streamReader.ReadToEnd(); + var result = versionRegex.Match(context); + var urlResult = baseUrlRegex.Match(context); if (!result.Success || !result.Success) return; var currentVersion = Assembly.GetExecutingAssembly().GetName().Version; - Version remoteVersion = Version.Parse(result.Groups[1].Value); + var remoteVersion = Version.Parse(result.Groups[1].Value); if (currentVersion >= remoteVersion) { MessageBox.Show($"v{currentVersion} 已是最新版", @"As Expected"); @@ -66,7 +66,7 @@ private static void OnResponse(IAsyncResult ar) var dialogResult = MessageBox.Show(caption: @"Wow! Such Impressive", text: $"新车已发车 v{remoteVersion},上车!", buttons: MessageBoxButtons.YesNo, icon: MessageBoxIcon.Asterisk); if (dialogResult != DialogResult.Yes) return; - FormUpdater formUpdater = new FormUpdater(Assembly.GetExecutingAssembly().Location, remoteVersion, urlResult.Groups[1].Value); + var formUpdater = new FormUpdater(Assembly.GetExecutingAssembly().Location, remoteVersion, urlResult.Groups[1].Value); formUpdater.ShowDialog(); } @@ -74,7 +74,7 @@ public static void CheckUpdate() { if (!IsConnectInternet()) return; - HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://tautcony.github.io/tcupdate.html"); + var webRequest = (HttpWebRequest)WebRequest.Create("http://tautcony.github.io/tcupdate.html"); #if DEBUG webRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:4000/tcupdate.html"); #endif From 864def2a159114da729bddb32427f1e12c4b404e Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Thu, 4 May 2017 16:35:27 +0800 Subject: [PATCH 30/31] Skip some attributes reading to get UHD's chapters first. --- Time_Shift/Util/ChapterData/MplsData.cs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Time_Shift/Util/ChapterData/MplsData.cs b/Time_Shift/Util/ChapterData/MplsData.cs index fb1012f..2210d58 100644 --- a/Time_Shift/Util/ChapterData/MplsData.cs +++ b/Time_Shift/Util/ChapterData/MplsData.cs @@ -38,6 +38,8 @@ public class MplsData private readonly byte[] _data; + private int _version; + public static readonly decimal[] FrameRate = { 0M, 24000M / 1001, 24M, 25M, 30000M / 1001, 0M, 50M, 60000M / 1001 }; public static event Action<string> OnLog; @@ -53,7 +55,6 @@ private void ParseMpls() ParseHeader(out int playlistMarkSectionStartAddress, out int playItemNumber, out int playItemEntries); for (var playItemOrder = 0; playItemOrder < playItemNumber; playItemOrder++) { - ParsePlayItem(playItemEntries, out int lengthOfPlayItem, out int itemStartAdress, out int streamCount); for (var streamOrder = 0; streamOrder < streamCount; streamOrder++) { @@ -69,10 +70,15 @@ private void ParseMpls() private void ParseHeader(out int playlistMarkSectionStartAddress, out int playItemNumber, out int playItemEntries) { var fileType = Encoding.ASCII.GetString(_data, 0, 8); - if ((fileType != "MPLS0100" && fileType != "MPLS0200") /*|| _data[45] != 1*/) + if ((fileType != "MPLS0100" && fileType != "MPLS0200" && fileType != "MPLS0300") /*|| _data[45] != 1*/) { throw new Exception($"This Playlist has an unknown file type {fileType}."); } + _version = int.Parse(fileType.Substring(5, 1)); + if (_version == 3) + { + OnLog?.Invoke("There is no complete support for UHD's playlist currently"); + } var playlistSectionStartAddress = Byte2Int32(_data, 0x08); playlistMarkSectionStartAddress = Byte2Int32(_data, 0x0c); playItemNumber = Byte2Int16(_data, playlistSectionStartAddress + 0x06); @@ -128,9 +134,12 @@ private void ParseStream(int itemStartAdress, int streamOrder, int playItemOrder var streamCodingType = stream[0x0b]; var chapterClip = ChapterClips[playItemOrder]; var clipName = 0x01 == stream[01] ? chapterClip.Name : chapterClip.Name + " Sub Path"; - StreamAttribute.OnLog += StreamAttributeLog; - StreamAttribute.LogStreamAttributes(stream, clipName); - StreamAttribute.OnLog -= StreamAttributeLog; + if (_version < 3) + { + StreamAttribute.OnLog += StreamAttributeLog; + StreamAttribute.LogStreamAttributes(stream, clipName); + StreamAttribute.OnLog -= StreamAttributeLog; + } if (0x01 != stream[01]) return; //make sure this stream is Play Item if (0x1b != streamCodingType && 0x02 != streamCodingType && From 162fda77900954774f0684e1a15a22543ab6d60d Mon Sep 17 00:00:00 2001 From: tautcony <tautcony@gmail.com> Date: Thu, 4 May 2017 16:42:25 +0800 Subject: [PATCH 31/31] Bumped version number to 2.33.33.2 --- ChangeLog.md | 7 +++++++ Time_Shift/Properties/AssemblyInfo.cs | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 979a9f6..64e7f8f 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -339,3 +339,10 @@ - mpls增加追加功能 - 低版本.Net运行时增加更新提示 - 新增flac parser可获得更多flac相关信息(虽然是ATI用的 + +## [2.33.33.2] +- 错误修正与效能提升 +- 修正内封cue的读取 +- 增加json输出格式 +- 增加对高分屏的支持 +- 增加对UHD原盘基础支持 diff --git a/Time_Shift/Properties/AssemblyInfo.cs b/Time_Shift/Properties/AssemblyInfo.cs index dd60faf..821d7a3 100644 --- a/Time_Shift/Properties/AssemblyInfo.cs +++ b/Time_Shift/Properties/AssemblyInfo.cs @@ -31,5 +31,5 @@ // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("2.33.33.1")] -[assembly: AssemblyFileVersion("2.33.33.1")] +[assembly: AssemblyVersion("2.33.33.2")] +[assembly: AssemblyFileVersion("2.33.33.2")]