public TimeSpan GetRunTime(string filename) { MediaInfoLib.MediaInfo mediaInfo = null; try { mediaInfo = new MediaInfoLib.MediaInfo(); _logger.Trace("Getting media info from {0}", filename); mediaInfo.Option("ParseSpeed", "0.2"); int open = mediaInfo.Open(filename); if (open != 0) { int runTime; Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); mediaInfo.Close(); return(TimeSpan.FromMilliseconds(runTime)); } } catch (Exception ex) { _logger.ErrorException("Unable to parse media info from file: " + filename, ex); } finally { if (mediaInfo != null) { mediaInfo.Close(); } } return(new TimeSpan()); }
public MediaViewModel(string Name = "", string ArtistName = "", string AlbumName = "", Uri Path = null, String Length = "00:00:00") { Dictionary<String, String> tmp = new Dictionary<string, string>(); if (Path != null) { try { MediaInfo lol = new MediaInfo(); if (lol.Open(Uri.UnescapeDataString(Path.AbsolutePath)) == 1) { foreach (string entry in lol.Inform().Split('\n')) { var tokens = entry.Split(':'); if (tokens.Length == 2) tmp[tokens[0].Trim()] = tokens[1].Trim(); } lol.Close(); } } catch (Exception e) { MessageBox.Show("MediaInfo: "+ e.Message); } } Song = new Media(tmp.ContainsKey("Track name") ? tmp["Track name"] : "", tmp.ContainsKey("Performer") ? tmp["Performer"] : "", tmp.ContainsKey("Album") ? tmp["Album"] : "", Path, tmp.ContainsKey("Duration") ? getLength(tmp["Duration"]) : ""); }
public static DateTime? GetVideoFileTakenDate(string filePath) { MediaInfo mediaInfo = null; try { mediaInfo = new MediaInfo(); mediaInfo.Open(filePath); DateTime? result = null; string recordedDate = mediaInfo.Get(StreamKind.General, 0, "Recorded_Date"); if (!string.IsNullOrWhiteSpace(recordedDate)) { result = DateTime.Parse(recordedDate, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal); } if (result == null) { recordedDate = mediaInfo.Get(StreamKind.General, 0, "Encoded_Date"); if (string.IsNullOrWhiteSpace(recordedDate)) { recordedDate = mediaInfo.Get(StreamKind.General, 0, "Tagged_Date"); } if (!string.IsNullOrWhiteSpace(recordedDate)) { var dateTimeStyles = DateTimeStyles.AssumeUniversal; // Canon records local time as UTC var canonCameraIdentifier = mediaInfo.Get(StreamKind.General, 0, "CodecID/String"); if (canonCameraIdentifier.Contains("/CAEP")) { dateTimeStyles = DateTimeStyles.AssumeLocal; } result = DateTime.ParseExact(recordedDate, "\"UTC\" yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, dateTimeStyles); } } if (result == null) { recordedDate = mediaInfo.Get(StreamKind.General, 0, "Mastered_Date"); if (!string.IsNullOrWhiteSpace(recordedDate)) { result = DateTime.ParseExact(recordedDate, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal); } } return result; } catch (Exception) { } finally { if (mediaInfo != null) { mediaInfo.Close(); } } return null; }
public FileInput(string filename) { this.filename = filename; MediaInfo MI = new MediaInfo(); if (MI.Open(this.GetFileName()) > 0) { string s = MI.Option("Info_Parameters"); int width = int.Parse(MI.Get(StreamKind.Video, 0, "Width")); int height = int.Parse(MI.Get(StreamKind.Video, 0, "Height")); decimal aspect = (decimal)width / (decimal)height; bool resize = false; if (width > 1280) { width = 1280; height = (int)(width / aspect); resize = true; } if (height > 720) { height = 720; width = (int)(height * aspect); resize = true; } if (resize) { if (width % 2 > 0) width -= 1; if (height % 2 > 0) height -= 1; this._size = " -s " + width + "x" + height; } Log.WriteLine("resize=" + resize + ",size=" + width + "x" + height); int videobitrate = int.Parse(MI.Get(StreamKind.Video, 0, "BitRate")); if (videobitrate > 7 * 1024 * 1024 || resize) { this._parameter = " libx264 -coder 0 -flags -loop -cmp +chroma -partitions -parti8x8-parti4x4-partp8x8-partb8x8 -me_method dia -subq 0 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 0 -i_qfactor 0.71 -b_strategy 0 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 0 -refs 1 -directpred 1 -trellis 0 -flags2 -bpyramid-mixed_refs-wpred-dct8x8+fastpskip-mbtree -wpredp 0 -b 4096k "; } else { this._parameter = " copy"; } this._parameter = " -vcodec " + this._parameter; //Log.WriteLine("media info supported :" + s); MI.Close(); } if (this.GetFileName().ToLower().EndsWith(".mp4") || this.GetFileName().ToLower().EndsWith(".mkv")) { this._parameter += " -vbsf h264_mp4toannexb "; } this._parameter += " -acodec libfaac -ac 2 -ab 192k "; }
public static void Main() { MediaInfo MI = new MediaInfo(); //change the files accordingly, tested with .avi, .mpg, .mpeg - these should be enough MI.Open("1.flv"); string display = ""; display += "FileName: " + MI.Get(0, 0, "FileName") + "\n"; display += "FileExtension: " + MI.Get(0, 0, "FileExtension") + "\n"; display += "Title: " + MI.Get(0, 0, "Title") + "\n"; display += "Subtitle: " + MI.Get(0, 0, "Title/More") + "\n"; display += "Tags: " + MI.Get(0, 0, "WM/Category") + "\n"; display += "Comments: " + MI.Get(0, 0, "Comment") + "\n"; string sizeInKBStr = MI.Get(0, 0, "FileSize/String").Substring(0, MI.Get(0, 0, "FileSize/String").LastIndexOf(" ")).Replace(" ", ""); double sizeInKB = Double.Parse(sizeInKBStr); double sizeInMB = (double)(sizeInKB / 1024); string sizeInMBStr = String.Format("{0:0.00}", sizeInMB); display += "Size: " + sizeInMBStr + " MB" + "\n"; display += "Date created: " + MI.Get(0, 0, "File_Created_Date").Substring(MI.Get(0, 0, "File_Created_Date").IndexOf(" ") + 1, MI.Get(0, 0, "File_Created_Date").LastIndexOf(".")-4) + "\n"; display += "Date modified: " + MI.Get(0, 0, "File_Modified_Date").Substring(MI.Get(0, 0, "File_Modified_Date").IndexOf(" ") + 1, MI.Get(0, 0, "File_Modified_Date").LastIndexOf(".")-4) + "\n"; display += "\nVIDEO\n"; display += "Length: " + MI.Get(0, 0, "Duration/String3").Substring(0, MI.Get(0, 0, "Duration/String3").LastIndexOf(".")) + "\n"; display += "Frame width: " + MI.Get(StreamKind.Video, 0, "Width/String") + "\n"; display += "Frame height: " + MI.Get(StreamKind.Video, 0, "Height/String") + "\n"; if (MI.Get(StreamKind.Video, 0, "BitRate/String") != "") display += "Data rate: " + MI.Get(StreamKind.Video, 0, "BitRate/String").Substring(0, MI.Get(StreamKind.Video, 0, "BitRate/String").LastIndexOf(" ")).Replace(" ", "") + " kbps" + "\n"; else display += "Data rate:\n"; string frameRateOriStr = MI.Get(StreamKind.Video, 0, "FrameRate/String").Substring(0, MI.Get(StreamKind.Video, 0, "FrameRate/String").LastIndexOf(" ")).Replace(" ", ""); double frameRate = Double.Parse(frameRateOriStr); string frameRateStr = String.Format("{0:0}", frameRate); display += "Frame rate: " + frameRateStr + " fps" + "\n"; display += "\nAUDIO\n"; string bitrateOriStr = MI.Get(StreamKind.Audio, 0, "BitRate/String").Substring(0, MI.Get(StreamKind.Audio, 0, "BitRate/String").LastIndexOf(" ")).Replace(" ", ""); double bitrateRate = Double.Parse(bitrateOriStr); string bitrateRateStr = String.Format("{0:0}", bitrateRate); display += "Bitrate: " + bitrateRateStr + " kbps" + "\n"; display += "Channels: " + MI.Get(StreamKind.Audio, 0, "Channel(s)/String") + "\n"; string audioSampleRateOriStr = MI.Get(StreamKind.Audio, 0, "SamplingRate/String").Substring(0, MI.Get(StreamKind.Audio, 0, "SamplingRate/String").LastIndexOf(" ")).Replace(" ", ""); double audioSampleRate = Double.Parse(audioSampleRateOriStr); string audioSampleRateStr = String.Format("{0:0}", audioSampleRate); display += "Audio sample rate: " + audioSampleRateStr + " kHz" + "\n"; display += "\nMEDIA\n"; display += "Artist: " + MI.Get(0, 0, "Performer") + "\n"; display += "Year: " + MI.Get(0, 0, "Recorded_Date") + "\n"; display += "Genre: " + MI.Get(0, 0, "Genre") + "\n"; MI.Close(); Console.WriteLine(display); }
public Musiikki(string nimi, string filePath) { FilePath = filePath; MediaInfo MI = new MediaInfo(); MI.Open(FilePath); Nimi = MI.Get(StreamKind.General, 0, "FileName"); Pituus = MI.Get(StreamKind.General, 0, "Duration/String"); SoundEncoding = MI.Get(StreamKind.Audio, 0, "Language/String") + "," + MI.Get(StreamKind.Audio, 0, "SamplingRate/String") + "," + MI.Get(StreamKind.Audio, 0, "Channel(s)/String") + "," + MI.Get(StreamKind.General, 0, "Audio_Format_List"); TiedostonKoko = MI.Get(StreamKind.General, 0, "FileSize/String"); MI.Close(); }
private Int32 GetDuration(string location) { MediaInfoLib.MediaInfo mediaInfo = new MediaInfoLib.MediaInfo(); mediaInfo.Option("ParseSpeed", "0.3"); int i = mediaInfo.Open(location); int runTime = 0; if (i != 0) { Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); } mediaInfo.Close(); return(runTime); }
public Elokuva(string nimi, string filePath) { Watched = false; FilePath = filePath; MediaInfo MI = new MediaInfo(); MI.Open(FilePath); nimi = MI.Get(StreamKind.General, 0, "FileName"); Nimi = TrimNimi(nimi); Pituus = MI.Get(StreamKind.General, 0, "Duration/String"); VideoEncoding = MI.Get(StreamKind.General, 0, "Format"); SoundEncoding = MI.Get(StreamKind.Audio, 0, "Language/String") + "," + MI.Get(StreamKind.Audio, 0, "SamplingRate/String") + "," + MI.Get(StreamKind.Audio, 0, "Channel(s)/String") + "," + MI.Get(StreamKind.General, 0, "Audio_Format_List"); TiedostonKoko = MI.Get(StreamKind.General, 0, "FileSize/String"); Fps = MI.Get(StreamKind.Video, 0, "FrameRate/String"); Resolution = MI.Get(StreamKind.Video, 0, "Width") + "x" + MI.Get(StreamKind.Video, 0, "Height"); MI.Close(); Movie movie = Search.getMovieInfoFromDb(Nimi); // movie.Elokuva = this; DbTiedot=movie; }
private void Form1_Load(object sender, System.EventArgs e) { //Test if version of DLL is compatible : 3rd argument is "version of DLL tested;Your application name;Your application version" String ToDisplay; MediaInfo MI = new MediaInfo(); ToDisplay = MI.Option("Info_Version", "0.7.0.0;MediaInfoDLL_Example_CS;0.7.0.0"); if (ToDisplay.Length == 0) { richTextBox1.Text = "MediaInfo.Dll: this version of the DLL is not compatible"; return; } //Information about MediaInfo ToDisplay += "\r\n\r\nInfo_Parameters\r\n"; ToDisplay += MI.Option("Info_Parameters"); ToDisplay += "\r\n\r\nInfo_Capacities\r\n"; ToDisplay += MI.Option("Info_Capacities"); ToDisplay += "\r\n\r\nInfo_Codecs\r\n"; ToDisplay += MI.Option("Info_Codecs"); //An example of how to use the library ToDisplay += "\r\n\r\nOpen\r\n"; MI.Open("Example.ogg"); ToDisplay += "\r\n\r\nInform with Complete=false\r\n"; MI.Option("Complete"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nInform with Complete=true\r\n"; MI.Option("Complete", "1"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nCustom Inform\r\n"; MI.Option("Inform", "General;File size is %FileSize% bytes"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n"; ToDisplay += MI.Get(0, 0, "FileSize"); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n"; ToDisplay += MI.Get(0, 0, 46); ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n"; ToDisplay += MI.Count_Get(StreamKind.Audio); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n"; ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount"); ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n"; ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount"); ToDisplay += "\r\n\r\nClose\r\n"; MI.Close(); //Example with a stream //ToDisplay+="\r\n"+ExampleWithStream()+"\r\n"; Crc16Ccitt A=new Crc16Ccitt(InitialCrcValue.Zeros); byte[] B = { 0x84, 0x00, 0x00, 0x00, 0x6B, 0x00, 0x00, 0x00, 0x67, 0x1F, 0x20, 0x00, 0x00, 0x62, 0x0C, 0x9B, 0x35, 0x35, 0x38, 0x3B, 0x34, 0x31, 0x36, 0x20, 0x56, 0x9B, 0x38, 0x31, 0x3B, 0x33, 0x32, 0x20, 0x5F, 0x90, 0x6F, 0x90, 0x20, 0x41, 0x90, 0x7E, 0x9B, 0x31, 0x3B, 0x30, 0x30, 0x30, 0x30, 0x20, 0x63, 0x9B, 0x30, 0x20, 0x58, 0x1C, 0x40, 0x40, 0x1C, 0x46, 0x40, 0x90, 0x20, 0x40, 0x90, 0x50, 0xC9, 0xB3, 0xC7, 0x89, 0x20, 0x1D, 0x61, 0x1B, 0x7E, 0xC0, 0xA4, 0xE9, 0xF3, 0xC1, 0xF3, 0x8A, 0x24, 0x72, 0x21, 0x29, 0x88, 0x1C, 0x4F, 0x41, 0x89, 0xE1, 0xAD, 0xB7, 0xB3, 0x8A, 0x21, 0x29, 0x89, 0x20, 0x8A, 0x21, 0x44, 0x89, 0xA4, 0xF3, 0xBF, 0xF9, 0xCD, 0xC3, 0xC8, 0x8A, 0x21, 0x29 }; ushort C=A.ComputeChecksum(B); //Displaying the text richTextBox1.Text = ToDisplay; }
private bool IndexCrop() { try { DoPlugin(PluginType.BeforeAutoCrop); string filename = ""; AdvancedVideoOptions avo = null; foreach (StreamInfo si in demuxedStreamList.streams) { if (si.streamType == StreamType.Video) { filename = si.filename; if (si.advancedOptions != null && si.advancedOptions.GetType() == typeof(AdvancedVideoOptions)) avo = (AdvancedVideoOptions)si.advancedOptions; break; } } string fps = ""; string resX = ""; string resY = ""; string length = ""; string frames = ""; try { MediaInfoLib.MediaInfo mi2 = new MediaInfoLib.MediaInfo(); mi2.Open(filename); mi2.Option("Complete", "1"); string[] tmpstr = mi2.Inform().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in tmpstr) { logWindow.MessageCrop(s.Trim()); } if (mi2.Count_Get(StreamKind.Video) > 0) { fps = mi2.Get(StreamKind.Video, 0, "FrameRate"); resX = mi2.Get(StreamKind.Video, 0, "Width"); resY = mi2.Get(StreamKind.Video, 0, "Height"); length = mi2.Get(StreamKind.Video, 0, "Duration"); frames = mi2.Get(StreamKind.Video, 0, "FrameCount"); } mi2.Close(); } catch (Exception ex) { logWindow.MessageCrop(Global.Res("ErrorMediaInfo") + " " + ex.Message); return false; } if (avo != null && avo.disableFps) { logWindow.MessageCrop(Global.Res("InfoManualFps")); fps = avo.fps; length = avo.length; frames = avo.frames; } if (fps == "") { logWindow.MessageCrop(Global.Res("ErrorFramerate")); foreach (StreamInfo si in demuxedStreamList.streams) { if (si.streamType == StreamType.Video) { if (si.desc.Contains("24 /1.001")) { logWindow.MessageCrop(Global.ResFormat("InfoFps", " 23.976")); fps = "23.976"; break; } else if (si.desc.Contains("1080p24 (16:9)")) { logWindow.MessageCrop(Global.ResFormat("InfoFps", " 24")); fps = "24"; break; } // add other framerates here } } if (fps == "") { logWindow.MessageCrop(Global.Res("ErrorNoFramerate")); return false; } } if (frames == "" || length == "") { logWindow.MessageCrop(Global.Res("InfoFrames")); } CropInfo cropInfo = new CropInfo(); if (!settings.untouchedVideo) { if (settings.cropInput == 1 || settings.encodeInput == 1) { bool skip = false; if (File.Exists(filename + ".ffindex") && !settings.deleteIndex) { skip = true; } if (!skip) { it = new IndexTool(settings, filename, IndexType.ffmsindex); it.OnInfoMsg += new ExternalTool.InfoEventHandler(IndexMsg); it.OnLogMsg += new ExternalTool.LogEventHandler(IndexMsg); it.Start(); it.WaitForExit(); if (it == null || !it.Successfull) { logWindow.MessageCrop(Global.Res("ErrorIndex")); return false; } } } if (settings.cropInput == 2 || settings.encodeInput == 2) { string output = System.IO.Path.ChangeExtension(filename, "dgi"); bool skip = false; if (File.Exists(output) && !settings.deleteIndex) { skip = true; } if (!skip) { it = new IndexTool(settings, filename, IndexType.dgindex); it.OnInfoMsg += new ExternalTool.InfoEventHandler(IndexMsg); it.OnLogMsg += new ExternalTool.LogEventHandler(IndexMsg); it.Start(); it.WaitForExit(); if (!it.Successfull) { logWindow.MessageCrop(Global.Res("ErrorIndex")); return false; } } } if (avo == null || !avo.disableAutocrop) { if (settings.cropInput == 0) { File.WriteAllText(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", "DirectShowSource(\"" + filename + "\")"); } else if (settings.cropInput == 1) { string data = ""; string dlldir = System.IO.Path.GetDirectoryName(settings.ffmsindexPath); if (File.Exists(dlldir + "\\ffms2.dll")) { data = "LoadPlugin(\"" + dlldir + "\\ffms2.dll" + "\")\r\n"; } data += "FFVideoSource(\"" + filename + "\")"; File.WriteAllText(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", data); } else if (settings.cropInput == 2) { string output = System.IO.Path.ChangeExtension(filename, "dgi"); string data = ""; string dlldir = System.IO.Path.GetDirectoryName(settings.dgindexnvPath); if (File.Exists(dlldir + "\\DGDecodeNV.dll")) { data = "LoadPlugin(\"" + dlldir + "\\DGDecodeNV.dll" + "\")\r\n"; } data += "DGSource(\"" + output + "\")"; File.WriteAllText(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", data); } else if (settings.cropInput == 3) { string data = ""; string dlldir = System.IO.Path.GetDirectoryName(settings.lsmashPath); if (File.Exists(dlldir + "\\LSMASHSource.dll")) { data = "LoadPlugin(\"" + dlldir + "\\LSMASHSource.dll" + "\")\r\n"; } data += "LWLibavVideoSource(\"" + filename + "\")"; File.WriteAllText(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", data); } logWindow.MessageCrop(Global.Res("InfoStartCrop")); AutoCrop ac = new AutoCrop(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", settings, ref cropInfo); if (cropInfo.error) { logWindow.MessageCrop(Global.Res("ErrorException") + " " + cropInfo.errorStr); return false; } if (settings.minimizeAutocrop && !settings.manualCrop) { ac.WindowState = FormWindowState.Minimized; } ac.NrFrames = settings.nrFrames; ac.BlackValue = settings.blackValue; ac.ShowDialog(); if (cropInfo.error) { logWindow.MessageCrop(Global.Res("ErrorException") + " " + cropInfo.errorStr); return false; } cropInfo.resizeMethod = settings.resizeMethod; } else { cropInfo.border = avo.manualBorders; cropInfo.borderBottom = avo.borderBottom; cropInfo.borderTop = avo.borderTop; cropInfo.resize = avo.manualResize; cropInfo.resizeX = avo.resizeX; cropInfo.resizeY = avo.resizeY; cropInfo.resizeMethod = avo.resizeMethod; cropInfo.error = false; if (avo.manualCrop) { cropInfo.cropBottom = avo.cropBottom; cropInfo.cropTop = avo.cropTop; } else { cropInfo.cropBottom = 0; cropInfo.cropTop = 0; } } logWindow.MessageCrop(""); logWindow.MessageCrop(Global.ResFormat("InfoCropTop", cropInfo.cropTop)); logWindow.MessageCrop(Global.ResFormat("InfoCropBottom", cropInfo.cropBottom)); if (cropInfo.border) { logWindow.MessageCrop(Global.ResFormat("InfoBorderTop", cropInfo.borderTop)); logWindow.MessageCrop(Global.ResFormat("InfoBorderBottom", cropInfo.borderBottom)); } if (cropInfo.resize) { logWindow.MessageCrop(Global.ResFormat("InfoResize", cropInfo.resizeX, cropInfo.resizeY)); } } foreach (StreamInfo si in demuxedStreamList.streams) { if (si.streamType == StreamType.Video) { if (si.extraFileInfo.GetType() != typeof(VideoFileInfo)) { si.extraFileInfo = new VideoFileInfo(); } ((VideoFileInfo)si.extraFileInfo).fps = fps; ((VideoFileInfo)si.extraFileInfo).length = length; if (frames != "") { ((VideoFileInfo)si.extraFileInfo).frames = frames; } ((VideoFileInfo)si.extraFileInfo).cropInfo = new CropInfo(cropInfo); } } DoPlugin(PluginType.AfterAutoCrop); TitleInfo.SaveStreamInfoFile(demuxedStreamList, settings.workingDir + "\\" + settings.filePrefix + "_streamInfo.xml"); demuxedStreamsWindow.UpdateDemuxedStreams(); return true; } catch (Exception ex) { logWindow.MessageCrop(Global.Res("ErrorException") + " " + ex.Message); return false; } finally { } }
public virtual MediaInfoModel GetMediaInfo(string filename) { if (!_diskProvider.FileExists(filename)) throw new FileNotFoundException("Media file does not exist: " + filename); var mediaInfo = new MediaInfo(); try { logger.Trace("Getting media info from {0}", filename); mediaInfo.Option("ParseSpeed", "0.2"); int open = mediaInfo.Open(filename); if (open != 0) { int width; int height; int videoBitRate; int audioBitRate; int runTime; int streamCount; int audioChannels; string subtitles = mediaInfo.Get(StreamKind.General, 0, "Text_Language_List"); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Width"), out width); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Height"), out height); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int ABindex = aBitRate.IndexOf(" /"); if (ABindex > 0) aBitRate = aBitRate.Remove(ABindex); Int32.TryParse(aBitRate, out audioBitRate); Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); string audioChannelsStr = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)"); int ACindex = audioChannelsStr.IndexOf(" /"); if (ACindex > 0) audioChannelsStr = audioChannelsStr.Remove(ACindex); string audioLanguages = mediaInfo.Get(StreamKind.General, 0, "Audio_Language_List"); decimal videoFrameRate = Decimal.Parse(mediaInfo.Get(StreamKind.Video, 0, "FrameRate")); string audioProfile = mediaInfo.Get(StreamKind.Audio, 0, "Format_Profile"); int APindex = audioProfile.IndexOf(" /"); if (APindex > 0) audioProfile = audioProfile.Remove(APindex); Int32.TryParse(audioChannelsStr, out audioChannels); var mediaInfoModel = new MediaInfoModel { VideoCodec = mediaInfo.Get(StreamKind.Video, 0, "Codec/String"), VideoBitrate = videoBitRate, Height = height, Width = width, AudioFormat = mediaInfo.Get(StreamKind.Audio, 0, "Format"), AudioBitrate = audioBitRate, RunTime = (runTime / 1000), //InSeconds AudioStreamCount = streamCount, AudioChannels = audioChannels, AudioProfile = audioProfile.Trim(), VideoFps = videoFrameRate, AudioLanguages = audioLanguages, Subtitles = subtitles, ScanType = scanType }; mediaInfo.Close(); return mediaInfoModel; } } catch (Exception ex) { logger.ErrorException("Unable to parse media info from file: " + filename, ex); mediaInfo.Close(); } return null; }
public virtual Int32 GetRunTime(string filename) { var mediaInfo = new MediaInfo(); try { logger.Trace("Getting media info from {0}", filename); mediaInfo.Option("ParseSpeed", "0.2"); int open = mediaInfo.Open(filename); if (open != 0) { int runTime; Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); mediaInfo.Close(); return runTime / 1000; //Convert to seconds } } catch (Exception ex) { logger.ErrorException("Unable to parse media info from file: " + filename, ex); mediaInfo.Close(); } return 0; }
private bool IndexCrop() { try { DoPlugin(PluginType.BeforeAutoCrop); string filename = ""; AdvancedVideoOptions avo = null; foreach (StreamInfo si in demuxedStreamList.streams) { if (si.streamType == StreamType.Video) { filename = si.filename; if (si.advancedOptions != null && si.advancedOptions.GetType() == typeof(AdvancedVideoOptions)) { avo = (AdvancedVideoOptions)si.advancedOptions; } break; } } string fps = ""; string resX = ""; string resY = ""; string length = ""; string frames = ""; try { MediaInfoLib.MediaInfo mi2 = new MediaInfoLib.MediaInfo(); mi2.Open(filename); mi2.Option("Complete", "1"); string[] tmpstr = mi2.Inform().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in tmpstr) { logWindow.MessageCrop(s.Trim()); } if (mi2.Count_Get(StreamKind.Video) > 0) { fps = mi2.Get(StreamKind.Video, 0, "FrameRate"); resX = mi2.Get(StreamKind.Video, 0, "Width"); resY = mi2.Get(StreamKind.Video, 0, "Height"); length = mi2.Get(StreamKind.Video, 0, "Duration"); frames = mi2.Get(StreamKind.Video, 0, "FrameCount"); } mi2.Close(); } catch (Exception ex) { logWindow.MessageCrop(Global.Res("ErrorMediaInfo") + " " + ex.Message); return(false); } if (avo != null && avo.disableFps) { logWindow.MessageCrop(Global.Res("InfoManualFps")); fps = avo.fps; length = avo.length; frames = avo.frames; } if (fps == "") { logWindow.MessageCrop(Global.Res("ErrorFramerate")); foreach (StreamInfo si in demuxedStreamList.streams) { if (si.streamType == StreamType.Video) { if (si.desc.Contains("24 /1.001")) { logWindow.MessageCrop(Global.ResFormat("InfoFps", " 23.976")); fps = "23.976"; break; } else if (si.desc.Contains("1080p24 (16:9)")) { logWindow.MessageCrop(Global.ResFormat("InfoFps", " 24")); fps = "24"; break; } // add other framerates here } } if (fps == "") { logWindow.MessageCrop(Global.Res("ErrorNoFramerate")); return(false); } } if (frames == "" || length == "") { logWindow.MessageCrop(Global.Res("InfoFrames")); } CropInfo cropInfo = new CropInfo(); if (!settings.untouchedVideo) { if (settings.cropInput == 1 || settings.encodeInput == 1) { bool skip = false; if (File.Exists(filename + ".ffindex") && !settings.deleteIndex) { skip = true; } if (!skip) { it = new IndexTool(settings, filename, IndexType.ffmsindex); it.OnInfoMsg += new ExternalTool.InfoEventHandler(IndexMsg); it.OnLogMsg += new ExternalTool.LogEventHandler(IndexMsg); it.Start(); it.WaitForExit(); if (it == null || !it.Successfull) { logWindow.MessageCrop(Global.Res("ErrorIndex")); return(false); } } } if (settings.cropInput == 2 || settings.encodeInput == 2) { string output = System.IO.Path.ChangeExtension(filename, "dgi"); bool skip = false; if (File.Exists(output) && !settings.deleteIndex) { skip = true; } if (!skip) { it = new IndexTool(settings, filename, IndexType.dgindex); it.OnInfoMsg += new ExternalTool.InfoEventHandler(IndexMsg); it.OnLogMsg += new ExternalTool.LogEventHandler(IndexMsg); it.Start(); it.WaitForExit(); if (!it.Successfull) { logWindow.MessageCrop(Global.Res("ErrorIndex")); return(false); } } } if (avo == null || !avo.disableAutocrop) { if (settings.cropInput == 0) { File.WriteAllText(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", "DirectShowSource(\"" + filename + "\")"); } else if (settings.cropInput == 1) { string data = ""; string dlldir = System.IO.Path.GetDirectoryName(settings.ffmsindexPath); if (File.Exists(dlldir + "\\ffms2.dll")) { data = "LoadPlugin(\"" + dlldir + "\\ffms2.dll" + "\")\r\n"; } data += "FFVideoSource(\"" + filename + "\")"; File.WriteAllText(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", data); } else if (settings.cropInput == 2) { string output = System.IO.Path.ChangeExtension(filename, "dgi"); string data = ""; string dlldir = System.IO.Path.GetDirectoryName(settings.dgindexnvPath); if (File.Exists(dlldir + "\\DGDecodeNV.dll")) { data = "LoadPlugin(\"" + dlldir + "\\DGDecodeNV.dll" + "\")\r\n"; } data += "DGSource(\"" + output + "\")"; File.WriteAllText(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", data); } logWindow.MessageCrop(Global.Res("InfoStartCrop")); AutoCrop ac = new AutoCrop(settings.workingDir + "\\" + settings.filePrefix + "_cropTemp.avs", settings, ref cropInfo); if (cropInfo.error) { logWindow.MessageCrop(Global.Res("ErrorException") + " " + cropInfo.errorStr); return(false); } if (settings.minimizeAutocrop && !settings.manualCrop) { ac.WindowState = FormWindowState.Minimized; } ac.NrFrames = settings.nrFrames; ac.BlackValue = settings.blackValue; ac.ShowDialog(); if (cropInfo.error) { logWindow.MessageCrop(Global.Res("ErrorException") + " " + cropInfo.errorStr); return(false); } cropInfo.resizeMethod = settings.resizeMethod; } else { cropInfo.border = avo.manualBorders; cropInfo.borderBottom = avo.borderBottom; cropInfo.borderTop = avo.borderTop; cropInfo.resize = avo.manualResize; cropInfo.resizeX = avo.resizeX; cropInfo.resizeY = avo.resizeY; cropInfo.resizeMethod = avo.resizeMethod; cropInfo.error = false; if (avo.manualCrop) { cropInfo.cropBottom = avo.cropBottom; cropInfo.cropTop = avo.cropTop; } else { cropInfo.cropBottom = 0; cropInfo.cropTop = 0; } } logWindow.MessageCrop(""); logWindow.MessageCrop(Global.ResFormat("InfoCropTop", cropInfo.cropTop)); logWindow.MessageCrop(Global.ResFormat("InfoCropBottom", cropInfo.cropBottom)); if (cropInfo.border) { logWindow.MessageCrop(Global.ResFormat("InfoBorderTop", cropInfo.borderTop)); logWindow.MessageCrop(Global.ResFormat("InfoBorderBottom", cropInfo.borderBottom)); } if (cropInfo.resize) { logWindow.MessageCrop(Global.ResFormat("InfoResize", cropInfo.resizeX, cropInfo.resizeY)); } } foreach (StreamInfo si in demuxedStreamList.streams) { if (si.streamType == StreamType.Video) { if (si.extraFileInfo.GetType() != typeof(VideoFileInfo)) { si.extraFileInfo = new VideoFileInfo(); } ((VideoFileInfo)si.extraFileInfo).fps = fps; ((VideoFileInfo)si.extraFileInfo).length = length; ((VideoFileInfo)si.extraFileInfo).frames = frames; ((VideoFileInfo)si.extraFileInfo).cropInfo = new CropInfo(cropInfo); } } DoPlugin(PluginType.AfterAutoCrop); TitleInfo.SaveStreamInfoFile(demuxedStreamList, settings.workingDir + "\\" + settings.filePrefix + "_streamInfo.xml"); demuxedStreamsWindow.UpdateDemuxedStreams(); return(true); } catch (Exception ex) { logWindow.MessageCrop(Global.Res("ErrorException") + " " + ex.Message); return(false); } finally { } }
public string GetMediaInfoString(string VideoName) { StringBuilder info = new StringBuilder(); if (File.Exists(VideoName)) { MediaInfo MI = new MediaInfo(); MI.Open(VideoName); //全局 string container = MI.Get(StreamKind.General, 0, "Format"); string bitRate = MI.Get(StreamKind.General, 0, "BitRate/String"); string duration = MI.Get(StreamKind.General, 0, "Duration/String1"); string fileSize = MI.Get(StreamKind.General, 0, "FileSize/String"); //视频 string v_id = MI.Get(StreamKind.Video, 0, "ID"); string v_format = MI.Get(StreamKind.Video, 0, "Format"); string v_bitRate = MI.Get(StreamKind.Video, 0, "BitRate/String"); string v_size = MI.Get(StreamKind.Video, 0, "StreamSize/String"); string v_width = MI.Get(StreamKind.Video, 0, "Width"); string v_height = MI.Get(StreamKind.Video, 0, "Height"); string v_displayAspectRatio = MI.Get(StreamKind.Video, 0, "DisplayAspectRatio/String"); string v_displayAspectRatio2 = MI.Get(StreamKind.Video, 0, "DisplayAspectRatio"); string v_frameRate = MI.Get(StreamKind.Video, 0, "FrameRate/String"); string v_colorSpace = MI.Get(StreamKind.Video, 0, "ColorSpace"); string v_chromaSubsampling = MI.Get(StreamKind.Video, 0, "ChromaSubsampling"); string v_bitDepth = MI.Get(StreamKind.Video, 0, "BitDepth/String"); string v_scanType = MI.Get(StreamKind.Video, 0, "ScanType/String"); string v_pixelAspectRatio = MI.Get(StreamKind.Video, 0, "PixelAspectRatio"); string v_encodedLibrary = MI.Get(StreamKind.Video, 0, "Encoded_Library/String"); string v_encodingSettings = MI.Get(StreamKind.Video, 0, "Encoded_Library_Settings"); string v_encodedTime = MI.Get(StreamKind.Video, 0, "Encoded_Date"); string v_codecProfile = MI.Get(StreamKind.Video, 0, "Codec_Profile"); string v_frameCount = MI.Get(StreamKind.Video, 0, "FrameCount"); //音频 string a_id = MI.Get(StreamKind.Audio, 0, "ID"); string a_format = MI.Get(StreamKind.Audio, 0, "Format"); string a_bitRate = MI.Get(StreamKind.Audio, 0, "BitRate/String"); string a_samplingRate = MI.Get(StreamKind.Audio, 0, "SamplingRate/String"); string a_channel = MI.Get(StreamKind.Audio, 0, "Channel(s)"); string a_size = MI.Get(StreamKind.Audio, 0, "StreamSize/String"); string audioInfo = MI.Get(StreamKind.Audio, 0, "Inform") + MI.Get(StreamKind.Audio, 1, "Inform") + MI.Get(StreamKind.Audio, 2, "Inform") + MI.Get(StreamKind.Audio, 3, "Inform"); string videoInfo = MI.Get(StreamKind.Video, 0, "Inform"); info = info.Append(Path.GetFileName(VideoName) + "\r\n"); if (!string.IsNullOrEmpty(container)) info.Append("容器:" + container + "\r\n"); if (!string.IsNullOrEmpty(bitRate)) info.Append("总码率:" + bitRate + "\r\n"); if (!string.IsNullOrEmpty(fileSize)) info.Append("大小:" + fileSize + "\r\n"); if (!string.IsNullOrEmpty(duration)) info.Append("时长:" + duration + "\r\n"); if (!string.IsNullOrEmpty(v_format)) info.Append("\r\n" + "视频(" + v_id + "):" + v_format + "\r\n"); if (!string.IsNullOrEmpty(v_codecProfile)) info.Append("Profile:" + v_codecProfile + "\r\n"); if (!string.IsNullOrEmpty(v_bitRate)) info.Append("码率:" + v_bitRate + "\r\n"); if (!string.IsNullOrEmpty(v_size)) info.Append("文件大小:" + v_size + "\r\n"); if (!string.IsNullOrEmpty(v_width) && !string.IsNullOrEmpty(v_height)) info.Append("分辨率:" + v_width + "x" + v_height + "\r\n"); if (!string.IsNullOrEmpty(v_displayAspectRatio) && !string.IsNullOrEmpty(v_displayAspectRatio2)) info.Append("画面比例:" + v_displayAspectRatio + "(" + v_displayAspectRatio2 + ")" + "\r\n"); if (!string.IsNullOrEmpty(v_pixelAspectRatio)) info.Append("像素宽高比:" + v_pixelAspectRatio + "\r\n"); if (!string.IsNullOrEmpty(v_frameRate)) info.Append("帧率:" + v_frameRate + "\r\n"); if (!string.IsNullOrEmpty(v_colorSpace)) info.Append("色彩空间:" + v_colorSpace + "\r\n"); if (!string.IsNullOrEmpty(v_chromaSubsampling)) info.Append("色度抽样:" + v_chromaSubsampling + "\r\n"); if (!string.IsNullOrEmpty(v_bitDepth)) info.Append("位深度:" + v_bitDepth + "\r\n"); if (!string.IsNullOrEmpty(v_scanType)) info.Append("扫描方式:" + v_scanType + "\r\n"); if (!string.IsNullOrEmpty(v_encodedTime)) info.Append("编码时间:" + v_encodedTime + "\r\n"); if (!string.IsNullOrEmpty(v_frameCount)) info.Append("总帧数:" + v_frameCount + "\r\n"); if (!string.IsNullOrEmpty(v_encodedLibrary)) info.Append("编码库:" + v_encodedLibrary + "\r\n"); if (!string.IsNullOrEmpty(v_encodingSettings)) info.Append("编码设置:" + v_encodingSettings + "\r\n"); if (!string.IsNullOrEmpty(a_format)) info.Append("\r\n" + "音频(" + a_id + "):" + a_format + "\r\n"); if (!string.IsNullOrEmpty(a_size)) info.Append("大小:" + a_size + "\r\n"); if (!string.IsNullOrEmpty(a_bitRate)) info.Append("码率:" + a_bitRate + "\r\n"); if (!string.IsNullOrEmpty(a_samplingRate)) info.Append("采样率:" + a_samplingRate + "\r\n"); if (!string.IsNullOrEmpty(a_channel)) info.Append("声道数:" + a_channel + "\r\n"); info.Append("\r\n====详细信息====\r\n" + videoInfo + "\r\n" + audioInfo + "\r\n"); MI.Close(); } else info.Append("文件不存在、非有效文件或者文件夹 无视频信息"); return info.ToString(); }
private void CheckInputFile(Media mf) { using (FFMpegWrapper ff = new FFMpegWrapper(mf.FullPath)) { inputFileStreams = ff.GetStreamInfo(); } MediaInfo mi = new MediaInfo(); try { mi.Open(mf.FullPath); mi.Option("Complete"); string miOutput = mi.Inform(); Regex format_lxf = new Regex("Format\\s*:\\s*LXF"); if (format_lxf.Match(miOutput).Success) { string[] miOutputLines = miOutput.Split('\n'); Regex vitc = new Regex("ATC_VITC"); Regex re = new Regex("Time code of first frame\\s*:[\\s]\\d{2}:\\d{2}:\\d{2}:\\d{2}"); for (int i = 0; i < miOutputLines.Length; i++) { if (vitc.Match(miOutputLines[i]).Success && i >= 1) { Match m_tcs = re.Match(miOutputLines[i - 1]); if (m_tcs.Success) { Regex reg_tc = new Regex("\\d{2}:\\d{2}:\\d{2}:\\d{2}"); Match m_tc = reg_tc.Match(m_tcs.Value); if (m_tc.Success) { DestMedia.TCStart = reg_tc.Match(m_tc.Value).Value.SMPTETimecodeToTimeSpan(); if (DestMedia.TCPlay == TimeSpan.Zero) DestMedia.TCPlay = DestMedia.TCStart; break; } } } } } Regex format_mxf = new Regex(@"Format\s*:\s*MXF"); if (format_mxf.Match(miOutput).Success) { string[] miOutputLines = miOutput.Split('\n'); Regex mxf_tc = new Regex(@"MXF TC"); Regex re = new Regex(@"Time code of first frame\s*:[\s]\d{2}:\d{2}:\d{2}:\d{2}"); for (int i = 0; i < miOutputLines.Length; i++) { Match mxf_match = mxf_tc.Match(miOutputLines[i]); if (mxf_match.Success && i < miOutputLines.Length - 1) { Regex reg_tc = new Regex(@"\d{2}:\d{2}:\d{2}:\d{2}"); Match m_tc = re.Match(miOutputLines[i + 1]); if (m_tc.Success) { DestMedia.TCStart = reg_tc.Match(m_tc.Value).Value.SMPTETimecodeToTimeSpan(); if (DestMedia.TCPlay == TimeSpan.Zero) DestMedia.TCPlay = DestMedia.TCStart; break; } } } } } finally { mi.Close(); } }
/// <summary> /// Closes the underlaying MediaInfo instance and releases all resources. /// </summary> public void Close() { _mediaInfo.Close(); _isValid = false; }
private MediaInfoData GetMediaInfo(string location, MediaType mediaType) { Logger.ReportInfo("Getting media info from " + location); MediaInfoLib.MediaInfo mediaInfo = new MediaInfoLib.MediaInfo(); mediaInfo.Option("ParseSpeed", "0.2"); int i = mediaInfo.Open(location); MediaInfoData mediaInfoData = null; if (i != 0) { string subtitles = mediaInfo.Get(StreamKind.General, 0, "Text_Language_List"); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); int width; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Width"), out width); int height; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Height"), out height); int videoBitRate; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); int audioBitRate; string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int ABindex = aBitRate.IndexOf(" /"); if (ABindex > 0) aBitRate = aBitRate.Remove(ABindex); Int32.TryParse(aBitRate, out audioBitRate); int runTime; Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); int streamCount; Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); string audioChannels = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)"); int ACindex = audioChannels.IndexOf(" /"); if (ACindex > 0) audioChannels = audioChannels.Remove(ACindex); string audioLanguages = mediaInfo.Get(StreamKind.General, 0, "Audio_Language_List"); string videoFrameRate = mediaInfo.Get(StreamKind.Video, 0, "FrameRate"); string audioProfile = mediaInfo.Get(StreamKind.Audio, 0, "Format_Profile"); int APindex = audioProfile.IndexOf(" /"); if (APindex > 0) audioProfile = audioProfile.Remove(APindex); mediaInfoData = new MediaInfoData { PluginData = new MediaInfoData.MIData() { VideoCodec = mediaInfo.Get(StreamKind.Video, 0, "Codec/String"), VideoBitRate = videoBitRate, //MI.Get(StreamKind.Video, 0, "DisplayAspectRatio")), Height = height, Width = width, //MI.Get(StreamKind.Video, 0, "Duration/String3")), AudioFormat = mediaInfo.Get(StreamKind.Audio, 0, "Format"), AudioBitRate = audioBitRate, RunTime = (runTime / 60000), AudioStreamCount = streamCount, AudioChannelCount = audioChannels.Trim(), AudioProfile = audioProfile.Trim(), VideoFPS = videoFrameRate, AudioLanguages = audioLanguages, Subtitles = subtitles, ScanType = scanType } }; } else { Logger.ReportInfo("Could not extract media information from " + location); } if (mediaType == MediaType.DVD && i != 0) { mediaInfo.Close(); location = location.Replace("0.IFO", "1.vob"); Logger.ReportInfo("Getting additional media info from " + location); mediaInfo.Option("ParseSpeed", "0.0"); i = mediaInfo.Open(location); if (i != 0) { int videoBitRate; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); int audioBitRate; string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int ABindex = aBitRate.IndexOf(" /"); if (ABindex > 0) aBitRate = aBitRate.Remove(ABindex); Int32.TryParse(aBitRate, out audioBitRate); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); mediaInfoData.PluginData.AudioBitRate = audioBitRate; mediaInfoData.PluginData.VideoBitRate = videoBitRate; mediaInfoData.PluginData.ScanType = scanType; } else { Logger.ReportInfo("Could not extract additional media info from " + location); } } mediaInfo.Close(); return mediaInfoData; }
static void Main(string[] Args) { String ToDisplay; MediaInfo MI = new MediaInfo(); ToDisplay = MI.Option("Info_Version", "0.7.0.0;MediaInfoDLL_Example_CS;0.7.0.0"); if (ToDisplay.Length == 0) { Console.Out.WriteLine("MediaInfo.Dll: this version of the DLL is not compatible"); return; } //Information about MediaInfo ToDisplay += "\r\n\r\nInfo_Parameters\r\n"; ToDisplay += MI.Option("Info_Parameters"); ToDisplay += "\r\n\r\nInfo_Capacities\r\n"; ToDisplay += MI.Option("Info_Capacities"); ToDisplay += "\r\n\r\nInfo_Codecs\r\n"; ToDisplay += MI.Option("Info_Codecs"); //An example of how to use the library ToDisplay += "\r\n\r\nOpen\r\n"; String File_Name; if (Args.Length == 0) File_Name = "Example.ogg"; else File_Name = Args[0]; MI.Open(File_Name); ToDisplay += "\r\n\r\nInform with Complete=false\r\n"; MI.Option("Complete"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nInform with Complete=true\r\n"; MI.Option("Complete", "1"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nCustom Inform\r\n"; MI.Option("Inform", "General;File size is %FileSize% bytes"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n"; ToDisplay += MI.Get(0, 0, "FileSize"); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n"; ToDisplay += MI.Get(0, 0, 46); ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n"; ToDisplay += MI.Count_Get(StreamKind.Audio); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n"; ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount"); ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n"; ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount"); ToDisplay += "\r\n\r\nClose\r\n"; MI.Close(); //Displaying the text Console.Out.WriteLine(ToDisplay); Console.Out.WriteLine("Press a key to close window."); Console.Read(); }
private void media_info() { try { MediaInfo MI = new MediaInfo(); MI.Open(inputfilename); if (MI.Count_Get(StreamKind.Video) > 0) { InputWidth = Convert.ToInt32(MI.Get(StreamKind.Video, 0, "Width")); InputHeight = Convert.ToInt32(MI.Get(StreamKind.Video, 0, "Height")); frames = Convert.ToInt32(MI.Get(StreamKind.Video, 0, "FrameCount")); videoFormat = MI.Get(StreamKind.Video, 0, "Format"); videoFormatVersion = MI.Get(StreamKind.Video, 0, "Format_Version"); videoFormatProfile = MI.Get(StreamKind.Video, 0, "Format_Profile"); } if (MI.Count_Get(StreamKind.Audio) > 0) { audioFormat = MI.Get(StreamKind.Audio, 0, "Format"); audioFormatVersion = MI.Get(StreamKind.Audio, 0, "Format_Version"); audioFormatProfile = MI.Get(StreamKind.Audio, 0, "Format_Profile"); audioSamplingRate = Convert.ToInt32(MI.Get(StreamKind.Audio, 0, "SamplingRate")); } MI.Close(); } catch (System.Exception excep) { MessageBox.Show("An error occured while opening the file. \r\nThe following error message was reported: \r\n" + excep.Message, "Error"); } }
private void ReadDirectory() { // if a folder then read all media files // append all the durations and save in Duration if (Directory.Exists(Location)) { // get largest file FileCollection = GetFilesToProcess(Location); List <FileInfo> listFileInfo = new List <FileInfo>(); foreach (string fp in FileCollection) { listFileInfo.Add(new FileInfo(fp)); } // Subtitles, Format: DVD Video using VTS_01_0.IFO string[] ifo = Directory.GetFiles(Location, "VTS_01_0.IFO", SearchOption.AllDirectories); if (ifo.Length == 1) // CHECK IF A DVD { this.MediaTypeChoice = MediaType.MediaDisc; MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); this.DiscType = TDMakerLib.SourceType.DVD; mi.Open(ifo[0]); // most prolly this will be: DVD Video this.Overall.Format = mi.Get(StreamKind.General, 0, "Format"); int subCount = 0; int.TryParse(mi.Get(StreamKind.Text, 0, "StreamCount"), out subCount); if (subCount > 0) { List <string> langs = new List <string>(); for (int i = 0; i < subCount; i++) { string lang = mi.Get(StreamKind.Text, i, "Language/String"); if (!string.IsNullOrEmpty(lang)) { // System.Windows.Forms.MessageBox.Show(lang); if (!langs.Contains(lang)) { langs.Add(lang); } } } StringBuilder sbLangs = new StringBuilder(); for (int i = 0; i < langs.Count; i++) { sbLangs.Append(langs[i]); if (i < langs.Count - 1) { sbLangs.Append(", "); } } this.Overall.Subtitles = sbLangs.ToString(); } // close ifo file mi.Close(); // AFTER IDENTIFIED THE MEDIA TYPE IS A DVD listFileInfo.RemoveAll(x => x.Length < 1000000000); } // Set Media Type bool allAudio = Adapter.MediaIsAudio(FileCollection); if (allAudio) { this.MediaTypeChoice = MediaType.MusicAudioAlbum; } if (FileCollection.Count > 0) { foreach (FileInfo fi in listFileInfo) { this.AddMedia(new MediaFile(fi.FullName, this.Source)); } this.Overall = new MediaFile(FileSystemHelper.GetLargestFilePathFromDir(Location), this.Source); // Set Overall File Name this.Overall.FileName = Path.GetFileName(Location); if (Overall.FileName.ToUpper().Equals("VIDEO_TS")) { Overall.FileName = Path.GetFileName(Path.GetDirectoryName(Location)); } if (string.IsNullOrEmpty(Title)) { this.Title = this.Overall.FileName; } } // DVD Video // Combined Duration and File Size if (MediaTypeChoice == MediaType.MediaDisc) { if (listFileInfo.Count > 0) { long dura = 0; double size = 0; foreach (FileInfo fiVob in listFileInfo) { MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); mi.Open(fiVob.FullName); string temp = mi.Get(0, 0, "Duration"); if (!string.IsNullOrEmpty(temp)) { long d = 0; long.TryParse(temp, out d); dura += d; } // we are interested in combined file size only for VOB files // thats why we dont calculate FileSize in FileInfo while determining largest file double sz = 0; double.TryParse(mi.Get(0, 0, "FileSize"), out sz); size += sz; // close vob file mi.Close(); } this.Overall.FileSize = size; // override any previous file size this.Overall.FileSizeString = string.Format("{0} MiB", (this.Overall.FileSize / 1024.0 / 1024.0).ToString("0.00")); this.Overall.Duration = dura; this.Overall.DurationString2 = Program.GetDurationString(dura); } } } // if Location is a directory }
/// <summary> /// Gets the movie runtime in seconds /// </summary> /// <param name="movie">The movie.</param> /// <returns></returns> public int GetMovieRuntime(string movie) { var MI = new MediaInfo(); MI.Open(movie); decimal dd = Math.Floor(decimal.Parse(MI.Get(StreamKind.Video, 0, "Duration")) / 1000); MI.Close(); return Convert.ToInt32(dd); }
private object ReplaceChapters(string file) { //Remove the chapters var info = new FileInfo(file); String newFileName = CustomOutputName.Replace("%O", Path.GetFileNameWithoutExtension(info.FullName)) + ".mkv"; Char q = Convert.ToChar(34); String newpath = q + workDir + "\\" + newFileName + q; String oldpath = q + info.FullName + q; String args = "-o " + newpath + " --no-chapters --compression -1:none " + oldpath; var prcinfo = new ProcessStartInfo(); var prc = new Process(); prcinfo.FileName = MKVMergePath; prcinfo.Arguments = args; prcinfo.RedirectStandardOutput = true; prcinfo.RedirectStandardError = true; prcinfo.CreateNoWindow = !ShowConsole; prcinfo.UseShellExecute = false; prc.StartInfo = prcinfo; prc.Start(); string str; while ((str = prc.StandardOutput.ReadLine()) != null) { //Check for Cancellation if (chapterizeWorker.CancellationPending) { if (!prc.WaitForExit(500)) { prc.Kill(); Thread.Sleep(1000); } return workDir + "\\" + newFileName; } //End Check if (str == "") { continue; } if (str.Contains("Progress")) { Progress = Convert.ToInt32(parseProgress(str)) / 2; } else if (str.Contains("Error")) { MessageBox.Show(null, str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } //Add the new var info2 = new FileInfo(workDir + "\\" + newFileName); var MI = new MediaInfo(); MI.Open(info2.FullName); string cpath; if (ChapterMode == ChapterModes.ChapterSet) { WriteLog("Creating chapterfile: " + workDir + "\\chapters.xml"); cpath = CreateChapterFile(CustomChapterSet, workDir + "\\chapters.xml"); } else if (ChapterMode == ChapterModes.File) { WriteLog("Using pre-set chapterfile: " + CustomChapterFile); cpath = CustomChapterFile; } else { WriteLog("Creating chapterfile: " + workDir + "\\chapters.xml"); cpath = CreateChapterFile(CreateChapterSet(GetMovieRuntime(info.FullName), ChapterInterval), workDir + "\\chapters.xml"); } string newFileName2 = CustomOutputName.Replace("%O", Path.GetFileNameWithoutExtension(info2.FullName)) + ".mkv"; newpath = q + workDir + "\\" + newFileName2 + q; oldpath = q + info2.FullName + q; args = "-o " + newpath + " --chapters " + q + cpath + q + " --compression -1:none " + oldpath; prcinfo.Arguments = args; prc.StartInfo = prcinfo; prc.Start(); while ((str = prc.StandardOutput.ReadLine()) != null) { //Check for Cancellation if (chapterizeWorker.CancellationPending) { MI.Close(); if (!prc.WaitForExit(500)) { prc.Kill(); Thread.Sleep(1000); } if (ChapterMode != ChapterModes.File) { File.Delete(cpath); } return workDir + "\\" + newFileName; } //End Check if (str != "") { if (str.Contains("Progress")) { Progress = 50 + Convert.ToInt32(parseProgress(str)) / 2; } else if (str.Contains("Error")) { MessageBox.Show(null, str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } if (ChapterMode != ChapterModes.File) { File.Delete(cpath); } File.Delete(workDir + "\\" + newFileName); File.Move(workDir + "\\" + newFileName2, workDir + "\\" + newFileName); return new FileInfo(workDir + "\\" + newFileName); }
public static Media Convert(string filename, IFile file) { if (file == null) { return(null); } try { lock (_lock) { Media m = new Media(); Part p = new Part(); Thread mediaInfoThread = new Thread(() => { if (minstance == null) { minstance = new MediaInfoLib.MediaInfo(); } if (minstance.Open(filename) == 0) { return; //it's a boolean response. } Stream VideoStream = null; m.Duration = p.Duration = minstance.GetLong(StreamKind.General, 0, "Duration"); p.Size = minstance.GetLong(StreamKind.General, 0, "FileSize"); int brate = minstance.GetInt(StreamKind.General, 0, "BitRate"); if (brate != 0) { m.Bitrate = (int)Math.Round(brate / 1000F); } int chaptercount = minstance.GetInt(StreamKind.General, 0, "MenuCount"); m.Chaptered = chaptercount > 0; int video_count = minstance.GetInt(StreamKind.General, 0, "VideoCount"); int audio_count = minstance.GetInt(StreamKind.General, 0, "AudioCount"); int text_count = minstance.GetInt(StreamKind.General, 0, "TextCount"); m.Container = p.Container = TranslateContainer(minstance.Get(StreamKind.General, 0, "Format")); string codid = minstance.Get(StreamKind.General, 0, "CodecID"); if (!string.IsNullOrEmpty(codid) && (codid.Trim().ToLower() == "qt")) { m.Container = p.Container = "mov"; } List <Stream> streams = new List <Stream>(); byte iidx = 0; if (video_count > 0) { for (int x = 0; x < video_count; x++) { Stream s = TranslateVideoStream(minstance, x); if (x == 0) { VideoStream = s; m.Width = s.Width; m.Height = s.Height; if (m.Height != 0) { if (m.Width != 0) { m.VideoResolution = GetResolution(m.Width, m.Height); m.AspectRatio = GetAspectRatio(m.Width, m.Height, s.PA); } } if (s.FrameRate != 0) { float fr = System.Convert.ToSingle(s.FrameRate); string frs = ((int)Math.Round(fr)).ToString(CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(s.ScanType)) { if (s.ScanType.ToLower().Contains("int")) { frs += "i"; } else { frs += "p"; } } else { frs += "p"; } if ((frs == "25p") || (frs == "25i")) { frs = "PAL"; } else if ((frs == "30p") || (frs == "30i")) { frs = "NTSC"; } m.VideoFrameRate = frs; } m.VideoCodec = string.IsNullOrEmpty(s.CodecID) ? s.Codec : s.CodecID; if (m.Duration != 0 && s.Duration != 0) { if (s.Duration > m.Duration) { m.Duration = p.Duration = s.Duration; } } if (video_count == 1) { s.Default = 0; s.Forced = 0; } } if (m.Container != "mkv") { s.Index = iidx; iidx++; } streams.Add(s); } } int totalsoundrate = 0; if (audio_count > 0) { for (int x = 0; x < audio_count; x++) { Stream s = TranslateAudioStream(minstance, x); if ((s.Codec == "adpcm") && (p.Container == "flv")) { s.Codec = "adpcm_swf"; } if (x == 0) { m.AudioCodec = string.IsNullOrEmpty(s.CodecID) ? s.Codec : s.CodecID; m.AudioChannels = s.Channels; if (m.Duration != 0 && s.Duration != 0) { if (s.Duration > m.Duration) { m.Duration = p.Duration = s.Duration; } } if (audio_count == 1) { s.Default = 0; s.Forced = 0; } } if (s.Bitrate != 0) { totalsoundrate += s.Bitrate; } if (m.Container != "mkv") { s.Index = iidx; iidx++; } streams.Add(s); } } if ((VideoStream != null) && VideoStream.Bitrate == 0 && m.Bitrate != 0) { VideoStream.Bitrate = m.Bitrate - totalsoundrate; } if (text_count > 0) { for (int x = 0; x < audio_count; x++) { Stream s = TranslateTextStream(minstance, x); streams.Add(s); if (text_count == 1) { s.Default = 0; s.Forced = 0; } if (m.Container != "mkv") { s.Index = iidx; iidx++; } } } m.Parts = new List <Part> { p }; bool over = false; if (m.Container == "mkv") { byte val = byte.MaxValue; foreach (Stream s in streams.OrderBy(a => a.Index).Skip(1)) { if (s.Index <= 0) { over = true; break; } s.idx = s.Index; if (s.idx < val) { val = s.idx; } } if (val != 0 && !over) { foreach (Stream s in streams) { s.idx = (byte)(s.idx - val); s.Index = s.idx; } } else if (over) { byte xx = 0; foreach (Stream s in streams) { s.idx = xx++; s.Index = s.idx; } } streams = streams.OrderBy(a => a.idx).ToList(); } p.Streams = streams; }); mediaInfoThread.Start(); bool finished = mediaInfoThread.Join(TimeSpan.FromMinutes(5)); //TODO Move Timeout to settings if (!finished) { try { mediaInfoThread.Abort(); } catch { /*ignored*/ } try { CloseMediaInfo(); } catch { /*ignored*/ } return(null); } if ((p.Container == "mp4") || (p.Container == "mov")) { p.Has64bitOffsets = 0; p.OptimizedForStreaming = 0; m.OptimizedForStreaming = 0; byte[] buffer = new byte[8]; FileSystemResult <System.IO.Stream> fsr = file.OpenRead(); if (fsr == null || fsr.Status != NutzCode.CloudFileSystem.Status.Ok) { return(null); } System.IO.Stream fs = fsr.Result; fs.Read(buffer, 0, 4); int siz = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; fs.Seek(siz, SeekOrigin.Begin); fs.Read(buffer, 0, 8); if ((buffer[4] == 'f') && (buffer[5] == 'r') && (buffer[6] == 'e') && (buffer[7] == 'e')) { siz = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3] - 8); fs.Seek(siz, SeekOrigin.Current); fs.Read(buffer, 0, 8); } if ((buffer[4] == 'm') && (buffer[5] == 'o') && (buffer[6] == 'o') && (buffer[7] == 'v')) { p.OptimizedForStreaming = 1; m.OptimizedForStreaming = 1; siz = ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]) - 8; buffer = new byte[siz]; fs.Read(buffer, 0, siz); if (!FindInBuffer("trak", 0, siz, buffer, out int opos, out int oposmax)) { return(m); } if (!FindInBuffer("mdia", opos, oposmax, buffer, out opos, out oposmax)) { return(m); } if (!FindInBuffer("minf", opos, oposmax, buffer, out opos, out oposmax)) { return(m); } if (!FindInBuffer("stbl", opos, oposmax, buffer, out opos, out oposmax)) { return(m); } if (!FindInBuffer("co64", opos, oposmax, buffer, out opos, out oposmax)) { return(m); } p.Has64bitOffsets = 1; } } return(m); } } finally { minstance?.Close(); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); } }
public MediaInfoModel GetMediaInfo(string filename) { if (!_diskProvider.FileExists(filename)) throw new FileNotFoundException("Media file does not exist: " + filename); MediaInfoLib.MediaInfo mediaInfo = null; try { mediaInfo = new MediaInfoLib.MediaInfo(); _logger.Trace("Getting media info from {0}", filename); mediaInfo.Option("ParseSpeed", "0.2"); int open = mediaInfo.Open(filename); if (open != 0) { int width; int height; int videoBitRate; int audioBitRate; int audioRuntime; int videoRuntime; int generalRuntime; int streamCount; int audioChannels; decimal videoFrameRate; string subtitles = mediaInfo.Get(StreamKind.General, 0, "Text_Language_List"); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Width"), out width); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Height"), out height); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); Decimal.TryParse(mediaInfo.Get(StreamKind.Video, 0, "FrameRate"), out videoFrameRate); //Runtime Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "PlayTime"), out videoRuntime); Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "PlayTime"), out audioRuntime); Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out generalRuntime); string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int aBindex = aBitRate.IndexOf(" /", StringComparison.InvariantCultureIgnoreCase); if (aBindex > 0) aBitRate = aBitRate.Remove(aBindex); Int32.TryParse(aBitRate, out audioBitRate); Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); string audioChannelsStr = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)"); int aCindex = audioChannelsStr.IndexOf(" /", StringComparison.InvariantCultureIgnoreCase); if (aCindex > 0) audioChannelsStr = audioChannelsStr.Remove(aCindex); string audioLanguages = mediaInfo.Get(StreamKind.General, 0, "Audio_Language_List"); string audioProfile = mediaInfo.Get(StreamKind.Audio, 0, "Format_Profile"); int aPindex = audioProfile.IndexOf(" /", StringComparison.InvariantCultureIgnoreCase); if (aPindex > 0) audioProfile = audioProfile.Remove(aPindex); Int32.TryParse(audioChannelsStr, out audioChannels); var mediaInfoModel = new MediaInfoModel { VideoCodec = mediaInfo.Get(StreamKind.Video, 0, "Codec/String"), VideoBitrate = videoBitRate, Height = height, Width = width, AudioFormat = mediaInfo.Get(StreamKind.Audio, 0, "Format"), AudioBitrate = audioBitRate, RunTime = GetBestRuntime(audioRuntime, videoRuntime, generalRuntime), AudioStreamCount = streamCount, AudioChannels = audioChannels, AudioProfile = audioProfile.Trim(), VideoFps = videoFrameRate, AudioLanguages = audioLanguages, Subtitles = subtitles, ScanType = scanType }; return mediaInfoModel; } } catch (DllNotFoundException ex) { _logger.ErrorException("mediainfo is required but was not found", ex); throw; } catch (Exception ex) { _logger.ErrorException("Unable to parse media info from file: " + filename, ex); } finally { if (mediaInfo != null) { mediaInfo.Close(); } } return null; }
private void ReadDirectory() { // if a folder then read all media files // append all the durations and save in Duration if (Directory.Exists(Location)) { // get largest file FileCollection = GetFilesToProcess(Location); List<FileInfo> listFileInfo = new List<FileInfo>(); foreach (string fp in FileCollection) { listFileInfo.Add(new FileInfo(fp)); } // Subtitles, Format: DVD Video using VTS_01_0.IFO string[] ifo = Directory.GetFiles(Location, "VTS_01_0.IFO", SearchOption.AllDirectories); if (ifo.Length == 1) // CHECK IF A DVD { this.MediaTypeChoice = MediaType.MediaDisc; MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); this.DiscType = TDMakerLib.SourceType.DVD; mi.Open(ifo[0]); // most prolly this will be: DVD Video this.Overall.Format = mi.Get(StreamKind.General, 0, "Format"); int subCount = 0; int.TryParse(mi.Get(StreamKind.Text, 0, "StreamCount"), out subCount); if (subCount > 0) { List<string> langs = new List<string>(); for (int i = 0; i < subCount; i++) { string lang = mi.Get(StreamKind.Text, i, "Language/String"); if (!string.IsNullOrEmpty(lang)) { // System.Windows.Forms.MessageBox.Show(lang); if (!langs.Contains(lang)) langs.Add(lang); } } StringBuilder sbLangs = new StringBuilder(); for (int i = 0; i < langs.Count; i++) { sbLangs.Append(langs[i]); if (i < langs.Count - 1) sbLangs.Append(", "); } this.Overall.Subtitles = sbLangs.ToString(); } // close ifo file mi.Close(); // AFTER IDENTIFIED THE MEDIA TYPE IS A DVD listFileInfo.RemoveAll(x => x.Length < 1000000000); } // Set Media Type bool allAudio = Adapter.MediaIsAudio(FileCollection); if (allAudio) { this.MediaTypeChoice = MediaType.MusicAudioAlbum; } if (FileCollection.Count > 0) { foreach (FileInfo fi in listFileInfo) { this.AddMedia(new MediaFile(fi.FullName, this.Source)); } this.Overall = new MediaFile(FileSystemHelper.GetLargestFilePathFromDir(Location), this.Source); // Set Overall File Name this.Overall.FileName = Path.GetFileName(Location); if (Overall.FileName.ToUpper().Equals("VIDEO_TS")) Overall.FileName = Path.GetFileName(Path.GetDirectoryName(Location)); if (string.IsNullOrEmpty(Title)) this.Title = this.Overall.FileName; } // DVD Video // Combined Duration and File Size if (MediaTypeChoice == MediaType.MediaDisc) { if (listFileInfo.Count > 0) { long dura = 0; double size = 0; foreach (FileInfo fiVob in listFileInfo) { MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); mi.Open(fiVob.FullName); string temp = mi.Get(0, 0, "Duration"); if (!string.IsNullOrEmpty(temp)) { long d = 0; long.TryParse(temp, out d); dura += d; } // we are interested in combined file size only for VOB files // thats why we dont calculate FileSize in FileInfo while determining largest file double sz = 0; double.TryParse(mi.Get(0, 0, "FileSize"), out sz); size += sz; // close vob file mi.Close(); } this.Overall.FileSize = size; // override any previous file size this.Overall.FileSizeString = string.Format("{0} MiB", (this.Overall.FileSize / 1024.0 / 1024.0).ToString("0.00")); this.Overall.Duration = dura; this.Overall.DurationString2 = Program.GetDurationString(dura); } } } // if Location is a directory }
public string MediaInfo(string VideoName) { string info = "无视频信息"; if (File.Exists(VideoName)) { MediaInfo MI = new MediaInfo(); MI.Open(VideoName); //全局 string container = MI.Get(StreamKind.General, 0, "Format"); string bitrate = MI.Get(StreamKind.General, 0, "BitRate/String"); string duration = MI.Get(StreamKind.General, 0, "Duration/String1"); string fileSize = MI.Get(StreamKind.General, 0, "FileSize/String"); //视频 string vid = MI.Get(StreamKind.Video, 0, "ID"); string video = MI.Get(StreamKind.Video, 0, "Format"); string vBitRate = MI.Get(StreamKind.Video, 0, "BitRate/String"); string vSize = MI.Get(StreamKind.Video, 0, "StreamSize/String"); string width = MI.Get(StreamKind.Video, 0, "Width"); string height = MI.Get(StreamKind.Video, 0, "Height"); string risplayAspectRatio = MI.Get(StreamKind.Video, 0, "DisplayAspectRatio/String"); string risplayAspectRatio2 = MI.Get(StreamKind.Video, 0, "DisplayAspectRatio"); string frameRate = MI.Get(StreamKind.Video, 0, "FrameRate/String"); string bitDepth = MI.Get(StreamKind.Video, 0, "BitDepth/String"); string pixelAspectRatio = MI.Get(StreamKind.Video, 0, "PixelAspectRatio"); string encodedLibrary = MI.Get(StreamKind.Video, 0, "Encoded_Library"); string encodeTime = MI.Get(StreamKind.Video, 0, "Encoded_Date"); string codecProfile = MI.Get(StreamKind.Video, 0, "Codec_Profile"); string frameCount = MI.Get(StreamKind.Video, 0, "FrameCount"); //音频 string aid = MI.Get(StreamKind.Audio, 0, "ID"); string audio = MI.Get(StreamKind.Audio, 0, "Format"); string aBitRate = MI.Get(StreamKind.Audio, 0, "BitRate/String"); string samplingRate = MI.Get(StreamKind.Audio, 0, "SamplingRate/String"); string channel = MI.Get(StreamKind.Audio, 0, "Channel(s)"); string aSize = MI.Get(StreamKind.Audio, 0, "StreamSize/String"); string audioInfo = MI.Get(StreamKind.Audio, 0, "Inform") + MI.Get(StreamKind.Audio, 1, "Inform") + MI.Get(StreamKind.Audio, 2, "Inform") + MI.Get(StreamKind.Audio, 3, "Inform"); string videoInfo = MI.Get(StreamKind.Video, 0, "Inform"); info = Path.GetFileName(VideoName) + "\r\n" + "容器:" + container + "\r\n" + "总码率:" + bitrate + "\r\n" + "大小:" + fileSize + "\r\n" + "时长:" + duration + "\r\n" + "\r\n" + "视频(" + vid + "):" + video + "\r\n" + "码率:" + vBitRate + "\r\n" + "大小:" + vSize + "\r\n" + "分辨率:" + width + "x" + height + "\r\n" + "宽高比:" + risplayAspectRatio + "(" + risplayAspectRatio2 + ")" + "\r\n" + "帧率:" + frameRate + "\r\n" + "位深度:" + bitDepth + "\r\n" + "像素宽高比:" + pixelAspectRatio + "\r\n" + "编码库:" + encodedLibrary + "\r\n" + "Profile:" + codecProfile + "\r\n" + "编码时间:" + encodeTime + "\r\n" + "总帧数:" + frameCount + "\r\n" + "\r\n" + "音频(" + aid + "):" + audio + "\r\n" + "大小:" + aSize + "\r\n" + "码率:" + aBitRate + "\r\n" + "采样率:" + samplingRate + "\r\n" + "声道数:" + channel + "\r\n" + "\r\n====详细信息====\r\n" + videoInfo + "\r\n" + audioInfo + "\r\n" ; MI.Close(); } return info; }
private void dataGridView1_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach(String sFullPath in files) { String sFileExtension = System.IO.Path.GetExtension(sFullPath).ToLower(); if (sFileExtension == ".ac3" || sFileExtension == ".ddp" || sFileExtension == ".dts" || sFileExtension == ".dtshd" || sFileExtension == ".flac" || sFileExtension == ".wav") { MediaInfo MI = new MediaInfo(); AudioFile af = new AudioFile(); MI.Open(sFullPath); af.bAllowToConvert = true; af.sBitDepth = MI.Get(StreamKind.Audio, 0, "BitDepth", InfoKind.Text, InfoKind.Name); af.sBitrate = MI.Get(StreamKind.Audio, 0, "BitRate", InfoKind.Text, InfoKind.Name); af.sChannels = MI.Get(StreamKind.Audio, 0, "Channels", InfoKind.Text, InfoKind.Name); af.sCodec = MI.Get(StreamKind.Audio, 0, "Codec", InfoKind.Text, InfoKind.Name); af.sDuration = MI.Get(StreamKind.Audio, 0, "Duration/String", InfoKind.Text, InfoKind.Name); af.sFileName = System.IO.Path.GetFileNameWithoutExtension(sFullPath); af.sFullFileName = System.IO.Path.GetFileName(sFullPath); af.sPath = System.IO.Path.GetDirectoryName(sFullPath); af.sSamplingRate = MI.Get(StreamKind.Audio, 0, "SamplingRate", InfoKind.Text, InfoKind.Name); af.sDescription = af.sCodec + " - " + af.sChannels + " Channel - " + Convert.ToInt32(af.sBitrate) / 1000 + " Kbps - " + af.sSamplingRate + " Hz - " + af.sDuration; listAudioFiles.Add(af); MI.Close(); dt.Rows.Add(af.bAllowToConvert, af.sFullFileName, af.sDescription); buttonStartConverting.Enabled = true; } } }
private Int32 GetDuration(string location) { MediaInfoLib.MediaInfo mediaInfo = new MediaInfoLib.MediaInfo(); mediaInfo.Option("ParseSpeed", "0.3"); int i = mediaInfo.Open(location); int runTime = 0; if (i != 0) { Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); } mediaInfo.Close(); return runTime; }
public static void Main(string[] args) { String ToDisplay = ""; MediaInfo MI = new MediaInfo(); //An example of how to use the library ToDisplay += "\r\n\r\nOpen\r\n"; MI.Open(args[0]); ToDisplay += "\r\n\r\nInform with Complete=false\r\n"; MI.Option("Complete"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nInform with Complete=true\r\n"; MI.Option("Complete", "1"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nCustom Inform\r\n"; MI.Option("Inform", "General;File size is %FileSize% bytes"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n"; ToDisplay += MI.Get(0, 0, "FileSize"); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n"; ToDisplay += MI.Get(0, 0, 46); ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n"; ToDisplay += MI.Count_Get(StreamKind.Audio); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n"; ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount"); ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n"; ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount"); ToDisplay += "\r\n\r\nClose\r\n"; MI.Close(); Console.WriteLine(ToDisplay); }
/// <summary> /// Reads a media file and creates a MediaFile object /// </summary> /// <param name="fp">File Path of the Media File</param> /// <returns>MediaFile object</returns> public void ReadFile() { this.Source = Source; if (File.Exists(FilePath)) { //********************* //* General //********************* //System.Debug.WriteLine("Current Dir1: " + System.Environment.CurrentDirectory); //System.Environment.CurrentDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); //System.Debug.WriteLine("Current Dir2: " + System.Environment.CurrentDirectory); MediaInfoLib.MediaInfo MI = null; try { Debug.WriteLine("Loading MediaInfo.dll"); MI = new MediaInfoLib.MediaInfo(); Debug.WriteLine("Loaded MediaInfo.dll"); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } if (MI != null) { Debug.WriteLine(string.Format("MediaInfo Opening {0}", FilePath)); MI.Open(FilePath); Debug.WriteLine(string.Format("MediaInfo Opened {0}", FilePath)); MI.Option("Complete"); this.Summary = MI.Inform(); MI.Option("Complete", "1"); this.SummaryComplete = MI.Inform(); if (Program.IsUNIX) { Debug.WriteLine(string.Format("MediaInfo Summary Length: {0}", this.Summary.Length.ToString())); Debug.WriteLine(string.Format("MediaInfo Summary: {0}", this.Summary)); } // Format Info if (string.IsNullOrEmpty(this.Format)) { this.Format = MI.Get(StreamKind.General, 0, "Format"); } this.FormatInfo = MI.Get(StreamKind.General, 0, "Format/Info"); // this.FileName = mMI.Get(0, 0, "FileName"); if (0 == this.FileSize) { double sz; double.TryParse(MI.Get(0, 0, "FileSize"), out sz); this.FileSize = sz; } if (string.IsNullOrEmpty(this.FileSizeString)) { this.FileSizeString = string.Format("{0} MiB", (this.FileSize / 1024.0 / 1024.0).ToString("0.00")); } // Duration if (string.IsNullOrEmpty(this.DurationString2)) { this.DurationString2 = MI.Get(0, 0, "Duration/String2"); } if (this.Duration == 0.0) { double dura = 0.0; double.TryParse(MI.Get(0, 0, "Duration"), out dura); this.Duration = dura; this.SegmentDuration = dura; } if (string.IsNullOrEmpty(this.DurationString3)) { this.DurationString3 = MI.Get(0, 0, "Duration/String3"); } this.BitrateOverall = MI.Get(StreamKind.General, 0, "OverallBitRate/String"); this.EncodedApplication = MI.Get(StreamKind.General, 0, "Encoded_Application"); this.EncodedDate = MI.Get(StreamKind.General, 0, "Encoded_Date"); if (string.IsNullOrEmpty(this.Subtitles)) { StringBuilder sbSubs = new StringBuilder(); int subCount = 0; int.TryParse(MI.Get(StreamKind.Text, 0, "StreamCount"), out subCount); if (subCount > 0) { StringBuilder sbLang = new StringBuilder(); for (int i = 0; i < subCount; i++) { string lang = MI.Get(StreamKind.Text, i, "Language/String"); if (!string.IsNullOrEmpty(lang)) { // System.Windows.Forms.MessageBox.Show(lang); sbLang.Append(lang); if (i < subCount - 1) { sbLang.Append(", "); } } } if (!string.IsNullOrEmpty(sbLang.ToString())) { sbSubs.Append(sbLang.ToString()); } else { sbSubs.Append("N/A"); } } else { sbSubs.Append("None"); } this.Subtitles = sbSubs.ToString(); } //********************* //* Video //********************* int videoCount; int.TryParse(MI.Get(StreamKind.General, 0, "VideoCount"), out videoCount); this.HasVideo = videoCount > 0; this.Video.Format = MI.Get(StreamKind.Video, 0, "Format"); this.Video.FormatVersion = MI.Get(StreamKind.Video, 0, "Format_Version"); if (Path.GetExtension(this.FilePath).ToLower().Equals(".mkv")) { this.Video.Codec = MI.Get(StreamKind.Video, 0, "Encoded_Library"); } this.Video.EncodedLibrarySettings = MI.Get(StreamKind.Video, 0, "Encoded_Library_Settings"); this.Video.DisplayAspectRatio = MI.Get(StreamKind.Video, 0, "DisplayAspectRatio/String"); if (string.IsNullOrEmpty(this.Video.Codec)) { this.Video.Codec = MI.Get(StreamKind.Video, 0, "CodecID/Hint"); } if (string.IsNullOrEmpty(this.Video.Codec)) { this.Video.Codec = MI.Get(StreamKind.Video, 0, "CodecID"); } this.Video.Bitrate = MI.Get(StreamKind.Video, 0, "BitRate/String"); this.Video.Standard = MI.Get(StreamKind.Video, 0, "Standard");; this.Video.FrameRate = MI.Get(StreamKind.Video, 0, "FrameRate/String"); this.Video.ScanType = MI.Get(StreamKind.Video, 0, "ScanType/String"); this.Video.Height = MI.Get(StreamKind.Video, 0, "Height"); this.Video.Width = MI.Get(StreamKind.Video, 0, "Width"); this.Video.Resolution = string.Format("{0}x{1}", this.Video.Width, this.Video.Height); this.Video.BitsPerPixelXFrame = MI.Get(StreamKind.Video, 0, "Bits-(Pixel*Frame)"); //********************* //* Audio //********************* int audioCount; int.TryParse(MI.Get(StreamKind.General, 0, "AudioCount"), out audioCount); this.HasAudio = audioCount > 0; for (int id = 0; id < audioCount; id++) { AudioInfo ai = new AudioInfo(id); ai.Format = MI.Get(StreamKind.Audio, id, "Format"); ai.FormatVersion = MI.Get(StreamKind.Audio, 0, "Format_Version"); ai.FormatProfile = MI.Get(StreamKind.Audio, 0, "Format_Profile"); ai.Codec = MI.Get(StreamKind.Audio, 0, "CodecID/Hint"); if (string.IsNullOrEmpty(ai.Codec)) { ai.Codec = MI.Get(StreamKind.Audio, 0, "CodecID/Info"); } if (string.IsNullOrEmpty(ai.Codec)) { ai.Codec = MI.Get(StreamKind.Audio, 0, "CodecID"); } ai.Bitrate = MI.Get(StreamKind.Audio, id, "BitRate/String"); ai.BitrateMode = MI.Get(StreamKind.Audio, id, "BitRate_Mode/String"); ai.Channels = MI.Get(StreamKind.Audio, id, "Channel(s)/String"); ai.SamplingRate = MI.Get(StreamKind.Audio, id, "SamplingRate/String"); ai.Resolution = MI.Get(StreamKind.Audio, id, "Resolution/String"); this.Audio.Add(ai); } MI.Close(); //// Analyse Audio only files using TagLib //if (this.HasAudio && !this.HasVideo) //{ // TagLib.File f = TagLib.File.Create(this.FilePath); // this.TagLibFile = f; //} } } }
private MediaInfoData GetMediaInfo(string location, MediaType mediaType) { Logger.ReportInfo("Getting media info from " + location); MediaInfoLib.MediaInfo mediaInfo = new MediaInfoLib.MediaInfo(); mediaInfo.Option("ParseSpeed", "0.2"); int i = mediaInfo.Open(location); MediaInfoData mediaInfoData = null; if (i != 0) { string subtitles = mediaInfo.Get(StreamKind.General, 0, "Text_Language_List"); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); int width; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Width"), out width); int height; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Height"), out height); int videoBitRate; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); int audioBitRate; string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int ABindex = aBitRate.IndexOf(" /"); if (ABindex > 0) { aBitRate = aBitRate.Remove(ABindex); } Int32.TryParse(aBitRate, out audioBitRate); int runTime; Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); int streamCount; Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); string audioChannels = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)"); int ACindex = audioChannels.IndexOf(" /"); if (ACindex > 0) { audioChannels = audioChannels.Remove(ACindex); } string audioLanguages = mediaInfo.Get(StreamKind.General, 0, "Audio_Language_List"); string videoFrameRate = mediaInfo.Get(StreamKind.Video, 0, "FrameRate"); string audioProfile = mediaInfo.Get(StreamKind.Audio, 0, "Format_Profile"); int APindex = audioProfile.IndexOf(" /"); if (APindex > 0) { audioProfile = audioProfile.Remove(APindex); } mediaInfoData = new MediaInfoData { PluginData = new MediaInfoData.MIData() { VideoCodec = mediaInfo.Get(StreamKind.Video, 0, "Codec/String"), VideoBitRate = videoBitRate, //MI.Get(StreamKind.Video, 0, "DisplayAspectRatio")), Height = height, Width = width, //MI.Get(StreamKind.Video, 0, "Duration/String3")), AudioFormat = mediaInfo.Get(StreamKind.Audio, 0, "Format"), AudioBitRate = audioBitRate, RunTime = (runTime / 60000), AudioStreamCount = streamCount, AudioChannelCount = audioChannels.Trim(), AudioProfile = audioProfile.Trim(), VideoFPS = videoFrameRate, AudioLanguages = audioLanguages, Subtitles = subtitles, ScanType = scanType } }; } else { Logger.ReportInfo("Could not extract media information from " + location); } if (mediaType == MediaType.DVD && i != 0) { mediaInfo.Close(); location = location.Replace("0.IFO", "1.vob"); Logger.ReportInfo("Getting additional media info from " + location); mediaInfo.Option("ParseSpeed", "0.0"); i = mediaInfo.Open(location); if (i != 0) { int videoBitRate; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); int audioBitRate; string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int ABindex = aBitRate.IndexOf(" /"); if (ABindex > 0) { aBitRate = aBitRate.Remove(ABindex); } Int32.TryParse(aBitRate, out audioBitRate); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); mediaInfoData.PluginData.AudioBitRate = audioBitRate; mediaInfoData.PluginData.VideoBitRate = videoBitRate; mediaInfoData.PluginData.ScanType = scanType; } else { Logger.ReportInfo("Could not extract additional media info from " + location); } } mediaInfo.Close(); return(mediaInfoData); }
public MediaInfoModel GetMediaInfo(string filename) { if (!_diskProvider.FileExists(filename)) { throw new FileNotFoundException("Media file does not exist: " + filename); } MediaInfoLib.MediaInfo mediaInfo = null; try { mediaInfo = new MediaInfoLib.MediaInfo(); _logger.Debug("Getting media info from {0}", filename); mediaInfo.Option("ParseSpeed", "0.2"); int open = mediaInfo.Open(filename); if (open != 0) { int width; int height; int videoBitRate; int audioBitRate; int audioRuntime; int videoRuntime; int generalRuntime; int streamCount; int audioChannels; decimal videoFrameRate; string subtitles = mediaInfo.Get(StreamKind.General, 0, "Text_Language_List"); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Width"), out width); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Height"), out height); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); Decimal.TryParse(mediaInfo.Get(StreamKind.Video, 0, "FrameRate"), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out videoFrameRate); //Runtime Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "PlayTime"), out videoRuntime); Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "PlayTime"), out audioRuntime); Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out generalRuntime); string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int aBindex = aBitRate.IndexOf(" /", StringComparison.InvariantCultureIgnoreCase); if (aBindex > 0) { aBitRate = aBitRate.Remove(aBindex); } Int32.TryParse(aBitRate, out audioBitRate); Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); string audioChannelsStr = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)"); int aCindex = audioChannelsStr.IndexOf(" /", StringComparison.InvariantCultureIgnoreCase); if (aCindex > 0) { audioChannelsStr = audioChannelsStr.Remove(aCindex); } string audioLanguages = mediaInfo.Get(StreamKind.General, 0, "Audio_Language_List"); string audioProfile = mediaInfo.Get(StreamKind.Audio, 0, "Format_Profile"); int aPindex = audioProfile.IndexOf(" /", StringComparison.InvariantCultureIgnoreCase); if (aPindex > 0) { audioProfile = audioProfile.Remove(aPindex); } Int32.TryParse(audioChannelsStr, out audioChannels); var mediaInfoModel = new MediaInfoModel { VideoCodec = mediaInfo.Get(StreamKind.Video, 0, "Codec/String"), VideoBitrate = videoBitRate, Height = height, Width = width, AudioFormat = mediaInfo.Get(StreamKind.Audio, 0, "Format"), AudioBitrate = audioBitRate, RunTime = GetBestRuntime(audioRuntime, videoRuntime, generalRuntime), AudioStreamCount = streamCount, AudioChannels = audioChannels, AudioProfile = audioProfile.Trim(), VideoFps = videoFrameRate, AudioLanguages = audioLanguages, Subtitles = subtitles, ScanType = scanType }; return(mediaInfoModel); } } catch (DllNotFoundException ex) { _logger.ErrorException("mediainfo is required but was not found", ex); } catch (Exception ex) { _logger.ErrorException("Unable to parse media info from file: " + filename, ex); } finally { if (mediaInfo != null) { mediaInfo.Close(); } } return(null); }
/// <summary> /// Reads a media file and creates a MediaFile object /// </summary> /// <param name="fp">File Path of the Media File</param> /// <returns>MediaFile object</returns> public void ReadFile() { this.Source = Source; if (File.Exists(FilePath)) { //********************* //* General //********************* //System.Debug.WriteLine("Current Dir1: " + System.Environment.CurrentDirectory); //System.Environment.CurrentDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); //System.Debug.WriteLine("Current Dir2: " + System.Environment.CurrentDirectory); MediaInfoLib.MediaInfo MI = null; try { Debug.WriteLine("Loading MediaInfo.dll"); MI = new MediaInfoLib.MediaInfo(); Debug.WriteLine("Loaded MediaInfo.dll"); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } if (MI != null) { Debug.WriteLine(string.Format("MediaInfo Opening {0}", FilePath)); MI.Open(FilePath); Debug.WriteLine(string.Format("MediaInfo Opened {0}", FilePath)); MI.Option("Complete"); this.Summary = MI.Inform(); MI.Option("Complete", "1"); this.SummaryComplete = MI.Inform(); if (Program.IsUNIX) { Debug.WriteLine(string.Format("MediaInfo Summary Length: {0}", this.Summary.Length.ToString())); Debug.WriteLine(string.Format("MediaInfo Summary: {0}", this.Summary)); } // Format Info if (string.IsNullOrEmpty(this.Format)) this.Format = MI.Get(StreamKind.General, 0, "Format"); this.FormatInfo = MI.Get(StreamKind.General, 0, "Format/Info"); // this.FileName = mMI.Get(0, 0, "FileName"); if (0 == this.FileSize) { double sz; double.TryParse(MI.Get(0, 0, "FileSize"), out sz); this.FileSize = sz; } if (string.IsNullOrEmpty(this.FileSizeString)) { this.FileSizeString = string.Format("{0} MiB", (this.FileSize / 1024.0 / 1024.0).ToString("0.00")); } // Duration if (string.IsNullOrEmpty(this.DurationString2)) this.DurationString2 = MI.Get(0, 0, "Duration/String2"); if (this.Duration == 0.0) { double dura = 0.0; double.TryParse(MI.Get(0, 0, "Duration"), out dura); this.Duration = dura; this.SegmentDuration = dura; } if (string.IsNullOrEmpty(this.DurationString3)) this.DurationString3 = MI.Get(0, 0, "Duration/String3"); this.BitrateOverall = MI.Get(StreamKind.General, 0, "OverallBitRate/String"); this.EncodedApplication = MI.Get(StreamKind.General, 0, "Encoded_Application"); this.EncodedDate = MI.Get(StreamKind.General, 0, "Encoded_Date"); if (string.IsNullOrEmpty(this.Subtitles)) { StringBuilder sbSubs = new StringBuilder(); int subCount = 0; int.TryParse(MI.Get(StreamKind.Text, 0, "StreamCount"), out subCount); if (subCount > 0) { StringBuilder sbLang = new StringBuilder(); for (int i = 0; i < subCount; i++) { string lang = MI.Get(StreamKind.Text, i, "Language/String"); if (!string.IsNullOrEmpty(lang)) { // System.Windows.Forms.MessageBox.Show(lang); sbLang.Append(lang); if (i < subCount - 1) sbLang.Append(", "); } } if (!string.IsNullOrEmpty(sbLang.ToString())) { sbSubs.Append(sbLang.ToString()); } else { sbSubs.Append("N/A"); } } else { sbSubs.Append("None"); } this.Subtitles = sbSubs.ToString(); } //********************* //* Video //********************* int videoCount; int.TryParse(MI.Get(StreamKind.General, 0, "VideoCount"), out videoCount); this.HasVideo = videoCount > 0; this.Video.Format = MI.Get(StreamKind.Video, 0, "Format"); this.Video.FormatVersion = MI.Get(StreamKind.Video, 0, "Format_Version"); if (Path.GetExtension(this.FilePath).ToLower().Equals(".mkv")) { this.Video.Codec = MI.Get(StreamKind.Video, 0, "Encoded_Library"); } this.Video.EncodedLibrarySettings = MI.Get(StreamKind.Video, 0, "Encoded_Library_Settings"); this.Video.DisplayAspectRatio = MI.Get(StreamKind.Video, 0, "DisplayAspectRatio/String"); if (string.IsNullOrEmpty(this.Video.Codec)) this.Video.Codec = MI.Get(StreamKind.Video, 0, "CodecID/Hint"); if (string.IsNullOrEmpty(this.Video.Codec)) this.Video.Codec = MI.Get(StreamKind.Video, 0, "CodecID"); this.Video.Bitrate = MI.Get(StreamKind.Video, 0, "BitRate/String"); this.Video.Standard = MI.Get(StreamKind.Video, 0, "Standard"); ; this.Video.FrameRate = MI.Get(StreamKind.Video, 0, "FrameRate/String"); this.Video.ScanType = MI.Get(StreamKind.Video, 0, "ScanType/String"); this.Video.Height = MI.Get(StreamKind.Video, 0, "Height"); this.Video.Width = MI.Get(StreamKind.Video, 0, "Width"); this.Video.Resolution = string.Format("{0}x{1}", this.Video.Width, this.Video.Height); this.Video.BitsPerPixelXFrame = MI.Get(StreamKind.Video, 0, "Bits-(Pixel*Frame)"); //********************* //* Audio //********************* int audioCount; int.TryParse(MI.Get(StreamKind.General, 0, "AudioCount"), out audioCount); this.HasAudio = audioCount > 0; for (int id = 0; id < audioCount; id++) { AudioInfo ai = new AudioInfo(id); ai.Format = MI.Get(StreamKind.Audio, id, "Format"); ai.FormatVersion = MI.Get(StreamKind.Audio, 0, "Format_Version"); ai.FormatProfile = MI.Get(StreamKind.Audio, 0, "Format_Profile"); ai.Codec = MI.Get(StreamKind.Audio, 0, "CodecID/Hint"); if (string.IsNullOrEmpty(ai.Codec)) ai.Codec = MI.Get(StreamKind.Audio, 0, "CodecID/Info"); if (string.IsNullOrEmpty(ai.Codec)) ai.Codec = MI.Get(StreamKind.Audio, 0, "CodecID"); ai.Bitrate = MI.Get(StreamKind.Audio, id, "BitRate/String"); ai.BitrateMode = MI.Get(StreamKind.Audio, id, "BitRate_Mode/String"); ai.Channels = MI.Get(StreamKind.Audio, id, "Channel(s)/String"); ai.SamplingRate = MI.Get(StreamKind.Audio, id, "SamplingRate/String"); ai.Resolution = MI.Get(StreamKind.Audio, id, "Resolution/String"); this.Audio.Add(ai); } MI.Close(); //// Analyse Audio only files using TagLib //if (this.HasAudio && !this.HasVideo) //{ // TagLib.File f = TagLib.File.Create(this.FilePath); // this.TagLibFile = f; //} } } }
public MediaInfoModel GetMediaInfo(string filename) { if (!_diskProvider.FileExists(filename)) { throw new FileNotFoundException("Media file does not exist: " + filename); } var mediaInfo = new MediaInfoLib.MediaInfo(); try { _logger.Trace("Getting media info from {0}", filename); mediaInfo.Option("ParseSpeed", "0.2"); int open = mediaInfo.Open(filename); if (open != 0) { int width; int height; int videoBitRate; int audioBitRate; int runTime; int streamCount; int audioChannels; string subtitles = mediaInfo.Get(StreamKind.General, 0, "Text_Language_List"); string scanType = mediaInfo.Get(StreamKind.Video, 0, "ScanType"); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Width"), out width); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Height"), out height); Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); string aBitRate = mediaInfo.Get(StreamKind.Audio, 0, "BitRate"); int ABindex = aBitRate.IndexOf(" /"); if (ABindex > 0) { aBitRate = aBitRate.Remove(ABindex); } Int32.TryParse(aBitRate, out audioBitRate); Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); string audioChannelsStr = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)"); int ACindex = audioChannelsStr.IndexOf(" /"); if (ACindex > 0) { audioChannelsStr = audioChannelsStr.Remove(ACindex); } string audioLanguages = mediaInfo.Get(StreamKind.General, 0, "Audio_Language_List"); decimal videoFrameRate = Decimal.Parse(mediaInfo.Get(StreamKind.Video, 0, "FrameRate")); string audioProfile = mediaInfo.Get(StreamKind.Audio, 0, "Format_Profile"); int APindex = audioProfile.IndexOf(" /"); if (APindex > 0) { audioProfile = audioProfile.Remove(APindex); } Int32.TryParse(audioChannelsStr, out audioChannels); var mediaInfoModel = new MediaInfoModel { VideoCodec = mediaInfo.Get(StreamKind.Video, 0, "Codec/String"), VideoBitrate = videoBitRate, Height = height, Width = width, AudioFormat = mediaInfo.Get(StreamKind.Audio, 0, "Format"), AudioBitrate = audioBitRate, RunTime = (runTime / 1000), //InSeconds AudioStreamCount = streamCount, AudioChannels = audioChannels, AudioProfile = audioProfile.Trim(), VideoFps = videoFrameRate, AudioLanguages = audioLanguages, Subtitles = subtitles, ScanType = scanType }; mediaInfo.Close(); return(mediaInfoModel); } } catch (Exception ex) { _logger.ErrorException("Unable to parse media info from file: " + filename, ex); mediaInfo.Close(); } return(null); }
public TimeSpan GetRunTime(string filename) { MediaInfoLib.MediaInfo mediaInfo = null; try { mediaInfo = new MediaInfoLib.MediaInfo(); _logger.Trace("Getting media info from {0}", filename); mediaInfo.Option("ParseSpeed", "0.2"); int open = mediaInfo.Open(filename); if (open != 0) { int runTime; Int32.TryParse(mediaInfo.Get(StreamKind.General, 0, "PlayTime"), out runTime); mediaInfo.Close(); return TimeSpan.FromMilliseconds(runTime); } } catch (Exception ex) { _logger.ErrorException("Unable to parse media info from file: " + filename, ex); } finally { if (mediaInfo != null) { mediaInfo.Close(); } } return new TimeSpan(); }
private void Form1_Load(object sender, System.EventArgs e) { //Test if version of DLL is compatible : 3rd argument is "version of DLL tested;Your application name;Your application version" String ToDisplay; MediaInfo MI = new MediaInfo(); ToDisplay = MI.Option("Info_Version", "0.7.0.0;MediaInfoDLL_Example_CS;0.7.0.0"); if (ToDisplay.Length == 0) { richTextBox1.Text = "MediaInfo.Dll: this version of the DLL is not compatible"; return; } //Information about MediaInfo ToDisplay += "\r\n\r\nInfo_Parameters\r\n"; ToDisplay += MI.Option("Info_Parameters"); ToDisplay += "\r\n\r\nInfo_Capacities\r\n"; ToDisplay += MI.Option("Info_Capacities"); ToDisplay += "\r\n\r\nInfo_Codecs\r\n"; ToDisplay += MI.Option("Info_Codecs"); //An example of how to use the library ToDisplay += "\r\n\r\nOpen\r\n"; MI.Open("Example.ogg"); ToDisplay += "\r\n\r\nInform with Complete=false\r\n"; MI.Option("Complete"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nInform with Complete=true\r\n"; MI.Option("Complete", "1"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nCustom Inform\r\n"; MI.Option("Inform", "General;File size is %FileSize% bytes"); ToDisplay += MI.Inform(); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n"; ToDisplay += MI.Get(0, 0, "FileSize"); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n"; ToDisplay += MI.Get(0, 0, 46); ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n"; ToDisplay += MI.Count_Get(StreamKind.Audio); ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n"; ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount"); ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n"; ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount"); ToDisplay += "\r\n\r\nClose\r\n"; MI.Close(); //Example with a stream //ToDisplay+="\r\n"+ExampleWithStream()+"\r\n"; //Displaying the text richTextBox1.Text = ToDisplay; }
private MediaInfoData GetMediaInfo(string location) { Logger.ReportInfo("getting media info from " + location); MediaInfo mediaInfo = new MediaInfo(); int i = mediaInfo.Open(location); MediaInfoData mediaInfoData = null; if (i != 0) { int width; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Width"), out width); int height; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "Height"), out height); int videoBitRate; Int32.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate"), out videoBitRate); int audioBitRate; Int32.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "BitRate"), out audioBitRate); mediaInfoData = new MediaInfoData { VideoCodec = mediaInfo.Get(StreamKind.Video, 0, "CodecID/Hint"), VideoBitRate = videoBitRate, //MI.Get(StreamKind.Video, 0, "DisplayAspectRatio")), Height = height, Width = width, //MI.Get(StreamKind.Video, 0, "Duration/String3")), AudioFormat = mediaInfo.Get(StreamKind.Audio, 0, "Format"), AudioBitRate = audioBitRate }; } else { Logger.ReportInfo("Could not extract media information from " + location); } mediaInfo.Close(); return mediaInfoData; }