コード例 #1
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            pictureBox1.Image.Dispose();
            step = (int)numericUpDown1.Value;
            var ffProbe   = new NReco.VideoInfo.FFProbe();
            var videoInfo = ffProbe.GetMediaInfo(inputFile);
            var video     = VideoInfo.FromPath(inputFile);

            if (Directory.Exists(video.Directory + "\\" + video.Name + "_images"))
            {
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
                System.IO.Directory.Delete(video.Directory + "\\" + video.Name + "_images", true);
            }
            DBOPS.DeletePictures(vidId);
            System.IO.Directory.CreateDirectory(video.Directory + "\\" + video.Name + "_images");

            min                    = videoInfo.Duration.Minutes;
            sec                    = videoInfo.Duration.Seconds;
            maxframe               = (min * 60 + sec) / step;
            progressBar1.Maximum   = maxframe;
            progressBar1.Value     = 0;
            progressBar1.Step      = 1;
            kryptonButton1.Enabled = false;
            nButton.Visible        = true;
            bButton.Visible        = true;
            this.workerThread      = new Thread(new ThreadStart(this.BatchCalc2));
            this.workerThread.Start();
        }
コード例 #2
0
        public string GetSectionLessons(string sec)
        {
            StringBuilder sb = new StringBuilder();

            section sc = db.sections.Find(Convert.ToInt32(sec));
            int order = 1;

                foreach (lesson ls in sc.lessons)
                {
                    string complete = "text-grey-200";
                    int id = db.profiles.Where(p => p.email == HttpContext.Current.User.Identity.Name).FirstOrDefault().id;

                    userlesson ul = db.userlessons.FirstOrDefault(c => c.lessonId == ls.id && c.userId == id);
                    if(ul != null)
                    {
                        complete = "text-green-200";
                    }
                    var videoduration = new NReco.VideoInfo.FFProbe().GetMediaInfo(Server.MapPath("../" + ls.videoFile)).Duration;
                    string du = videoduration.Hours + ":" + videoduration.Minutes + ":" + videoduration.Seconds + " ";
                    // param 0 = status     &&    param 1 = order     &&    param 2 = title      &&    param 3 = duration
                    sb.Append(string.Format("<div class=\"list-group-item media {0}\" data-target=\"mylesson?id={5}\"><div class=\"media-left\"><div class=\"text-crt\">{1}</div></div><div class=\"media-body\"><i class=\"fa fa-fw fa-circle {4}\"></i>{2}</div><div class=\"media-right\"><div class=\"width-100 text-right text-caption\">{3}  min</div></div></div>", " ", order, ls.title, du,complete,ls.id ));
                    order ++;
                }

            return sb.ToString();
        }
コード例 #3
0
        static async Task <MemoryStream> getFrameFromVideo(float startTime)
        {
            Stream rawBmpOutputStream = new MemoryStream();
            var    ffProbe            = new NReco.VideoInfo.FFProbe();
            var    videoInfo          = ffProbe.GetMediaInfo(path);
            var    convertSettings    = new ConvertSettings()
            {
                VideoFrameSize = "1280*720", // lets resize to exact frame size
                VideoFrameRate = 24,         // lets consume 24 frames per second
                MaxDuration    = 1           // lets consume live stream for first 5 seconds
            };

            convertSettings.Seek = startTime;
            var videoConv  = new FFMpegConverter();
            var ffMpegTask = videoConv.ConvertLiveMedia(
                path,
                null,               // autodetect live stream format
                rawBmpOutputStream, // this is your special stream that will capture bitmaps
                Format.gif,
                convertSettings);

            ffMpegTask.Start();
            ffMpegTask.Wait();
            return((MemoryStream)rawBmpOutputStream);
        }
コード例 #4
0
        private void treeView2_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (Int32.Parse(e.Node.Tag.ToString()) != -1)
            {
                //vidTreeRefresh(Int32.Parse(e.Node.Tag.ToString()), e.Node.Text);
                var vid = DBOPS.GetVid(Int32.Parse(e.Node.Tag.ToString()));
                pics      = DBOPS.GetImagesList(Int32.Parse(e.Node.Tag.ToString()));
                pics      = pics.OrderBy(i => i.Id).ToList();
                vidDiag   = vid.Diag;
                vidId     = Int32.Parse(e.Node.Tag.ToString());
                inputFile = System.IO.Directory.GetCurrentDirectory() + vid.Path;
                var ffProbe   = new NReco.VideoInfo.FFProbe();
                var videoInfo = ffProbe.GetMediaInfo(inputFile);
                video          = new VideoInfo(inputFile);
                count          = 0;
                globalTimeSpan = new TimeSpan(0, 0, 0, 0);
                textBox2.Text  = vidDiag;

                videoLength = videoInfo.Duration;
                string output1 = videoInfo.Duration.ToString();
                //label3.Text = pat.FIO;
                //label2.Text = pat.Bdate.ToString("dd/MM/yyyy");
                //label5.Text = pat.Pdate.ToString("dd/MM/yyyy");
                label10.Text           = output1;
                kryptonButton1.Enabled = true;
                panel4.Enabled         = true;

                bool splitted = DBOPS.ExistPicturesCheck(vidId);
                if (splitted)
                {
                    nButton.Visible      = true;
                    bButton.Visible      = true;
                    nButton.Enabled      = true;
                    bButton.Enabled      = true;
                    pictureBox1.Image    = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + pics[imgnum].path);
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                    label15.Text         = "Текущий снимок:";
                    label16.Text         = (imgnum + 1) + " из " + pics.Count + " (" + pics[imgnum].timestamp + ")";
                }
                else
                {
                    nButton.Visible = false;
                    bButton.Visible = false;
                    TimeSpan duration = new TimeSpan(0, 0, 0, 0);
                    string   outstr   = video.Directory + "\\" + video.Name + " - " + duration.ToString(@"hh\_mm\_ss") + ".jpg";
                    label15.Text = "Текущая отметка:";
                    label16.Text = duration.ToString(@"hh\:mm\:ss");
                    FileInfo output = new FileInfo(outstr);
                    Bitmap   img    = new FFMpeg().Snapshot(
                        video,
                        output,
                        new Size(video.Width, video.Height),
                        duration
                        );
                    pictureBox1.Image    = img;
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                }
            }
        }
コード例 #5
0
        private int Duration(string path)
        {
            var ffProbe   = new NReco.VideoInfo.FFProbe();
            var videoInfo = ffProbe.GetMediaInfo(path);

            int count = videoInfo.Duration.Seconds + videoInfo.Duration.Minutes * 60 + videoInfo.Duration.Hours * 60 * 60;

            return(count);
        }
コード例 #6
0
        private float GetVideoDuration(string videosource)
        {
            var    ffProbe    = new NReco.VideoInfo.FFProbe();
            var    videoInfo  = ffProbe.GetMediaInfo(videosource);
            double duration   = videoInfo.Duration.TotalSeconds;
            float  f_duration = (float)duration;

            return(f_duration);
        }
コード例 #7
0
        public double getVidFPS(string VideoPath)
        {
            string ffprobPath = _env.ContentRootPath + "/wwwroot/ffmpeg/ffprob.exe";

            var ffprob = new NReco.VideoInfo.FFProbe();

            ffprob.ToolPath = _env.ContentRootPath + "/wwwroot/ffmpeg/";

            var   videoInfo = ffprob.GetMediaInfo(VideoPath);
            float fps       = videoInfo.Streams[0].FrameRate;

            return(Convert.ToDouble(fps));
        }
コード例 #8
0
        internal bool updateInfo()
        {
            try
            {
                if (fileInfo == null || fileInfo.Exists == false || fileInfo.DirectoryName.Contains(@":\$RECYCLE.BIN\"))
                {
                    return(false);
                }

                DateTime start     = DateTime.Now;
                var      ffProbe   = new NReco.VideoInfo.FFProbe();
                var      videoInfo = ffProbe.GetMediaInfo(fileInfo.FullName);

                durationMs = videoInfo.Duration.TotalMilliseconds;
                Duration   = string.Format("{0}:{1}:{2}", videoInfo.Duration.Hours, videoInfo.Duration.Minutes, videoInfo.Duration.Seconds);
                if (Duration.StartsWith("0:"))
                {
                    Duration = Duration.Substring(2);
                }
                SizeByte = fileInfo.Length;
                SizeMb   = (int)(fileInfo.Length / (1024 * 1024.0));
                Bitrate  = Math.Round((SizeByte / 1024.0) / (durationMs / 1000.0));

                string formatVideo = "";
                string formatAudio = "";
                for (int i = 0; i < videoInfo.Streams.Length; i++)
                {
                    if (videoInfo.Streams[i].CodecType == "video")
                    {
                        formatVideo += videoInfo.Streams[i].CodecName + " ";
                    }
                    else
                    {
                        formatAudio += videoInfo.Streams[i].CodecName + " ";
                    }
                }
                Format = formatVideo + formatAudio.Trim();

                Status = EnEncoding.HasInfo;

                //GenFunc.LogAddInfo(this,"updateInfo", "Time: " + Math.Round((DateTime.Now - start).TotalMilliseconds) + " [ms]");
                return(true);
            }
            catch (Exception ex)
            {
                GenFunc.LogAdd(ex);
                Status = EnEncoding.Error;
            }
            return(false);
        }
コード例 #9
0
 /// <summary>
 /// 获取视频文件长度;
 /// </summary>
 /// <param name="pathToVideoFile"></param>
 /// <returns></returns>
 public static int GetMediaTimeLenSecond(string pathToVideoFile)
 {
     try
     {
         var ffProbe = new NReco.VideoInfo.FFProbe();
         // ffProbe.FFProbeExeName = @"E:\ffmpeg-20190310-5ab44ff-win64-static\bin\ffprobe.exe";
         var videoInfo = ffProbe.GetMediaInfo(pathToVideoFile);
         return((int)videoInfo.Duration.TotalSeconds);
     }
     catch (Exception ex)
     {
         string xx = ex.Message;
         return(0);
     }
 }
コード例 #10
0
        /// <summary>
        /// Add new media to the favorite playlist
        /// </summary>
        /// <param name="sender"></param>
        private void addMediaMethod(object sender)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "Audio files (*.mp3 *.wav *.flac *.ogg)|*.mp3; *.wav; *.flac; *.ogg|Video files (*.mp4 *.avi *.flv *.wmv *.mov)|*.mp4; *.avi; *.flv; *.wmv; *.mov|All files (*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
            {
                IsRemoveMediaEnabled = true;
                MediaSingleElement selectedMedia = new MediaSingleElement();
                selectedMedia.Title    = Path.GetFileNameWithoutExtension(openFileDialog.FileName);
                selectedMedia.mediaUri = openFileDialog.FileName;
                var ffProbe   = new NReco.VideoInfo.FFProbe();
                var videoInfo = ffProbe.GetMediaInfo(openFileDialog.FileName);
                selectedMedia.MediaDuration = videoInfo.Duration.ToString(@"mm\:ss");
                ListOfMedia.Add(selectedMedia);

                selectedMedia.Extension = Path.GetExtension(openFileDialog.FileName);
                getIconImage(selectedMedia, selectedMedia.Extension);
            }
        }
コード例 #11
0
        private void openRightVideoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog2.ShowDialog();

            if (result == DialogResult.OK)
            {
                var ffProbe   = new NReco.VideoInfo.FFProbe();
                var videoInfo = ffProbe.GetMediaInfo(openFileDialog2.FileName);

                if (videoInfo.Streams.Length < 1)
                {
                    return;
                }

                axWindowsMediaPlayer2.Size = new Size(videoInfo.Streams[0].Width, videoInfo.Streams[0].Height);

                axWindowsMediaPlayer2.URL = openFileDialog2.FileName;

                axWindowsMediaPlayer2.Ctlcontrols.stop();
            }
        }
コード例 #12
0
        public static bool IsVideo(string FilePath)
        {
            try
            {
                NReco.VideoInfo.FFProbe   ffProbe   = new NReco.VideoInfo.FFProbe();
                NReco.VideoInfo.MediaInfo videoInfo = ffProbe.GetMediaInfo(FilePath);

                if (videoInfo.Duration.Seconds > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            catch (Exception ex)
            {
                return(false);
            }
        }
コード例 #13
0
        private void GenerageVideoThumbnail(MediabankEntity file, string fullFileName, string fileName, int percentIntoVideo = 50)
        {
            try
            {
                var   ffMpeg             = new NReco.VideoConverter.FFMpegConverter();
                float thumbnailTimeStart = 0;

                var ffp       = new NReco.VideoInfo.FFProbe();
                var videoInfo = ffp.GetMediaInfo(fullFileName);

                thumbnailTimeStart = (float)((videoInfo.Duration.TotalSeconds * percentIntoVideo) / 100);

                string newFullFileName = $@"{fullFileName.Replace(file.FileExtension, string.Empty)}_Thumbnail.jpg";

                ffMpeg.GetVideoThumbnail(fullFileName, newFullFileName, thumbnailTimeStart);

                file.Thumbnail = $@"/Uploads/Mediabank/{file.ClubId}/{fileName.Replace(file.FileExtension, string.Empty)}_Thumbnail.jpg";
            }
            catch (Exception ex)
            {
                LogHelper.LogError($"Error generating video thumbnail.", ex, file.ClubId);
            }
        }
コード例 #14
0
        public int getFramesTotal(string videoPath, double fps)
        {
            string duration    = "";
            double totalFrames = 0;


            string ffprobPath = _env.ContentRootPath + "/wwwroot/ffmpeg/";
            var    ffProbe    = new NReco.VideoInfo.FFProbe();

            ffProbe.ToolPath = ffprobPath;
            var videoInfo = ffProbe.GetMediaInfo(videoPath);

            duration = videoInfo.Duration.ToString();

            string[] time = duration.Split(':', '.');

            totalFrames += Convert.ToInt32(time[0]) * 3600 * fps;
            totalFrames += Convert.ToInt32(time[1]) * 60 * fps;
            totalFrames += Convert.ToInt32(time[2]) * fps;
            totalFrames += (Convert.ToInt32(time[3]) / 10000);

            return(Convert.ToInt32(totalFrames));
        }
コード例 #15
0
        static void Main(string[] args)
        {
            int TotalCount       = 0;
            var workingDirectory = "";
            var defaultDirectory = ConfigurationManager.AppSettings["DefaultDirectory"];
            var outputFileName   = ConfigurationManager.AppSettings["ListOutputFilename"];

            if (args.Length == 0)
            {
                foreach (var arg in args)
                {
                    workingDirectory += arg;
                }
            }
            workingDirectory = String.IsNullOrWhiteSpace(workingDirectory) ? defaultDirectory : workingDirectory;
            var workingDirectoryHandle = Directory.EnumerateDirectories(workingDirectory);
            var output = new StringBuilder();

            output.Append($"<ul>");
            foreach (var directoryName in workingDirectoryHandle)
            {
                var result = RecurseDirectory(directoryName);
                TotalCount += result.Item2;
                output.Append(result.Item1);
            }
            if (Directory.EnumerateFiles(workingDirectory).Count() > 0)
            {
                var RunningTotal = new TimeSpan();
                output.AppendLine($"<b>Titles (ESTIMATED start at {PlannedStartTime} Pacific Time).<b>");
                output.AppendLine($"<ul class='sublist'>");
                foreach (var fName in Directory.EnumerateFiles(workingDirectory))
                {
                    // Skip our non video files by default.
                    if (fName.Contains(".mp4") ||
                        fName.Contains(".avi") ||
                        fName.Contains(".mpg") ||
                        fName.Contains(".mkv") ||
                        fName.Contains(".divx") ||
                        fName.Contains(".mov"))
                    {
                        output.AppendLine($"<li>");
                        var ffProbe       = new NReco.VideoInfo.FFProbe();
                        var mediaInfo     = ffProbe.GetMediaInfo(fName);
                        var cleanFileName = fName.Replace(workingDirectory, "");
                        cleanFileName = cleanFileName.Replace(@".mp4", "");
                        cleanFileName = cleanFileName.Replace(@".mkv", "");
                        cleanFileName = cleanFileName.Replace(@".mpg", "");
                        cleanFileName = cleanFileName.Replace(@".avi", "");
                        output.Append($"<i>{cleanFileName}</i> - Estimated Start Time {RunningStartTime}");
                        RunningStartTime = RunningStartTime.Add(mediaInfo.Duration);
                        RunningTimeSpan  = RunningTimeSpan.Add(mediaInfo.Duration);
                        RunningTotal    += mediaInfo.Duration;
                        output.AppendLine($"</li>");
                    }
                }
                output.AppendLine($"<li>Directory Duration: {RunningTotal.Days} days {RunningTotal.Hours} hours {RunningTotal.Minutes} minutes</li>");
                output.AppendLine($"</ul>");
            }
            output.AppendLine($"<li>Total Titles: {TotalCount}</li>");
            output.AppendLine($"<li>Total Runtime: {RunningTimeSpan}</li>");
            output.AppendLine("</ul>");
            var outputStream       = new FileStream(workingDirectory + outputFileName, FileMode.OpenOrCreate);
            var outputStreamWriter = new StreamWriter(outputStream);

            outputStreamWriter.WriteLine(output);
            outputStreamWriter.Flush();
            outputStreamWriter.Close();
            outputStream.Close();
        }
コード例 #16
0
        private static void GetThumbnailApp(string video, string thumbnail, string smallThumbUrl, string smallThumbUrljpg, string OsType)
        {
            try
            {
                #region Scale & FrameRate
                var frameRate     = 15;
                var scale         = "420:-1";
                var scaleSmall    = "70x70";
                var scaleSmallJPG = "";

                string height       = "";
                string width        = "";
                int    Heightreduce = 3; //1920
                int    widthreduce  = 3; //1080
                try
                {
                    var ffProbe   = new NReco.VideoInfo.FFProbe();
                    var videoInfo = ffProbe.GetMediaInfo(video);
                    foreach (var stream in videoInfo.Streams)
                    {
                        frameRate = Convert.ToInt16(stream.FrameRate);
                        if (stream.Width > 420 && stream.Height < 560)
                        {
                            scale = "420x560";
                            if (OsType == "android")
                            {
                                frameRate     = 25;
                                height        = (stream.Height / (stream.Height * Heightreduce)).ToString();
                                width         = (stream.Width - (stream.Width / widthreduce)).ToString();
                                scale         = stream.Height + "x" + stream.Width;
                                scaleSmallJPG = stream.Height + "x" + stream.Width;
                            }
                            else
                            {
                                //scaleSmallJPG = stream.Width + "x" + stream.Height;
                                scale         = stream.Width + "x" + stream.Height;
                                scaleSmallJPG = scale;
                            }
                        }
                        else
                        {
                            if (stream.Height > 0 && stream.Width > 0)
                            {
                                scale = stream.Width + "x" + stream.Height;
                                if (OsType == "android")
                                {
                                    //height = (stream.Height - (stream.Height * Heightreduce / 100)).ToString();
                                    //width = (stream.Width - (stream.Width * widthreduce / 100)).ToString();
                                    //scale = stream.Height + "x" + stream.Width;
                                    //scaleSmallJPG = stream.Height + "x" + stream.Width;
                                    frameRate     = 25;
                                    height        = (stream.Height / Heightreduce).ToString();
                                    width         = (stream.Width / widthreduce).ToString();
                                    scale         = height + "x" + width;
                                    scaleSmallJPG = height + "x" + width;
                                }
                                else
                                {
                                    //scaleSmallJPG = stream.Width + "x" + stream.Height;
                                    scale         = stream.Width + "x" + stream.Height;
                                    scaleSmallJPG = scale;
                                }
                                //scale = "1280x720";
                                break;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    frameRate     = 15;
                    scale         = "420:-1";
                    scaleSmallJPG = "420:-1";
                }
                #endregion

                if (frameRate < 0)
                {
                    frameRate = 25;
                }

                var    ffmpeg        = CodeLibrary.SavePath() + @"\ffmpeg.exe";
                string pngimage      = CodeLibrary.SavePath() + @"\Images\Palette\palette_" + Guid.NewGuid() + ".png";
                string pngSmallimage = CodeLibrary.SavePath() + @"\Images\iconPalette\palette_" + Guid.NewGuid() + ".png";

                var processPalette = new Process();
                var processGif     = new Process();

                var processSmallPalette = new Process();
                var processSmallGif     = new Process();
                var processSmallJPG     = new Process();
                try
                {
                    #region Large Thumbnail
                    var infoPalette = new ProcessStartInfo(ffmpeg, " -y -t 3 -i " + video + " -vf fps=" + frameRate + ",scale=" + scale + ":flags=lanczos,palettegen " + pngimage)
                    {
                        CreateNoWindow         = false,
                        UseShellExecute        = false,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true
                    };
                    processPalette.StartInfo           = infoPalette;
                    processPalette.EnableRaisingEvents = true;
                    processPalette.Start();
                    processPalette.BeginOutputReadLine();
                    processPalette.BeginErrorReadLine();
                    processPalette.WaitForExit();
                    processPalette.Close();

                    var infoGif = new ProcessStartInfo(ffmpeg, " -t 3 -i " + video + " -i " + pngimage + " -filter_complex \"fps=" + frameRate + ",scale=" + scale + ":flags=lanczos[x];[x][1:v]paletteuse\" " + thumbnail)
                    {
                        CreateNoWindow         = false,
                        UseShellExecute        = false,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true
                    };
                    processGif.StartInfo           = infoGif;
                    processGif.EnableRaisingEvents = true;
                    processGif.Start();
                    processGif.BeginOutputReadLine();
                    processGif.BeginErrorReadLine();
                    processGif.WaitForExit();
                    processGif.Close();
                    #endregion

                    #region Small Thumbnail
                    var ext       = Path.GetExtension(video);
                    var startTime = "";
                    if (ext != ".jpg")
                    {
                        startTime = "-ss 2";
                    }
                    var infoSmallPalette = new ProcessStartInfo(ffmpeg, " -y " + startTime + " -t 3 -i " + video + " -vf fps=" + frameRate + ",scale=" + scaleSmall + ":flags=lanczos,palettegen " + pngSmallimage)
                    {
                        CreateNoWindow         = false,
                        UseShellExecute        = false,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true
                    };
                    processSmallPalette.StartInfo           = infoSmallPalette;
                    processSmallPalette.EnableRaisingEvents = true;
                    processSmallPalette.Start();
                    processSmallPalette.BeginOutputReadLine();
                    processSmallPalette.BeginErrorReadLine();
                    processSmallPalette.WaitForExit();
                    processSmallPalette.Close();

                    var infoSmallGif = new ProcessStartInfo(ffmpeg, " " + startTime + " -t 3 -i " + video + " -i " + pngSmallimage + " -filter_complex \"fps=" + frameRate + ",scale=" + scaleSmall + ":flags=lanczos[x];[x][1:v]paletteuse\" " + smallThumbUrl)
                    {
                        CreateNoWindow         = false,
                        UseShellExecute        = false,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true
                    };
                    processSmallGif.StartInfo           = infoSmallGif;
                    processSmallGif.EnableRaisingEvents = true;
                    processSmallGif.Start();
                    processSmallGif.BeginOutputReadLine();
                    processSmallGif.BeginErrorReadLine();
                    processSmallGif.WaitForExit();
                    processSmallGif.Close();
                    #endregion

                    #region Small Thumbnail JPG



                    var infoSmallJPG = new ProcessStartInfo(ffmpeg, " -t 3 -i " + video + " -i " + pngimage + " -filter_complex \"fps=" + frameRate + ",scale=" + scaleSmallJPG + ":flags=lanczos[x];[x][1:v]paletteuse\" " + smallThumbUrljpg)
                    {
                        CreateNoWindow         = false,
                        UseShellExecute        = false,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true
                    };
                    processSmallJPG.StartInfo           = infoSmallJPG;
                    processSmallJPG.EnableRaisingEvents = true;
                    processSmallJPG.Start();
                    processSmallJPG.BeginOutputReadLine();
                    processSmallJPG.BeginErrorReadLine();
                    processSmallJPG.WaitForExit();
                    processSmallJPG.Close();
                    #endregion

                    #region Remove Image/Video

                    //if ((File.Exists(video)))
                    //    File.Delete(video);

                    #endregion
                }
                catch (Exception ex)
                {
                    processPalette.Close();
                    processGif.Close();

                    processSmallPalette.Close();
                    processSmallGif.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #17
0
        public static Tuple <string, int> RecurseDirectory(string DirectoryName)
        {
            int count        = 0;
            var RunningTotal = new TimeSpan();
            var output       = new StringBuilder();

            output.AppendLine($"<li>");
            var cleanDirectory       = DirectoryName.Replace(Directory.GetParent(DirectoryName).FullName + "\\", "");
            var directoryEnumeration = Directory.EnumerateDirectories(DirectoryName);

            if (directoryEnumeration.Count() > 0)
            {
                output.AppendLine($"<b><h1>{cleanDirectory} estimated to start at {RunningStartTime}</h1></b>");
            }
            else
            {
                output.AppendLine(cleanDirectory);
            }
            output.AppendLine($"<ul class='sublist'>");
            foreach (var fName in Directory.EnumerateFiles(DirectoryName))
            {
                if (fName.Contains(".mp4") ||
                    fName.Contains(".avi") ||
                    fName.Contains(".mpg") ||
                    fName.Contains(".mkv") ||
                    fName.Contains(".divx") ||
                    fName.Contains(".mov"))
                {
                    output.AppendLine($"<li>");
                    var ffProbe = new NReco.VideoInfo.FFProbe();
                    try {
                        var mediaInfo = ffProbe.GetMediaInfo(fName);
                        RunningTotal += mediaInfo.Duration;
                        var cleanFileName = fName.Replace(DirectoryName, "");
                        cleanFileName = cleanFileName.Replace(@".mp4", "");
                        cleanFileName = cleanFileName.Replace(@".mpg", "");
                        cleanFileName = cleanFileName.Replace(@".mkv", "");
                        cleanFileName = cleanFileName.Replace(@".mov", "");
                        cleanFileName = cleanFileName.Replace(@".avi", "");
                        cleanFileName = cleanFileName.Replace(@".divx", "");
                        output.Append($"<div class='starttime'>{RunningStartTime}</div><div class='filename'><i>{cleanFileName}</i></div>");
                        RunningStartTime = RunningStartTime.Add(mediaInfo.Duration);
                        RunningTimeSpan  = RunningTimeSpan.Add(mediaInfo.Duration);
                        output.AppendLine($"</li>");
                    }
                    catch (Exception ex)
                    {
                        var cleanFileName = fName.Replace(DirectoryName, "");
                        cleanFileName = cleanFileName.Replace(@".mp4", "");
                        cleanFileName = cleanFileName.Replace(@".mpg", "");
                        cleanFileName = cleanFileName.Replace(@".mkv", "");
                        cleanFileName = cleanFileName.Replace(@".mov", "");
                        cleanFileName = cleanFileName.Replace(@".avi", "");
                        cleanFileName = cleanFileName.Replace(@".divx", "");
                        output.Append($"<div class='starttime'>{RunningStartTime}</div><div class='filename'><i>{cleanFileName}</i></div>");
                        // assume an average length of 25 minutes based on what normally failed for me and the average length of those things
                        // ideally though, you'd want to remove these from the list and identify/re-source.
                        RunningStartTime = RunningStartTime.Add(new TimeSpan(0, 25, 0));
                        RunningTimeSpan  = RunningTimeSpan.Add(new TimeSpan(0, 25, 0));
                        output.AppendLine($"</li>");
                    }
                    count++;
                }
            }
            output.AppendLine($"<li>Directory Duration: {RunningTotal.Days} days {RunningTotal.Hours} hours {RunningTotal.Minutes} minutes</li>");
            output.AppendLine($"</ul>");
            if (directoryEnumeration != null && directoryEnumeration.Count() > 0)
            {
                foreach (string s in directoryEnumeration)
                {
                    var outputResult = RecurseDirectory(s);
                    output.AppendLine("<ul>");
                    output.Append(outputResult.Item1);
                    count += outputResult.Item2;
                    output.AppendLine("</ul>");
                }
            }
            output.AppendLine($"</li>");
            Tuple <string, int> returnValue = new Tuple <string, int>(output.ToString(), count);

            return(returnValue);
        }
コード例 #18
0
        private static void DoWork(object sender, DoWorkEventArgs e)
        {
            // Long running background operation

            using (var edm_material = new db_transcriptEntities())
            {
                var i_material = (from c in edm_material.inf_material
                                  where c.id_estatus_material == 6
                                  select c).ToList();

                foreach (var item in i_material)
                {
                    string str_path_ini, str_path_fin;

                    using (db_transcriptEntities data_path = new db_transcriptEntities())
                    {
                        var count_path = (from c in data_path.inf_ruta_videos
                                          select c).FirstOrDefault();

                        str_path_fin = count_path.desc_ruta_fin;
                        str_path_ini = count_path.desc_ruta_fin + "\\" + str_video;
                    }

                    str_path_ini = str_path_fin + "\\" + item.archivo.ToString().Replace(".mp4", ".wmv");

                    string str_file_save = str_path_ini.ToString();
                    string str_save_file = str_path_ini.ToString().Replace(".wmv", ".mp4");
                    var    ffMpeg        = new NReco.VideoConverter.FFMpegConverter();

                    var ffProbe   = new NReco.VideoInfo.FFProbe();
                    var videoInfo = ffProbe.GetMediaInfo(str_file_save);

                    string str_duration_wmv = videoInfo.Duration.Hours + ":" + videoInfo.Duration.Minutes + ":" + videoInfo.Duration.Seconds;

                    try
                    {
                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 6;

                            data_mat.SaveChanges();
                        }

                        var two_user = new int?[] { 6 };

                        ffMpeg.ConvertMedia(str_file_save, str_save_file, Format.mp4);


                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 1;

                            data_mat.SaveChanges();
                        }

                        two_user = new int?[] { 1 };
                    }
                    catch
                    {
                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 5;

                            data_mat.SaveChanges();
                        }
                    }
                    var videoInfo_mp4 = ffProbe.GetMediaInfo(str_file_save);

                    string str_duration_mp4 = videoInfo_mp4.Duration.Hours + ":" + videoInfo_mp4.Duration.Minutes + ":" + videoInfo_mp4.Duration.Seconds;

                    if (str_duration_wmv == str_duration_mp4)
                    {
                        File.Delete(str_file_save);
                    }
                    else
                    {
                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 5;
                            data_mat.SaveChanges();
                        }
                    }
                }
            }
        }
コード例 #19
0
ファイル: Main.cs プロジェクト: eveloki/MediaInfoHelp
        public void GetInfo(string file)
        {
            string mainbasefile = basepath + "MB\\1.txt";
            string mbstring     = System.IO.File.ReadAllText(mainbasefile, Encoding.UTF8);

            if (!m_ready)
            {
                string msg = "程序没有正确初始化 err 001";
                SetrichTextBox1(msg);
                MessageBox.Show(msg);
                return;
            }
            string name = System.IO.Path.GetFileNameWithoutExtension(file);
            string type = System.IO.Path.GetExtension(file);

            type = type.ToLower();
            switch (type)
            {
            case ".mkv":
            case ".mp4":
            case ".flv":
                try
                {
                    using (var mediaInfo = new MediaInfo.DotNetWrapper.MediaInfo())
                    {
                        string text = "";
                        text += "\r\n\r\nOpen\r\n";
                        mediaInfo.Open(file);

                        //text += "\r\n\r\nInform with Complete=false\r\n";
                        //mediaInfo.Option("Complete");
                        //text += mediaInfo.Inform();

                        string sss = mediaInfo.Inform();

                        var fistinfp = GetKeyValues(sss);
                        //编码时间
                        string reeeeddd     = fistinfp.FirstOrDefault(T => T.key == "Encoded date").value;
                        var    RELEASE_DATE = reeeeddd.Split(' ')[1];
                        mbstring = mbstring.Replace("{RELEASE DATE}", RELEASE_DATE);

                        //文件大小
                        var RELEASE_SiZE = fistinfp.FirstOrDefault(T => T.key == "File size").value;
                        mbstring = mbstring = mbstring.Replace("{RELEASE SiZE}", RELEASE_SiZE);

                        //播放时间
                        //var RUNTiME = fistinfp.FirstOrDefault(T => T.key == "Duration").value;
                        //mbstring = mbstring.Replace("{RUNTiME}", RUNTiME);

                        //色深
                        var Bit_depth = fistinfp.FirstOrDefault(T => T.key == "Bit depth").value;
                        mbstring = mbstring.Replace("{BIT DEPTH}", Bit_depth);

                        //编码
                        var ViDEO_CODEC = fistinfp.FirstOrDefault(T => T.key == "Format profile").value;

                        var Bit_rate = fistinfp.FirstOrDefault(T => T.key == "Bit rate").value;

                        Bit_rate = Bit_rate.Replace("kb/s", "Kbps");
                        Bit_rate = Bit_rate.Replace("mb/s", "Mbps");
                        mbstring = mbstring.Replace("{Bit_rate}", Bit_rate);


                        //高宽
                        var Width = fistinfp.FirstOrDefault(T => T.key == "Width").value.Replace(" pixels", "");
                        Width = Width.Replace(" ", "");
                        var Height = fistinfp.FirstOrDefault(T => T.key == "Height").value.Replace(" pixels", "");
                        Height = Height.Replace(" ", "");
                        //像素比
                        var RESOLUTiON = Width + " x " + Height;
                        mbstring = mbstring.Replace("{RESOLUTiON}", RESOLUTiON);

                        //高宽比
                        var DiSPLAY_ASPECT_RATiO = fistinfp.FirstOrDefault(T => T.key == "Display aspect ratio").value;
                        mbstring = mbstring.Replace("{DiSPLAY ASPECT RATiO}", DiSPLAY_ASPECT_RATiO);

                        //fps
                        var FRAME_RATE = fistinfp.FirstOrDefault(T => T.key == "Frame rate").value;
                        mbstring = mbstring.Replace("{FRAME RATE}", FRAME_RATE);



                        mediaInfo.Option("Complete", "1");
                        var s2        = mediaInfo.Inform();
                        var fistinfp2 = GetKeyValues(s2);


                        var Encoded_Library_Name = fistinfp2.FirstOrDefault(T => T.key == "Encoded_Library_Name").value;
                        var Format_profile       = fistinfp2.FirstOrDefault(T => T.key == "Format profile").value;
                        Format_profile += "";


                        //string Encoded_Library_Name = mediaInfo.Get(StreamKind.Video,0, "Encoded_Library_Name");

                        //string Format_profile = mediaInfo.Get(StreamKind.Video, 0, "Format profile",InfoKind.Name);
                        //Format_profile += " Tier";

                        //string Frame_rate = mediaInfo.Get(StreamKind.Video, 0, "Frame rate", InfoKind.Name);
                        //text += "\r\n\r\nInform with Complete=true\r\n";
                        //mediaInfo.Option("Complete", "1");
                        //text += mediaInfo.Inform();

                        //text += "\r\n\r\nCustom Inform\r\n";
                        //mediaInfo.Option("Inform", "General;File size is %FileSize% bytes");
                        //text += mediaInfo.Inform();

                        //foreach (string param in new[] { "BitRate", "BitRate/String", "BitRate_Mode" })
                        //{
                        //    text += "\r\n\r\nGet with Stream=Audio and Parameter='" + param + "'\r\n";
                        //    text += mediaInfo.Get(StreamKind.Audio, 0, param);
                        //}

                        //text += "\r\n\r\nGet with Stream=General and Parameter=46\r\n";
                        //text += mediaInfo.Get(StreamKind.General, 0, 46);

                        //text += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n";
                        //text += mediaInfo.CountGet(StreamKind.Audio);

                        //text += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n";
                        //text += mediaInfo.Get(StreamKind.General, 0, "AudioCount");

                        //text += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n";
                        //text += mediaInfo.Get(StreamKind.Audio, 0, "StreamCount");
                        SetrichTextBox1(text);
                    }



                    //ffmpeg部分
                    var ffProbe   = new NReco.VideoInfo.FFProbe();
                    var videoInfo = ffProbe.GetMediaInfo(file);



                    //播放时间
                    string sj = ToReadableString(videoInfo.Duration);
                    mbstring = mbstring.Replace("{RUNTiME}", sj);



                    richTextBox2.Text = "";
                    richTextBox2.Text = mbstring;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误 请将输出提供给开发人员");
                    SetrichTextBox1(ex.ToString());
                }
                break;

            default:
                string msg = "不支持文件格式";
                SetrichTextBox1(msg);
                MessageBox.Show(msg);
                break;
            }
        }
コード例 #20
0
        static void Main(string[] args)
        {
            GifImage a;

            Console.CursorSize = 8;
            path       = Console.ReadLine();
            imageList  = new List <byte[]> {
            };
            frameCount = 0;
            //check if file is gif or video
            string ext = Path.GetExtension(path);

            if (ext.Equals(".gif"))
            {
                try
                {
                    a = new GifImage(path)
                    {
                        ReverseAtEnd = false
                    };
                    Timer timer = new Timer((object o) => TimerTick(o, ref a), null, 0, 60);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            //gif
            else
            {
                Stream rawBmpOutputStream = new MemoryStream();
                var    ffProbe            = new NReco.VideoInfo.FFProbe();
                var    videoInfo          = ffProbe.GetMediaInfo(path);

                var videoConv  = new FFMpegConverter();
                var ffMpegTask = videoConv.ConvertLiveMedia(
                    path,
                    null,               // autodetect live stream format
                    rawBmpOutputStream, // this is your special stream that will capture bitmaps
                    Format.gif,
                    new ConvertSettings()
                {
                    VideoFrameSize = "1280*720", // lets resize to exact frame size
                    VideoFrameRate = 24,         // lets consume 24 frames per second
                    MaxDuration    = 10          // lets consume live stream for first 5 seconds
                });
                ffMpegTask.Start();
                ffMpegTask.Wait();
                //var sr = new BinaryReader(rawBmpOutputStream);
                //sr.BaseStream.Position = 0;

                //using (var fileStream = File.Create(@"D:\test.gif"))
                //{
                //    rawBmpOutputStream.Seek(0, SeekOrigin.Begin);
                //    rawBmpOutputStream.CopyTo(fileStream);
                //}

                try
                {
                    a = new GifImage(rawBmpOutputStream)
                    {
                        ReverseAtEnd = false
                    };
                    Timer timer = new Timer((object o) => TimerTick(o, ref a), null, 0, 60);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            //video
            Console.WindowWidth  = Console.LargestWindowWidth;
            Console.WindowHeight = Console.LargestWindowHeight;
            // var t = new Timer((object o) => TimerTick(o, ref a), null, 0, 100);

            Console.ReadKey();
        }
コード例 #21
0
ファイル: WorkerThreads.cs プロジェクト: zachsteffens/ripper
        private void compressionThread(object sender, DoWorkEventArgs e)
        {
            while (isCompressionThreadRunning)
            {
                if (!currentlyCompressing && waitingToCompress.Count > 0)
                {
                    currentlyCompressing = true;
                    QueuedItem itemToCompress = waitingToCompress[0];
                    waitingToCompress.RemoveAt(0);

                    QueuedItem thisItem = (QueuedItem)queuedItems.Where(f => f.title == itemToCompress.title).FirstOrDefault();
                    thisItem.compressing = true;
                    //refresn the view
                    Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
                    {
                        lvInProgress.Items.Refresh();
                        lvInProgress.UpdateLayout();
                    }));
                    System.Diagnostics.Debug.WriteLine("compressing " + thisItem.title);
#if TESTINGNODISC
                    System.Threading.Thread.Sleep(22000);
#else
                    CompressWithHandbrake(thisItem);

                    //validate compression with nreco
                    try
                    {
                        var ffProbe   = new NReco.VideoInfo.FFProbe();
                        var videoInfo = ffProbe.GetMediaInfo(thisItem.pathToCompression);
                        Console.WriteLine(videoInfo.FormatName);
                    }
                    catch (Exception ex)
                    {
                        StringBuilder errormessage = new StringBuilder(ex.InnerException.ToString());
                        thisItem.failedCompressText = errormessage;
                        thisItem.failedCompression  = true;
                        notifier.Notify(mqttNotifyState.compress, "Compression Failed: " + errormessage.ToString());
                    }
#endif
                    System.Diagnostics.Debug.WriteLine("compression of " + thisItem.title + " complete");
                    thisItem.compressing = false;
                    if (thisItem.failedCompression != true)
                    {
                        thisItem.compressed = true;
                        waitingToCopy.Add(thisItem);
                    }

                    //refresn the view
                    Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
                    {
                        lvInProgress.Items.Refresh();
                        lvInProgress.UpdateLayout();
                    }));

                    currentlyCompressing = false;
                }
                else
                {
                    System.Threading.Thread.Sleep(10000);
                }
            }
        }
コード例 #22
0
        static void genVideos()
        {
            List <string> files = ScanFiles(srcDir, "*." + format);

            using (var progress = new ProgressBar())
            {
                int videoNow = 0;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Collect data...");
                Console.ForegroundColor = ConsoleColor.Gray;
                foreach (string item in files)
                {
                    FileInfo fi = new FileInfo(item);
                    if (format.Equals("*"))
                    {
                        if (!allowedFormats.Contains(fi.Extension.Replace(".", "").ToLower()))
                        {
                            continue;
                        }
                    }

                    var ffProbe = new NReco.VideoInfo.FFProbe();
                    ffProbe.ToolPath = binFiles;
                    try
                    {
                        var videoInfo = ffProbe.GetMediaInfo(item);

                        videoFile vid = new videoFile();
                        vid.name         = fi.Name.Replace(fi.Extension, "");
                        vid.duration_sec = (float)videoInfo.Duration.TotalSeconds;
                        vid.format       = fi.Extension.Replace(".", "").ToLower();
                        vid.path         = fi.FullName.Replace(@"\", @"/");
                        vid.size         = fi.Length;
                        vid.setSplitter();
                        if (ignoreSkip)
                        {
                            vid._skip = false;
                        }
                        videos.Add(vid);
                    }
                    catch (Exception e)
                    {
                        string errorFile = string.Format(@"{0}\{1}_error.txt", tmpDir, fi.Name);
                        Console.WriteLine("Error: {0}", fi.Name);
                        using (StreamWriter writer = new StreamWriter(errorFile, true))
                        {
                            writer.WriteLine("-----------------------------------------------------------------------------");
                            writer.WriteLine("Date : " + DateTime.Now.ToString());
                            writer.WriteLine();

                            while (e != null)
                            {
                                writer.WriteLine(e.GetType().FullName);
                                writer.WriteLine("Message : " + e.Message);
                                writer.WriteLine("StackTrace : " + e.StackTrace);

                                e = e.InnerException;
                            }
                        }

                        continue;
                    }

                    progress.Report((double)videoNow / files.Count);
                    videoNow++;
                }
            }
            breakLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write("Done.");
            Console.ForegroundColor = ConsoleColor.Gray;
            breakLine();
            videosToSplit = videos.Count(x => x._skip == false);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Total {0} files counted,", files.Count);
            Console.WriteLine("{0} will be processed.", videosToSplit);
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write("Show selected files? [y/n]");
            if (Console.ReadLine().ToLower().CompareTo("y") == 0)
            {
                Console.Write("\n\n");
                foreach (var v in videos.FindAll(x => x._skip == false))
                {
                    Console.WriteLine("{0} ({1} parts)", v.name, v._splitter.Count);
                }
            }
        }
コード例 #23
0
 public VideoInfoProvider()
 {
     FFProbe = new NReco.VideoInfo.FFProbe();
 }