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 AboutBox() { InitializeComponent(); this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; StringBuilder sbDesc = new StringBuilder(); sbDesc.AppendLine(AssemblyDescription); sbDesc.AppendLine(); sbDesc.AppendLine("Running from:"); sbDesc.AppendLine(Application.StartupPath); sbDesc.AppendLine(); sbDesc.AppendLine("Settings file:"); sbDesc.AppendLine(Program.AppConf.XMLSettingsFile); MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); sbDesc.AppendLine(); sbDesc.AppendLine("Using:"); sbDesc.AppendLine(mi.Option("Info_Version") + " from http://sourceforge.net/projects/mediainfo"); sbDesc.AppendLine("Movie Thumbnailer v200808a:"); this.textBoxDescription.Text = sbDesc.ToString(); uclUpdate.CheckUpdate(CheckUpdate); }
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; }
internal static bool ScanConstructedArrayAndImportMediaFiles (IMLSection moviesSection, IMLSection tvSection, IMLSection musicSection, ref IList<string> extensionsToIgnore, string[] filmLocations, string[] tvShowsLocations, string[] musicLocations, string[] videoExtensions, string[] audioExtensions, IEnumerable<string> combinedSceneTags, ICollection<FileInfo> filesToImport, MediaInfo mediaInfo, string pluginPath, IEnumerable<string> videoExtensionsCommon) { if (!Settings.UpdateMediaSectionOnEachImportedItem) ImportingEngineHelpers.BeginUpdatingSections(); if ( !ImportFilesInArray(moviesSection, tvSection, musicSection, ref extensionsToIgnore, filmLocations, tvShowsLocations, musicLocations, videoExtensions, audioExtensions, combinedSceneTags, filesToImport, mediaInfo, pluginPath, videoExtensionsCommon) ) return false; if (!Settings.UpdateMediaSectionOnEachImportedItem) ImportingEngineHelpers.EndUpdatingSections(); return true; }
internal static bool PopulateMediaSection (FileInfo file, IMLSection moviesSection, IMLSection tvSection, IMLSection musicSection, IEnumerable<string> videoexts, int audioDuration, string filesize, MediaInfo mi, DirectoryInfo parent, string filecodec, bool isVideo, bool isAudio, int videoDuration, string fileName, string parentName, IEnumerable<string> combinedSceneTags) { if (String.IsNullOrEmpty(filecodec) && !isVideo && !isAudio) return true; //Debugger.LogMessageToFile(Environment.NewLine + "The file " + file.Name + //" has been detected as a valid media file." + Environment.NewLine + //" Proceeding to media type recognition..."); if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, null)) return false; ImportVideo(file, moviesSection, tvSection, videoexts, filesize, mi, parent, filecodec, isVideo, videoDuration, fileName, parentName, combinedSceneTags); if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, null)) return false; ImportAudio(file, musicSection, audioDuration, filesize, mi, filecodec, isAudio, fileName); return true; }
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 string[] ExtractInfo(string path) { MediaInfo MI = new MediaInfo(); MI.Open(path); string[] returnInfo = new string[5]; //File name 0 returnInfo[0] = MI.Get(0, 0, "FileName"); //Size 1 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); returnInfo[1] = sizeInMBStr + " MB"; //Date created 2 returnInfo[2] = 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); //Performer 3 returnInfo[3] = MI.Get(0, 0, "Performer"); //Length 4 returnInfo[4] = MI.Get(0, 0, "Duration/String3").Substring(0, MI.Get(0, 0, "Duration/String3").LastIndexOf(".")); return returnInfo; }
internal static bool DetectAndImportMultipartMovie(IMLSection moviesSection, MediaInfo mediaInfo, bool isUNC, FileSystemInfo dir, string externalID, ArrayList filesInDir, string[] videoexts, int videosCount) { videosCount = CountVideosInDirectory(videoexts, videosCount, filesInDir); if (!Settings.EnableMediaDetection || videosCount <= 1 || videosCount >= 4) return false; MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "Detecting film parts..."); int parts = 0; string locationTag = String.Empty; int count = 1; foreach (FileInfo file in filesInDir) { var fileIsVideo = DetermineIfFileIsVideoByExtensionMatching(videoexts, file); parts = DetectMoviePart(parts, mediaInfo, videosCount, fileIsVideo, file, isUNC, ref count, ref locationTag, ref externalID); } return OnMultiplePartsDetectionAddToMoviesSection(moviesSection, locationTag, externalID, parts, dir); }
private static Stream TranslateTextStream(MediaInfoLib.MediaInfo m, int num) { Stream s = new Stream { Id = m.GetInt(StreamKind.Text, num, "UniqueID"), CodecID = m.Get(StreamKind.Text, num, "CodecID"), StreamType = 3 }; string title = m.Get(StreamKind.Text, num, "Title"); if (!string.IsNullOrEmpty(title)) { s.Title = title; } else if (!string.IsNullOrEmpty(title = m.Get(StreamKind.Text, num, "Subtitle"))) { s.Title = title; } string lang = m.Get(StreamKind.Text, num, "Language/String3"); if (!string.IsNullOrEmpty(lang)) { s.LanguageCode = PostTranslateCode3(lang); } string lan = PostTranslateLan(GetLanguageFromCode3(lang, m.Get(StreamKind.Text, num, "Language/String1"))); if (!string.IsNullOrEmpty(lan)) { s.Language = lan; } s.Index = m.GetByte(StreamKind.Text, num, "ID"); s.Format = s.Codec = GetFormat(m.Get(StreamKind.Text, num, "CodecID"), m.Get(StreamKind.Text, num, "Format")); string def = m.Get(StreamKind.Text, num, "Default"); if (!string.IsNullOrEmpty(def)) { if (def.ToLower(CultureInfo.InvariantCulture) == "yes") { s.Default = 1; } } string forced = m.Get(StreamKind.Text, num, "Forced"); if (!string.IsNullOrEmpty(forced)) { if (forced.ToLower(CultureInfo.InvariantCulture) == "yes") { s.Forced = 1; } } return(s); }
private static void GetCodecs(MediaInfo mediaInfo, out string videoCodec, out string audioCodec, out string filecodec) { filecodec = GetFileCodec(mediaInfo); videoCodec = GetVideoCodec(mediaInfo); audioCodec = GetAudioCodec(mediaInfo); }
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); }
private static void ImportAudio(FileInfo file, IMLSection musicSection, int audioDuration, string filesize, MediaInfo mi, string filecodec, bool isAudio, string fileName) { if (!MediaSectionPopulatorHelpers.ProceedToImportAudioTrack(file, isAudio)) return; AddToMusicSection_ImportMediaInfo(file, musicSection, audioDuration, filesize, mi, filecodec, fileName); }
private static int GetInt(this MediaInfoLib.MediaInfo mi, StreamKind kind, int number, string par) { string dta = mi.Get(kind, number, par); if (int.TryParse(dta, out int val)) { return(val); } return(0); }
public Audio(MediaInfo MI, int i) { this.codec = MI.Get(StreamKind.Audio, i, "Codec/String"); //this.profile = MI.Get(StreamKind.Audio, i, "Codec_Profile"); this.bitrate_mode = MI.Get(StreamKind.Audio, i, "BitRate_Mode/String"); this.bitrate = MI.Get(StreamKind.Audio, i, "BitRate/String"); this.sampling_frequency = MI.Get(StreamKind.Audio, i, "SamplingRate"); this.channels = MI.Get(StreamKind.Audio, i, "Channel(s)"); this.delay = MI.Get(StreamKind.Audio, i, "Video_Delay"); }
private static long GetLong(this MediaInfoLib.MediaInfo mi, StreamKind kind, int number, string par) { string dta = mi.Get(kind, number, par); if (long.TryParse(dta, out long val)) { return(val); } return(0); }
private static byte GetByte(this MediaInfoLib.MediaInfo mi, StreamKind kind, int number, string par) { string dta = mi.Get(kind, number, par); if (byte.TryParse(dta, out byte val)) { return(val); } return(0); }
private static float GetFloat(this MediaInfoLib.MediaInfo mi, StreamKind kind, int number, string par) { string dta = mi.Get(kind, number, par); if (float.TryParse(dta, out float val)) { return(val); } return(0.0F); }
/// <summary> /// Reads a media file details. /// </summary> /// <param name="fileName">File name to be read.</param> /// <returns>Media file details.</returns> public virtual MediaFileInfo Read(string fileName) { var FileInfo = new MediaFileInfo(); var MI = new MediaInfoLib.MediaInfo(); var s = MI.Option("Info_Version", Constants.INFO_VERSION_VALUE); if (s.Length == 0) { throw new Exception(string.Format("MediaInfo.Dll: this version of the DLL is not compatible. Version found: {0}", s)); } MI.Open(fileName); ReadProperties(MI, FileInfo.GeneralInfo, StreamKind.General, 0); int iNbVideoStreams = int.Parse(MI.Get(StreamKind.Video, 0, "StreamCount")); int iNbAudioStreams = int.Parse(MI.Get(StreamKind.Audio, 0, "StreamCount")); int iNbTextStreams = int.Parse(MI.Get(StreamKind.Text, 0, "StreamCount")); int iNbMenuStreams = int.Parse(MI.Get(StreamKind.Menu, 0, "StreamCount")); for (int i = 0; i < iNbVideoStreams; i++) { var vs = new VideoStream(); ReadProperties(MI, vs, StreamKind.Video, i); FileInfo.VideoStreams.Add(vs); } for (int i = 0; i < iNbAudioStreams; i++) { var aus = new AudioStream(); ReadProperties(MI, aus, StreamKind.Audio, i); FileInfo.AudioStreams.Add(aus); } for (int i = 0; i < iNbTextStreams; i++) { var ts = new TextStream(); ReadProperties(MI, ts, StreamKind.Text, i); FileInfo.TextStreams.Add(ts); } for (int i = 0; i < iNbMenuStreams; i++) { var ms = new MenuStream(); ReadProperties(MI, ms, StreamKind.Menu, i); for (int j = ms.Chapters_Pos_Begin; j < ms.Chapters_Pos_End; j++) { ms.Chapters.Add(MI.Get(StreamKind.Menu, i, j)); } FileInfo.MenuStreams.Add(ms); } return(FileInfo); }
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(); }
// ReSharper disable InconsistentNaming private static void AddToMusicSection_ImportMediaInfo(FileSystemInfo file, IMLSection musicSection, int audioDuration, // ReSharper restore InconsistentNaming string filesize, MediaInfo mi, string filecodec, string fileName) { Application.DoEvents(); //Debugger.LogMessageToFile("Importing audio track " + fileName + "..."); MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "Importing audio track " + fileName + "..."); IMLItem item; AddFileToSection(out item, musicSection, fileName, file.FullName, file.FullName); MediaInformation.ImportMediaInfoforAudio(mi, item, filesize, filecodec, audioDuration); }
internal static void AnalyzeMediaFileGetMediaInformation(FileSystemInfo file, MediaInfo mediaInfo, out int videoDuration, out string videoCodec, out string audioCodec, out int audioDuration, out string filesize, out string filecodec) { OpenMediaFileForProcessing(file, mediaInfo); filesize = GetFileSize(mediaInfo); GetCodecs(mediaInfo, out videoCodec, out audioCodec, out filecodec); GetDurations(mediaInfo, out videoDuration, out audioDuration); }
public AudioMetadata(string Filename) { var MI = new MediaInfo(); MI.Open(Filename); Title = MI.Get(StreamKind.General, 0, "Title"); Album = MI.Get(StreamKind.General, 0, "Album"); Artist = MI.Get(StreamKind.General, 0, "Performer"); Genre = MI.Get(StreamKind.General, 0, "Genre"); RecordDate = MI.Get(StreamKind.General, 0, "Recorded_Date"); var duration = MI.Get(StreamKind.General, 0, "Duration"); Duration = new TimeSpan(Convert.ToInt64(duration) * 10000); }
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); }
///<summary>Constructor to create a MediaInfo StreamKind-specific object, such as an audio ///stream, for use by an existing MediaFile object.</summary> ///<param name="mediaInfo">A pre-initialized MediaInfo object.</param> ///<param name="id">The MediaInfo ID for this stream.</param> public Media(MediaInfo mediaInfo, int id) { string errorText; this.mediaInfo = mediaInfo; if(mediaInfo == null) { errorText = "MediaInfo object cannot be null."; throw new ArgumentNullException(errorText); } else if(!isMediaInfoDllCompatible()) { errorText = "Incompatible version of MediaInfo.DLL"; throw new InvalidOperationException(errorText); } else { this.id = id; } }
private static string GetAudioCodec(MediaInfo mediaInfo) { Application.DoEvents(); string audioCodec; Debugger.LogMessageToFile("Getting audio codec..."); try { audioCodec = mediaInfo.Get(StreamKind.Audio, 0, "Codec"); } catch { audioCodec = string.Empty; } return audioCodec; }
public static String ExampleWithStream() { //Initilaizing MediaInfo MediaInfo MI = new MediaInfo(); //From: preparing an example file for reading FileStream From = new FileStream(FilePath, FileMode.Open, FileAccess.Read); //From: preparing a memory buffer for reading byte[] From_Buffer = new byte[64 * 1024]; int From_Buffer_Size; //The size of the read file buffer //Preparing to fill MediaInfo with a buffer MI.Open_Buffer_Init(From.Length, 0); //The parsing loop do { //Reading data somewhere, do what you want for this. From_Buffer_Size = From.Read(From_Buffer, 0, 64 * 1024); //Sending the buffer to MediaInfo System.Runtime.InteropServices.GCHandle GC = System.Runtime.InteropServices.GCHandle.Alloc(From_Buffer, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr From_Buffer_IntPtr = GC.AddrOfPinnedObject(); Status Result = (Status)MI.Open_Buffer_Continue(From_Buffer_IntPtr, (IntPtr)From_Buffer_Size); GC.Free(); if ((Result & Status.Finalized) == Status.Finalized) break; //Testing if MediaInfo request to go elsewhere if (MI.Open_Buffer_Continue_GoTo_Get() != -1) { Int64 Position = From.Seek(MI.Open_Buffer_Continue_GoTo_Get(), SeekOrigin.Begin); //Position the file MI.Open_Buffer_Init(From.Length, Position); //Informing MediaInfo we have seek } } while (From_Buffer_Size > 0); //Finalizing MI.Open_Buffer_Finalize(); //This is the end of the stream, MediaInfo must finnish some work //Get() example return "Container format is " + MI.Get(StreamKind.General, 0, "Format"); }
private static int GetAudioDuration(MediaInfo mediaInfo) { Application.DoEvents(); int audioDuration = 0; string audioDurationStr; Debugger.LogMessageToFile("Getting audio duration..."); try { audioDurationStr = mediaInfo.Get(StreamKind.Audio, 0, "Duration"); } catch (Exception e) { Debugger.LogMessageToFile("[Media File Analyzer] An unexpected error occured while" + " the Media Analyzer was trying to obtain a media file's Audio Duration." + " The error was: " + e); audioDurationStr = string.Empty; } try { if (!String.IsNullOrEmpty(audioDurationStr)) { Debugger.LogMessageToFile("Converting audio duration..."); audioDuration = Convert.ToInt32(audioDurationStr); audioDuration = audioDuration/60/1000; Debugger.LogMessageToFile("Audio duration: " + audioDuration); } } catch (Exception e) { Debugger.LogMessageToFile(""); } return audioDuration; }
///<summary>Used to create a stream-specific object, such as an audio ///stream, for use by an existing MediaFile object.</summary> ///<param name="mediaInfo">A pre-initialized MediaInfo object.</param> ///<param name="kind">A defined value from StreamKind enum.</param> ///<param name="id">The MediaInfo ID for this stream.</param> public Media(MediaInfo mediaInfo, StreamKind kind, int id) { string errorText; this.mediaInfo = mediaInfo; if (mediaInfo == null) { errorText = "MediaInfo object cannot be null."; throw new ArgumentNullException(errorText); } if (!isMediaInfoDllCompatible()) { errorText = "Incompatible version of MediaInfo.DLL"; throw new InvalidOperationException(errorText); } this.kind = kind; if (!Enum.IsDefined(typeof(StreamKind), (object)kind)) { errorText = "Invalid value for StreamKind"; throw new ArgumentOutOfRangeException(errorText); } this.id = id; }
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; }
internal static void AnalyzeFileDetectMediaType(FileInfo file, string fileName, MediaInfo mediaInfo, string pluginPath, string ext, ref bool isAudio, ref bool isVideo, out int videoDuration, out string filecodec, out string audioCodec, out string videoCodec, out string filesize, out int audioDuration) { Application.DoEvents(); UseMediaAnalyzerToDetectMediaDurations(file, mediaInfo, isAudio, isVideo, out filesize, out filecodec, out audioDuration, out videoDuration, out videoCodec, out audioCodec); Application.DoEvents(); DetectMediaTypeByUsingMediaDurations(fileName, ref isVideo, audioDuration, videoDuration, pluginPath, ext, ref isAudio); }
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); }
public AboutBox() { InitializeComponent(); this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; StringBuilder sbDesc = new StringBuilder(); sbDesc.AppendLine(AssemblyDescription); sbDesc.AppendLine(); sbDesc.AppendLine("Running from:"); sbDesc.AppendLine(Application.StartupPath); sbDesc.AppendLine(); sbDesc.AppendLine("Settings file:"); sbDesc.AppendLine(Program.AppConf.XMLSettingsFile); MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo(); sbDesc.AppendLine(); sbDesc.AppendLine("Using:"); sbDesc.AppendLine(mi.Option("Info_Version") + " from http://sourceforge.net/projects/mediainfo"); sbDesc.AppendLine("Movie Thumbnailer v200808a:"); this.textBoxDescription.Text = sbDesc.ToString(); }
private string ExtractAudio(string namevideo, string outfile, int streamIndex = 0) { if (string.IsNullOrEmpty(namevideo)) { return ""; } string ext = Path.GetExtension(namevideo); //aextract = "\"" + workPath + "\\mp4box.exe\" -raw 2 \"" + namevideo + "\""; string aextract = ""; aextract += Util.FormatPath(workPath + "\\ffmpeg.exe"); aextract += " -i " + Util.FormatPath(namevideo); aextract += " -vn -sn -c:a copy -y -map 0:a:" + streamIndex + " "; MediaInfo MI = new MediaInfo(); MI.Open(namevideo); string audioFormat = MI.Get(StreamKind.Audio, streamIndex, "Format"); string audioProfile = MI.Get(StreamKind.Audio, streamIndex, "Format_Profile"); if (!string.IsNullOrEmpty(audioFormat)) { if (audioFormat.Contains("MPEG") && audioProfile == "Layer 3") ext = ".mp3"; else if (audioFormat.Contains("MPEG") && audioProfile == "Layer 2") ext = ".mp2"; else if (audioFormat.Contains("PCM")) //flv support(PCM_U8 * PCM_S16BE * PCM_MULAW * PCM_ALAW * ADPCM_SWF) ext = ".wav"; else if (audioFormat == "AAC") ext = ".aac"; else if (audioFormat == "AC-3") ext = ".ac3"; else if (audioFormat == "ALAC") ext = ".m4a"; else ext = ".mka"; } else { return ""; } aextract += Util.FormatPath(outfile) + "\r\n"; return aextract; }
private void ExtractAV(string namevideo, string av, int streamIndex) { if (string.IsNullOrEmpty(namevideo)) { ShowErrorMessage("请选择视频文件"); return; } string ext = Path.GetExtension(namevideo); //aextract = "\"" + workPath + "\\mp4box.exe\" -raw 2 \"" + namevideo + "\""; string aextract = ""; aextract += Util.FormatPath(workPath + "\\ffmpeg.exe"); aextract += " -i " + Util.FormatPath(namevideo); if (av == "a") { aextract += " -vn -sn -c:a copy -y -map 0:a:" + streamIndex + " "; MediaInfo MI = new MediaInfo(); MI.Open(namevideo); string audioFormat = MI.Get(StreamKind.Audio, streamIndex, "Format"); string audioProfile = MI.Get(StreamKind.Audio, streamIndex, "Format_Profile"); if (!string.IsNullOrEmpty(audioFormat)) { if (audioFormat.Contains("MPEG") && audioProfile == "Layer 3") ext = ".mp3"; else if (audioFormat.Contains("MPEG") && audioProfile == "Layer 2") ext = ".mp2"; else if (audioFormat.Contains("PCM")) //flv support(PCM_U8 * PCM_S16BE * PCM_MULAW * PCM_ALAW * ADPCM_SWF) ext = ".wav"; else if (audioFormat == "AAC") ext = ".aac"; else if (audioFormat == "AC-3") ext = ".ac3"; else if (audioFormat == "ALAC") ext = ".m4a"; else ext = ".mka"; } else { ShowInfoMessage("该轨道无音频"); return; } } else if (av == "v") { aextract += " -an -sn -c:v copy -y -map 0:v:" + streamIndex + " "; } else { throw new Exception("未知流!"); } string suf = "_audio_"; if (av == "v") { suf = "_video_"; } suf += "index" + streamIndex; string outfile = Util.GetDir(namevideo) + Path.GetFileNameWithoutExtension(namevideo) + suf + ext; aextract += Util.FormatPath(outfile); batpath = workPath + "\\" + av + "extract.bat"; File.WriteAllText(batpath, aextract, Encoding.Default); LogRecord(aextract); Process.Start(batpath); }
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); }
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 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.IsOk) { 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(); } }
private static void CloseMediaInfo() { minstance?.Dispose(); minstance = null; }
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, 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); }
/// <summary> /// Creates a new instance of <see cref="MediaInfoWrapper"/>. To get metadata, the media resource has to be /// opened by the use of one of the methods <see cref="Open(Stream)"/> or <see cref="Open(string)"/>. /// </summary> public MediaInfoWrapper() { _mediaInfo = new MediaInfo(); _isValid = false; }
private static Stream TranslateAudioStream(MediaInfoLib.MediaInfo m, int num) { Stream s = new Stream { Id = m.GetInt(StreamKind.Audio, num, "UniqueID"), CodecID = m.Get(StreamKind.Audio, num, "CodecID"), Codec = TranslateCodec(m.Get(StreamKind.Audio, num, "Codec")) }; string title = m.Get(StreamKind.Audio, num, "Title"); if (!string.IsNullOrEmpty(title)) { s.Title = title; } s.StreamType = 2; string lang = m.Get(StreamKind.Audio, num, "Language/String3"); if (!string.IsNullOrEmpty(lang)) { s.LanguageCode = PostTranslateCode3(lang); } string lan = PostTranslateLan(GetLanguageFromCode3(lang, m.Get(StreamKind.Audio, num, "Language/String1"))); if (!string.IsNullOrEmpty(lan)) { s.Language = lan; } int duration = m.GetInt(StreamKind.Audio, num, "Duration"); if (duration != 0) { s.Duration = duration; } int brate = BiggerFromList(m.Get(StreamKind.Audio, num, "BitRate")); if (brate != 0) { s.Bitrate = (int)Math.Round(brate / 1000F); } byte bitdepth = m.GetByte(StreamKind.Audio, num, "BitDepth"); if (bitdepth != 0) { s.BitDepth = bitdepth; } string fprofile = m.Get(StreamKind.Audio, num, "Format_Profile"); if (!string.IsNullOrEmpty(fprofile)) { if ((fprofile.ToLower() != "layer 3") && (fprofile.ToLower() != "dolby digital") && (fprofile.ToLower() != "pro") && (fprofile.ToLower() != "layer 2")) { s.Profile = fprofile.ToLower(CultureInfo.InvariantCulture); } if (fprofile.ToLower().StartsWith("ma")) { s.Profile = "ma"; } } string fset = m.Get(StreamKind.Audio, num, "Format_Settings"); if (!string.IsNullOrEmpty(fset) && (fset == "Little / Signed") && (s.Codec == "pcm") && (bitdepth == 16)) { s.Profile = "pcm_s16le"; } else if (!string.IsNullOrEmpty(fset) && (fset == "Big / Signed") && (s.Codec == "pcm") && (bitdepth == 16)) { s.Profile = "pcm_s16be"; } else if (!string.IsNullOrEmpty(fset) && (fset == "Little / Unsigned") && (s.Codec == "pcm") && (bitdepth == 8)) { s.Profile = "pcm_u8"; } string id = m.Get(StreamKind.Audio, num, "ID"); if (!string.IsNullOrEmpty(id) && byte.TryParse(id, out byte idx)) { s.Index = idx; } int pa = BiggerFromList(m.Get(StreamKind.Audio, num, "SamplingRate")); if (pa != 0) { s.SamplingRate = pa; } int channels = BiggerFromList(m.Get(StreamKind.Audio, num, "Channel(s)")); if (channels != 0) { s.Channels = (byte)channels; } int channelso = BiggerFromList(m.Get(StreamKind.Audio, num, "Channel(s)_Original")); if (channelso != 0) { s.Channels = (byte)channelso; } string bitRateMode = m.Get(StreamKind.Audio, num, "BitRate_Mode"); if (!string.IsNullOrEmpty(bitRateMode)) { s.BitrateMode = bitRateMode.ToLower(CultureInfo.InvariantCulture); } string dialnorm = m.Get(StreamKind.Audio, num, "dialnorm"); if (!string.IsNullOrEmpty(dialnorm)) { s.DialogNorm = dialnorm; } dialnorm = m.Get(StreamKind.Audio, num, "dialnorm_Average"); if (!string.IsNullOrEmpty(dialnorm)) { s.DialogNorm = dialnorm; } string def = m.Get(StreamKind.Text, num, "Default"); if (!string.IsNullOrEmpty(def)) { if (def.ToLower(CultureInfo.InvariantCulture) == "yes") { s.Default = 1; } } string forced = m.Get(StreamKind.Text, num, "Forced"); if (!string.IsNullOrEmpty(forced)) { if (forced.ToLower(CultureInfo.InvariantCulture) == "yes") { s.Forced = 1; } } return(s); }
private static Stream TranslateVideoStream(MediaInfoLib.MediaInfo m, int num) { Stream s = new Stream { Id = m.GetByte(StreamKind.Video, num, "UniqueID"), Codec = TranslateCodec(m.Get(StreamKind.Video, num, "Codec")), CodecID = m.Get(StreamKind.Video, num, "CodecID"), StreamType = 1, Width = m.GetInt(StreamKind.Video, num, "Width"), Height = m.GetInt(StreamKind.Video, num, "Height"), Duration = m.GetInt(StreamKind.Video, num, "Duration") }; string title = m.Get(StreamKind.Video, num, "Title"); if (!string.IsNullOrEmpty(title)) { s.Title = title; } string lang = m.Get(StreamKind.Video, num, "Language/String3"); if (!string.IsNullOrEmpty(lang)) { s.LanguageCode = PostTranslateCode3(lang); } string lan = PostTranslateLan(GetLanguageFromCode3(lang, m.Get(StreamKind.Video, num, "Language/String1"))); if (!string.IsNullOrEmpty(lan)) { s.Language = lan; } int brate = BiggerFromList(m.Get(StreamKind.Video, num, "BitRate")); if (brate != 0) { s.Bitrate = (int)Math.Round(brate / 1000F); } string stype = m.Get(StreamKind.Video, num, "ScanType"); if (!string.IsNullOrEmpty(stype)) { s.ScanType = stype.ToLower(); } s.RefFrames = m.GetByte(StreamKind.Video, num, "Format_Settings_RefFrames"); string fprofile = m.Get(StreamKind.Video, num, "Format_Profile"); if (!string.IsNullOrEmpty(fprofile)) { int a = fprofile.ToLower(CultureInfo.InvariantCulture).IndexOf("@", StringComparison.Ordinal); if (a > 0) { s.Profile = TranslateProfile(s.Codec, fprofile.ToLower(CultureInfo.InvariantCulture).Substring(0, a)); if (int.TryParse(TranslateLevel(fprofile.ToLower(CultureInfo.InvariantCulture).Substring(a + 1)), out int level)) { s.Level = level; } } else { s.Profile = TranslateProfile(s.Codec, fprofile.ToLower(CultureInfo.InvariantCulture)); } } float rot = m.GetFloat(StreamKind.Video, num, "Rotation"); if (rot != 0) { switch (rot) { case 90F: s.Orientation = 9; break; case 180F: s.Orientation = 3; break; case 270F: s.Orientation = 6; break; } } string muxing = m.Get(StreamKind.Video, num, "MuxingMode"); if (!string.IsNullOrEmpty(muxing)) { if (muxing.ToLower(CultureInfo.InvariantCulture).Contains("strip")) { s.HeaderStripping = 1; } } string cabac = m.Get(StreamKind.Video, num, "Format_Settings_CABAC"); if (!string.IsNullOrEmpty(cabac)) { s.Cabac = (byte)(cabac.ToLower(CultureInfo.InvariantCulture) == "yes" ? 1 : 0); } if (s.Codec == "h264") { if (s.Level == 31 && s.Cabac == 0) { s.HasScalingMatrix = 1; } else { s.HasScalingMatrix = 0; } } string fratemode = m.Get(StreamKind.Video, num, "FrameRate_Mode"); if (!string.IsNullOrEmpty(fratemode)) { s.FrameRateMode = fratemode.ToLower(CultureInfo.InvariantCulture); } float frate = m.GetFloat(StreamKind.Video, num, "FrameRate"); if (frate == 0.0F) { frate = m.GetFloat(StreamKind.Video, num, "FrameRate_Original"); } if (frate != 0.0F) { s.FrameRate = frate; } string colorspace = m.Get(StreamKind.Video, num, "ColorSpace"); if (!string.IsNullOrEmpty(colorspace)) { s.ColorSpace = colorspace.ToLower(CultureInfo.InvariantCulture); } string chromasubsampling = m.Get(StreamKind.Video, num, "ChromaSubsampling"); if (!string.IsNullOrEmpty(chromasubsampling)) { s.ChromaSubsampling = chromasubsampling.ToLower(CultureInfo.InvariantCulture); } byte bitdepth = m.GetByte(StreamKind.Video, num, "BitDepth"); if (bitdepth != 0) { s.BitDepth = bitdepth; } string id = m.Get(StreamKind.Video, num, "ID"); if (!string.IsNullOrEmpty(id)) { if (byte.TryParse(id, out byte idx)) { s.Index = idx; } } string qpel = m.Get(StreamKind.Video, num, "Format_Settings_QPel"); if (!string.IsNullOrEmpty(qpel)) { s.QPel = (byte)(qpel.ToLower(CultureInfo.InvariantCulture) == "yes" ? 1 : 0); } string gmc = m.Get(StreamKind.Video, num, "Format_Settings_GMC"); if (!string.IsNullOrEmpty(gmc)) { s.GMC = gmc; } string bvop = m.Get(StreamKind.Video, num, "Format_Settings_BVOP"); if (!string.IsNullOrEmpty(bvop) && (s.Codec != "mpeg1video")) { if (bvop == "No") { s.BVOP = 0; } else if ((bvop == "1") || (bvop == "Yes")) { s.BVOP = 1; } } string def = m.Get(StreamKind.Text, num, "Default"); if (!string.IsNullOrEmpty(def)) { if (def.ToLower(CultureInfo.InvariantCulture) == "yes") { s.Default = 1; } } string forced = m.Get(StreamKind.Text, num, "Forced"); if (!string.IsNullOrEmpty(forced)) { if (forced.ToLower(CultureInfo.InvariantCulture) == "yes") { s.Forced = 1; } } s.PA = m.GetFloat(StreamKind.Video, num, "PixelAspectRatio"); string sp2 = m.Get(StreamKind.Video, num, "PixelAspectRatio_Original"); if (!string.IsNullOrEmpty(sp2)) { s.PA = System.Convert.ToSingle(sp2); } if ((s.PA != 1.0) && s.Width != 0) { if (s.Width != 0) { float width = s.Width; width *= s.PA; s.PixelAspectRatio = (int)Math.Round(width) + ":" + s.Width; } } return(s); }
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; //} } } }
///<summary>TextStream constructor.</summary> ///<param name="mediaInfo">A MediaInfo object.</param> ///<param name="id">The MediaInfo ID for this text stream.</param> public TextStream(MediaInfo mediaInfo, int id) : base(mediaInfo, StreamKind.Text, id) { }
public InfoMedia() { _mediaInfo = new MediaInfo(); }
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 File() { _mediaInfo = new MediaInfo(); VideoCodecs = new List<string>(); AudioCodecs = new List<string>(); AudioLanguages = new List<string>(); }