public Get ( StreamKind StreamKind, uint StreamNumber, String Parameter ) : String | ||
StreamKind | StreamKind | |
StreamNumber | uint | |
Parameter | String | |
Résultat | String |
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 "; }
/// <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 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; }
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); }
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 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); }
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 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 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); }
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 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 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 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 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 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; }
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 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 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); }
private void AudioOnePicButton_Click(object sender, EventArgs e) { if (!File.Exists(AudioPicTextBox.Text)) { ShowErrorMessage("请选择图片文件"); } else if (!File.Exists(AudioPicAudioTextBox.Text)) { ShowErrorMessage("请选择音频文件"); } else if (AudioOnePicOutputTextBox.Text == "") { ShowErrorMessage("请选择输出文件"); } else { System.Drawing.Image img = System.Drawing.Image.FromFile(AudioPicTextBox.Text); // if not even number, chop 1 pixel out int newWidth = (img.Width % 2 == 0 ? img.Width : img.Width - 1); int newHeight = (img.Height % 2 == 0 ? img.Height : img.Height - 1); Rectangle cropArea; if (img.Width % 2 != 0 || img.Height % 2 != 0) { Bitmap bmp = new Bitmap(img); cropArea = new Rectangle(0, 0, newWidth, newHeight); img = (Image)bmp.Clone(cropArea, bmp.PixelFormat); } //if (img.Width % 2 != 0 || img.Height % 2 != 0) //{ // MessageBox.Show("图片的长和宽必须是偶数。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); // img.Dispose(); // return; //} //if (img.RawFormat.Equals(ImageFormat.Jpeg)) //{ // File.Copy(AudioPicTextBox.Text, tempPic, true); //} //else { System.Drawing.Imaging.Encoder ImageEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameter ep = new EncoderParameter(ImageEncoder, 100L); EncoderParameters eps = new EncoderParameters(1); ImageCodecInfo ImageCoderType = getImageCoderInfo("image/jpeg"); eps.Param[0] = ep; img.Save(tempPic, ImageCoderType, eps); //img.Save(tempPic, ImageFormat.Jpeg); } //获得音频时长 MediaInfo MI = new MediaInfo(); MI.Open(AudioPicAudioTextBox.Text); int seconds = SecondsFromHHMMSS(MI.Get(StreamKind.General, 0, "Duration/String3")); string ffPath = Path.Combine(workPath, "ffmpeg.exe"); string neroPath = Path.Combine(workPath, "neroaacenc.exe"); if (AudioCopyCheckBox.Checked) { mux = "\"" + ffPath + "\" -loop 1 -r " + OnePicFPSNum.Value.ToString() + " -t " + seconds.ToString() + " -f image2 -i \"" + tempPic + "\" -c:v libx264 -crf " + OnePicCRFNum.Value.ToString() + " -y SinglePictureVideo.mp4\r\n"; mux += "\"" + ffPath + "\" -i SinglePictureVideo.mp4 -i \"" + AudioPicAudioTextBox.Text + "\" -c:v copy -c:a copy -y \"" + AudioOnePicOutputTextBox.Text + "\"\r\n"; mux += "del SinglePictureVideo.mp4\r\n"; mux += "cmd"; } else { mux = "\"" + ffPath + "\" -i \"" + AudioPicAudioTextBox.Text + "\" -f wav - |" + neroPath + " -br " + OnePicAudioBitrateNum.Value.ToString() + "000 -ignorelength -if - -of audio.mp4 -lc\r\n"; mux += "\"" + ffPath + "\" -loop 1 -r " + OnePicFPSNum.Value.ToString() + " -t " + seconds.ToString() + " -f image2 -i \"" + tempPic + "\" -c:v libx264 -crf " + OnePicCRFNum.Value.ToString() + " -y SinglePictureVideo.mp4\r\n"; mux += "\"" + ffPath + "\" -i SinglePictureVideo.mp4 -i audio.mp4 -c:v copy -c:a copy -y \"" + AudioOnePicOutputTextBox.Text + "\"\r\n"; mux += "del SinglePictureVideo.mp4\r\ndel audio.mp4\r\n"; mux += "cmd"; } /* string audioPath = AddExt(Path.GetFileName(AudioPicAudioTextBox.Text), "_atmp.mp4"); string videoPath = AddExt(Path.GetFileName(AudioPicAudioTextBox.Text), "_vtmp.mp4"); string picturePath = "c:\\" + Path.GetFileNameWithoutExtension(AudioPicTextBox.Text) + "_tmp.jpg"; if (AudioCopyCheckBox.Checked) { mux = "ffmpeg -loop 1 -r " + AudioOnePicFPSNum.Value.ToString() + " -t " + seconds.ToString() + " -f image2 -i \"" + picturePath + "\" -vcodec libx264 -crf 24 -y \"" + videoPath + "\"\r\n"; mux += "ffmpeg -i \"" + videoPath + "\" -i \"" + AudioPicAudioTextBox.Text + "\" -c:v copy -c:a copy -y \"" + AudioOnePicOutputTextBox.Text + "\"\r\n"; mux += "del \"" + videoPath + "\"\r\ndel \"" + picturePath + "\"\r\n"; } else { mux = "ffmpeg -i \"" + AudioPicAudioTextBox.Text + "\" -f wav - |neroaacenc -br " + AudioOnePicAudioBitrateNum.Value.ToString() + "000 -ignorelength -if - -of \"" + audioPath + "\" -lc\r\n"; mux += "ffmpeg -loop 1 -r " + AudioOnePicFPSNum.Value.ToString() + " -t " + seconds.ToString() + " -f image2 -i \"" + picturePath + "\" -vcodec libx264 -crf 24 -y \"" + videoPath + "\"\r\n"; mux += "ffmpeg -i \"" + videoPath + "\" -i \"" + audioPath + "\" -c:v copy -c:a copy -y \"" + AudioOnePicOutputTextBox.Text + "\"\r\n"; mux += "del \"" + videoPath + "\"\r\ndel \"" + audioPath + "\"\r\ndel \"" + picturePath + "\"\r\n"; } */ batpath = Path.Combine(workPath, Path.GetRandomFileName() + ".bat"); File.WriteAllText(batpath, mux, Encoding.Default); LogRecord(mux); Process.Start(batpath); } }
public string x264bat(string input, string output, int pass = 1, string sub = "") { StringBuilder sb = new StringBuilder(); //keyint设为fps的10倍 MediaInfo MI = new MediaInfo(); MI.Open(input); string frameRate = MI.Get(StreamKind.Video, 0, "FrameRate"); double fps; string keyint = "-1"; if (double.TryParse(frameRate, out fps)) { fps = Math.Round(fps); keyint = (fps * 10).ToString(); } if (Path.GetExtension(input) == ".avs") sb.Append("\"" + workPath + "\\avs4x26x.exe\"" + " -L "); sb.Append("\"" + Path.Combine(workPath, x264ExeComboBox.SelectedItem.ToString()) + "\""); // 编码模式 switch (x264mode) { case 0: // 自定义 sb.Append(" " + x264CustomParameterTextBox.Text); break; case 1: // crf sb.Append(" --crf " + x264CRFNum.Value); break; case 2: // 2pass sb.Append(" --pass " + pass + " --bitrate " + x264BitrateNum.Value + " --stats \"" + Path.Combine(tempfilepath, Path.GetFileNameWithoutExtension(output)) + ".stats\""); break; } if (x264mode != 0) { if (x264DemuxerComboBox.Text != "auto" && x264DemuxerComboBox.Text != string.Empty) sb.Append(" --demuxer " + x264DemuxerComboBox.Text); if (x264ThreadsComboBox.SelectedItem.ToString() != "auto" && x264ThreadsComboBox.SelectedItem.ToString() != string.Empty) sb.Append(" --threads " + x264ThreadsComboBox.SelectedItem.ToString()); if (x264extraLine.Text != string.Empty) sb.Append(" " + x264extraLine.Text); else sb.Append(" --preset 8 " + " -I " + keyint + " -r 4 -b 3 --me umh -i 1 --scenecut 60 -f 1:1 --qcomp 0.5 --psy-rd 0.3:0 --aq-mode 2 --aq-strength 0.8"); if (x264HeightNum.Value != 0 && x264WidthNum.Value != 0 && !MaintainResolutionCheckBox.Checked) sb.Append(" --vf resize:" + x264WidthNum.Value + "," + x264HeightNum.Value + ",,,,lanczos"); } if (!string.IsNullOrEmpty(sub)) { string x264tmpline = sb.ToString(); if (x264tmpline.IndexOf("--vf") == -1) sb.Append(" --vf subtitles --sub \"" + sub + "\""); else { Regex r = new Regex("--vf\\s\\S*"); Match m = r.Match(x264tmpline); sb.Insert(m.Index + 5, "subtitles/").Append(" --sub \"" + sub + "\""); } } if (x264SeekNumericUpDown.Value != 0) sb.Append(" --seek " + x264SeekNumericUpDown.Value.ToString()); if (x264FramesNumericUpDown.Value != 0) sb.Append(" --frames " + x264FramesNumericUpDown.Value.ToString()); if (x264mode == 2 && pass == 1) sb.Append(" -o NUL"); else if (!string.IsNullOrEmpty(output)) sb.Append(" -o " + "\"" + output + "\""); if (!string.IsNullOrEmpty(input)) sb.Append(" \"" + input + "\""); return sb.ToString(); }
private void btnBatchMP4_Click(object sender, EventArgs e) { if (lbffmpeg.Items.Count != 0) { string ext = MuxFormatComboBox.Text; string mux = ""; for (int i = 0; i < lbffmpeg.Items.Count; i++) { string filePath = lbffmpeg.Items[i].ToString(); //如果是源文件的格式和目标格式相同则跳过 if (Path.GetExtension(filePath).Contains(ext)) continue; string finish = Path.ChangeExtension(filePath, ext); aextract = ""; //检测音频是否需要转换为AAC MediaInfo MI = new MediaInfo(); MI.Open(filePath); string audio = MI.Get(StreamKind.Audio, 0, "Format"); if (audio.ToLower() != "aac") { mux += "\"" + workPath + "\\ffmpeg.exe\" -y -i \"" + lbffmpeg.Items[i].ToString() + "\" -c:v copy -c:a " + MuxAacEncoderComboBox.Text + " -strict -2 \"" + finish + "\" \r\n"; } else { mux += "\"" + workPath + "\\ffmpeg.exe\" -y -i \"" + lbffmpeg.Items[i].ToString() + "\" -c copy \"" + finish + "\" \r\n"; } } mux += "\r\ncmd"; batpath = workPath + "\\mux.bat"; File.WriteAllText(batpath, mux, Encoding.Default); LogRecord(mux); Process.Start(batpath); } else ShowErrorMessage("请输入视频!"); }
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 static int GetVideoDuration(MediaInfo mediaInfo) { Application.DoEvents(); int videoDuration = 0; Debugger.LogMessageToFile("Getting video duration..."); string videoDurationStr = mediaInfo.Get(StreamKind.Video, 0, "Duration"); if (!String.IsNullOrEmpty(videoDurationStr)) { Debugger.LogMessageToFile("Converting video duration..."); videoDuration = Convert.ToInt32(videoDurationStr); videoDuration = videoDuration/60/1000; Debugger.LogMessageToFile("Video duration: " + videoDuration); } return videoDuration; }
private static string GetFileSize(MediaInfo mediaInfo) { Application.DoEvents(); string filesize; Debugger.LogMessageToFile("Getting filesize..."); try { filesize = mediaInfo.Get(0, 0, "FileSize"); } catch (Exception e) { Debugger.LogMessageToFile("[Media File Analyzer] An unexpected error occured while" + " the Media Analyzer was trying to obtain a media file's size." + " The error was: " + e); throw; } return filesize; }
private static string GetVideoCodec(MediaInfo mediaInfo) { Application.DoEvents(); string videoCodec; #region Get video codec Debugger.LogMessageToFile("Getting video codec..."); try { videoCodec = (mediaInfo.Get(StreamKind.Video, 0, "Codec")); } catch (Exception e) { Debugger.LogMessageToFile("[Media File Analyzer] An unexpected error occured while" + " the Media Analyzer was trying to obtain a media file's size." + " The error was: " + e); videoCodec = String.Empty; } #endregion return videoCodec; }
private static string GetFileCodec(MediaInfo mediaInfo) { Application.DoEvents(); string filecodec; #region Get file codec Debugger.LogMessageToFile("Getting file codec..."); try { filecodec = (mediaInfo.Get(0, 0, "Codec")); } catch (Exception e) { Debugger.LogMessageToFile("[Media File Analyzer] An unexpected error occured while" + " the Media Analyzer was trying to obtain a media file's size." + " The error was: " + e); throw; } #endregion return filecodec; }
/// <summary> /// Returns the number of video streams in the media resource. /// </summary> /// <returns>Number of video streams. If the media resource isn't a video, <c>0</c> will be /// returned.</returns> public int GetVideoCount() { int result; return(int.TryParse(_mediaInfo.Get(StreamKind.Video, 0, "StreamCount"), out result) ? result : 0); }
/// <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); }
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 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); } 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 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); }
public string VideoBatch(string input, string output) { bool hasAudio = false; string bat = ""; string inputName = Path.GetFileNameWithoutExtension(input); string tempVideo = Path.Combine(tempfilepath, inputName + "_vtemp.mp4"); string tempAudio = Path.Combine(tempfilepath, inputName + "_atemp" + getAudioExt()); //检测是否含有音频 MediaInfo MI = new MediaInfo(); MI.Open(input); string audio = MI.Get(StreamKind.Audio, 0, "Format"); if (!string.IsNullOrEmpty(audio)) { hasAudio = true; } string sub = (x264BatchSubCheckBox.Checked) ? GetSubtitlePath(input) : string.Empty; int audioMode = x264AudioModeComboBox.SelectedIndex; if (!hasAudio) audioMode = 1; switch (audioMode) { case 0: aextract = audiobat(input, tempAudio); break; case 1: aextract = string.Empty; break; case 2: if (audio.ToLower() == "aac") { tempAudio = Path.Combine(tempfilepath, inputName + "_atemp.aac"); aextract = ExtractAudio(input, tempAudio); } else aextract = audiobat(input, tempAudio); break; default: break; } if (x264ExeComboBox.SelectedItem.ToString().ToLower().Contains("x264")) { if (x264mode == 2) x264 = x264bat(input, tempVideo, 1, sub) + "\r\n" + x264bat(input, tempVideo, 2, sub); else x264 = x264bat(input, tempVideo, 0, sub); if (audioMode == 1 || !hasAudio) x264 = x264.Replace(tempVideo, output); } else if (x264ExeComboBox.SelectedItem.ToString().ToLower().Contains("x265")) { tempVideo = Path.Combine(tempfilepath, inputName + "_vtemp.hevc"); if (x264mode == 2) x264 = x265bat(input, tempVideo, 1) + "\r\n" + x265bat(input, tempVideo, 2); else x264 = x265bat(input, tempVideo); if (audioMode == 1 || !hasAudio) x264 += "\r\n\"" + workPath + "\\mp4box.exe\" -add \"" + tempVideo + "#trackID=1:name=\" -new \"" + output + "\" \r\n"; } x264 += "\r\n"; //封装 if (VideoBatchFormatComboBox.Text == "mp4") mux = boxmuxbat(tempVideo, tempAudio, output); else mux = ffmuxbat(tempVideo, tempAudio, output); if (audioMode != 1 && hasAudio) //如果压制音频 bat += aextract + x264 + mux + " \r\n"; else bat += x264 + " \r\n"; bat += "del \"" + tempAudio + "\"\r\n"; bat += "del \"" + tempVideo + "\"\r\n"; bat += "echo ===== one file is completed! =====\r\n"; return bat; }
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 btnAVS9_Click(object sender, EventArgs e) { x264DemuxerComboBox.SelectedIndex = 0; //压制AVS始终使用分离器为auto if (string.IsNullOrEmpty(nameout9)) { ShowErrorMessage("请选择输出文件"); return; } if (Path.GetExtension(nameout9).ToLower() != ".mp4") { ShowErrorMessage("仅支持MP4输出", "不支持的输出格式"); return; } if (File.Exists(txtout9.Text.Trim())) { DialogResult dgs = ShowQuestion("目标文件:\r\n\r\n" + txtout9.Text.Trim() + "\r\n\r\n已经存在,是否覆盖继续压制?", "目标文件已经存在"); if (dgs == DialogResult.No) return; } if (string.IsNullOrEmpty(Util.CheckAviSynth()) && string.IsNullOrEmpty(Util.CheckinternalAviSynth())) { if (ShowQuestion("检测到本机未安装avisynth无法继续压制,是否去下载安装", "avisynth未安装") == DialogResult.Yes) Process.Start("http://sourceforge.net/projects/avisynth2/"); return; } string inputName = Path.GetFileNameWithoutExtension(namevideo9); string tempVideo = Path.Combine(tempfilepath, inputName + "_vtemp.mp4"); string tempAudio = Path.Combine(tempfilepath, inputName + "_atemp" + getAudioExt()); Util.ensureDirectoryExists(tempfilepath); string filepath = tempavspath; //string filepath = workpath + "\\temp.avs"; File.WriteAllText(filepath, AVSScriptTextBox.Text, Encoding.Default); //检测是否含有音频 bool hasAudio = false; MediaInfo MI = new MediaInfo(); MI.Open(namevideo9); string audio = MI.Get(StreamKind.Audio, 0, "Format"); if (!string.IsNullOrEmpty(audio)) { hasAudio = true; } //audio if (AVSwithAudioCheckBox.Checked && hasAudio) { if (!File.Exists(txtvideo9.Text)) { ShowErrorMessage("请选择视频文件"); return; } aextract = audiobat(namevideo9, tempAudio); } else aextract = string.Empty; //video if (x264ExeComboBox.SelectedItem.ToString().ToLower().Contains("x264")) { if (x264mode == 2) x264 = x264bat(filepath, tempVideo, 1) + "\r\n" + x264bat(filepath, tempVideo, 2); else x264 = x264bat(filepath, tempVideo); if (!AVSwithAudioCheckBox.Checked || !hasAudio) x264 = x264.Replace(tempVideo, nameout9); } else if (x264ExeComboBox.SelectedItem.ToString().ToLower().Contains("x265")) { tempVideo = Path.Combine(tempfilepath, inputName + "_vtemp.hevc"); if (x264mode == 2) x264 = x265bat(filepath, tempVideo, 1) + "\r\n" + x265bat(filepath, tempVideo, 2); else x264 = x265bat(filepath, tempVideo); if (!AVSwithAudioCheckBox.Checked || !hasAudio) { x264 += "\r\n\"" + workPath + "\\mp4box.exe\" -add \"" + tempVideo + "#trackID=1:name=\" -new \"" + nameout9 + "\" \r\n"; x264 += "del \"" + tempVideo + "\""; } } //mux if (AVSwithAudioCheckBox.Checked && hasAudio) //如果包含音频 mux = boxmuxbat(tempVideo, tempAudio, nameout9); else mux = string.Empty; auto = aextract + x264 + "\r\n" + mux + " \r\n"; auto += "\r\necho ===== one file is completed! =====\r\n"; LogRecord(auto); Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(GetCultureName()); WorkingForm wf = new WorkingForm(auto); wf.Owner = this; wf.Show(); //auto += "\r\ncmd"; //batpath = workPath + "\\x264avs.bat"; //File.WriteAllText(batpath, auto, Encoding.Default); //Process.Start(batpath); }
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 x264StartBtn_Click(object sender, EventArgs e) { #region validation if (string.IsNullOrEmpty(namevideo2)) { ShowErrorMessage("请选择视频文件"); return; } if (!string.IsNullOrEmpty(namesub2) && !File.Exists(namesub2)) { ShowErrorMessage("字幕文件不存在,请重新选择"); return; } if (string.IsNullOrEmpty(nameout2)) { ShowErrorMessage("请选择输出文件"); return; } if (x264ExeComboBox.SelectedIndex == -1) { ShowErrorMessage("请选择X264程序"); return; } if (AudioEncoderComboBox.SelectedIndex != 0 && AudioEncoderComboBox.SelectedIndex != 1 && AudioEncoderComboBox.SelectedIndex != 5) { ShowWarningMessage("音频页面中的编码器未采用AAC将可能导致压制失败,建议将编码器改为QAAC、NeroAAC或FDKAAC。"); } //防止未选择 x264 thread if (x264ThreadsComboBox.SelectedIndex == -1) { x264ThreadsComboBox.SelectedIndex = 0; } //目标文件已经存在提示是否覆盖 if (File.Exists(x264OutTextBox.Text.Trim())) { DialogResult dgs = ShowQuestion("目标文件:\r\n\r\n" + x264OutTextBox.Text.Trim() + "\r\n\r\n已经存在,是否覆盖继续压制?", "目标文件已经存在"); if (dgs == DialogResult.No) return; } //如果是AVS复制到C盘根目录 if (Path.GetExtension(x264VideoTextBox.Text) == ".avs") { if (string.IsNullOrEmpty(Util.CheckAviSynth()) && string.IsNullOrEmpty(Util.CheckinternalAviSynth())) { if (ShowQuestion("检测到本机未安装avisynth无法继续压制,是否去下载安装", "avisynth未安装") == DialogResult.Yes) Process.Start("http://sourceforge.net/projects/avisynth2/"); return; } //if (File.Exists(tempavspath)) File.Delete(tempavspath); File.Copy(x264VideoTextBox.Text, tempavspath, true); namevideo2 = tempavspath; x264DemuxerComboBox.SelectedIndex = 0; //压制AVS始终使用分离器为auto } #endregion validation string ext = Path.GetExtension(nameout2).ToLower(); bool hasAudio = false; string inputName = Path.GetFileNameWithoutExtension(namevideo2); string tempVideo = Path.Combine(tempfilepath, inputName + "_vtemp.mp4"); string tempAudio = Path.Combine(tempfilepath, inputName + "_atemp" + getAudioExt()); Util.ensureDirectoryExists(tempfilepath); #region Audio //检测是否含有音频 MediaInfo MI = new MediaInfo(); MI.Open(namevideo2); string audio = MI.Get(StreamKind.Audio, 0, "Format"); if (!string.IsNullOrEmpty(audio)) hasAudio = true; int audioMode = x264AudioModeComboBox.SelectedIndex; if (!hasAudio && x264AudioModeComboBox.SelectedIndex != 1) { DialogResult r = ShowQuestion("原视频不包含音频流,音频模式是否改为无音频流?", "提示"); if (r == DialogResult.Yes) audioMode = 1; } switch (audioMode) { case 0: aextract = audiobat(namevideo2, tempAudio); break; case 1: aextract = string.Empty; break; case 2: if (audio.ToLower() == "aac") { tempAudio = Path.Combine(tempfilepath, inputName + "_atemp.aac"); aextract = ExtractAudio(namevideo2, tempAudio); } else { ShowInfoMessage("因音频编码非AAC故无法复制音频流,音频将被重编码。"); aextract = audiobat(namevideo2, tempAudio); } break; default: break; } #endregion #region Video if (x264ExeComboBox.SelectedItem.ToString().ToLower().Contains("x264")) { if (x264mode == 2) x264 = x264bat(namevideo2, tempVideo, 1, namesub2) + "\r\n" + x264bat(namevideo2, tempVideo, 2, namesub2); else x264 = x264bat(namevideo2, tempVideo, 0, namesub2); if (audioMode == 1) x264 = x264.Replace(tempVideo, nameout2); } else if (x264ExeComboBox.SelectedItem.ToString().ToLower().Contains("x265")) { tempVideo = Path.Combine(tempfilepath, inputName + "_vtemp.hevc"); if (ext != ".mp4") { ShowErrorMessage("不支持的格式输出,x265当前工具箱仅支持MP4输出"); return; } if (x264mode == 2) x264 = x265bat(namevideo2, tempVideo, 1) + "\r\n" + x265bat(namevideo2, tempVideo, 2); else x264 = x265bat(namevideo2, tempVideo); if (audioMode == 1) { x264 += "\r\n\"" + workPath + "\\mp4box.exe\" -add \"" + tempVideo + "#trackID=1:name=\" -new \"" + Util.ChangeExt(nameout2, ".mp4") + "\" \r\n"; x264 += "del \"" + tempVideo + "\""; } } x264 += "\r\n"; #endregion #region Mux //封装 if (audioMode != 1) { if (ext == ".mp4") mux = boxmuxbat(tempVideo, tempAudio, Util.ChangeExt(nameout2, ext)); else mux = ffmuxbat(tempVideo, tempAudio, Util.ChangeExt(nameout2, ext)); x264 = aextract + x264 + mux + "\r\n" + "del \"" + tempVideo + "\"\r\n" + "del \"" + tempAudio + "\"\r\n"; } x264 += "\r\necho ===== one file is completed! =====\r\n"; #endregion LogRecord(x264); Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(GetCultureName()); WorkingForm wf = new WorkingForm(x264); wf.Owner = this; wf.Show(); //x264 += "\r\ncmd"; //batpath = workPath + "\\x264.bat"; //File.WriteAllText(batpath, x264, Encoding.Default); //Process.Start(batpath); }
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 BlackStartButton_Click(object sender, EventArgs e) { //验证 if (!File.Exists(BlackVideoTextBox.Text) || Path.GetExtension(BlackVideoTextBox.Text) != ".flv") { ShowErrorMessage("请选择FLV视频文件"); return; } MediaInfo MI = new MediaInfo(); MI.Open(BlackVideoTextBox.Text); double videobitrate = double.Parse(MI.Get(StreamKind.General, 0, "BitRate")); double targetBitrate = (double)BlackBitrateNum.Value; if (!File.Exists(BlackPicTextBox.Text) && BlackNoPicCheckBox.Checked == false) { ShowErrorMessage("请选择图片文件或勾选使用黑屏"); return; } if (BlackOutputTextBox.Text == "") { ShowErrorMessage("请选择输出文件"); return; } if (videobitrate < 1000000) { ShowInfoMessage("此视频不需要后黑。"); return; } if (videobitrate > 5000000) { ShowInfoMessage("此视频码率过大,请先压制再后黑。"); return; } //处理图片 int videoWidth = int.Parse(MI.Get(StreamKind.Video, 0, "Width")); int videoHeight = int.Parse(MI.Get(StreamKind.Video, 0, "Height")); if (BlackNoPicCheckBox.Checked) { Bitmap bm = new Bitmap(videoWidth, videoHeight); Graphics g = Graphics.FromImage(bm); //g.FillRectangle(Brushes.White, new Rectangle(0, 0, 800, 600)); g.Clear(Color.Black); bm.Save(tempPic, ImageFormat.Jpeg); g.Dispose(); bm.Dispose(); } else { System.Drawing.Image img = System.Drawing.Image.FromFile(BlackPicTextBox.Text); int sourceWidth = img.Width; int sourceHeight = img.Height; if (img.Width % 2 != 0 || img.Height % 2 != 0) { ShowErrorMessage("图片的长和宽必须都是偶数。"); img.Dispose(); return; } if (img.Width != videoWidth || img.Height != videoHeight) { ShowErrorMessage("图片的长和宽和视频不一致。"); img.Dispose(); return; } if (img.RawFormat.Equals(ImageFormat.Jpeg)) { File.Copy(BlackPicTextBox.Text, tempPic, true); } else { System.Drawing.Imaging.Encoder ImageEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameter ep = new EncoderParameter(ImageEncoder, 100L); EncoderParameters eps = new EncoderParameters(1); ImageCodecInfo ImageCoderType = getImageCoderInfo("image/jpeg"); eps.Param[0] = ep; img.Save(tempPic, ImageCoderType, eps); //img.Save(tempPic, ImageFormat.Jpeg); } } int blackSecond = 300; //计算后黑时长 if (BlackSecondComboBox.Text == "auto") { int seconds = SecondsFromHHMMSS(MI.Get(StreamKind.General, 0, "Duration/String3")); double s = videobitrate / 1000.0 * (double)seconds / targetBitrate - (double)seconds; blackSecond = (int)s; BlackSecondComboBox.Text = blackSecond.ToString(); } else { blackSecond = int.Parse(Regex.Replace(BlackSecondComboBox.Text.ToString(), @"\D", "")); //排除除数字外的所有字符 } //批处理 mux = "\"" + workPath + "\\ffmpeg\" -loop 1 -r " + BlackFPSNum.Value.ToString() + " -t " + blackSecond.ToString() + " -f image2 -i \"" + tempPic + "\" -c:v libx264 -crf " + BlackCRFNum.Value.ToString() + " -y black.flv\r\n"; mux += string.Format("\"{0}\\flvbind\" \"{1}\" \"{2}\" black.flv\r\n", workPath, BlackOutputTextBox.Text, BlackVideoTextBox.Text); mux += "del black.flv\r\n"; batpath = Path.Combine(workPath, Path.GetRandomFileName() + ".bat"); File.WriteAllText(batpath, mux, Encoding.Default); LogRecord(mux); Process.Start(batpath); }
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); }
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 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 }
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 { } }
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; }