private async void UpdatePosition(object sender, EventArgs e)
        {
            var downloaded = media.GetMediaInfo(file).Duration.TotalSeconds *downloader.Status.Progress;
            var seconds    = Player.MediaPosition / 10000000;

            TimeLine.Maximum   = downloaded;
            TimeLine.Value     = seconds;
            DownloadSpeed.Text = GetSpeed(downloader.Status.DownloadRate);
            UploadSpeed.Text   = GetSpeed(downloader.Status.UploadRate);
            SetValue(downloader.Status.Progress);
            CurrentTime.Text = GetTime(seconds) + "/" + GetTime((float)downloaded);
            if (seconds >= downloaded - 5)
            {
                Player.Pause();
                Middle.Visibility = Visibility.Visible;
                Middle.BeginStoryboard((Storyboard)FindResource("OpacityUp"));
                while ((media.GetMediaInfo(file).Duration.TotalSeconds *downloader.Status.Progress) - 10 > seconds)
                {
                    Animate();
                    await Task.Delay(1080);
                }
                var sb    = (Storyboard)FindResource("OpacityDown");
                var clone = sb.Clone();
                clone.Completed += (s, ev) => {
                    Middle.Visibility = Visibility.Collapsed;
                };
                sb.Begin(Middle);
                Player.Play();
            }
        }
        private VideoFileInfoSample GetVideo(Episode.ScannedFile file)
        {
            FFMpegConverter ffmpeg = new FFMpegConverter();
            FFProbe         probe  = new FFProbe();

            ffmpeg.FFMpegToolPath = probe.ToolPath = Environment.GetFolderPath(SpecialFolder.ApplicationData);
            var    info     = probe.GetMediaInfo(file.NewName);
            var    videotag = info.Streams.Where(x => x.CodecType == "video").FirstOrDefault();
            var    audiotag = info.Streams.Where(x => x.CodecType == "audio").FirstOrDefault();
            Stream str      = new MemoryStream();

            ffmpeg.GetVideoThumbnail(file.NewName, str, 10);
            Bitmap bmp = new Bitmap(str);

            return(Dispatcher.Invoke(() => {
                VideoFileInfoSample sample = sample = new VideoFileInfoSample();
                sample.ScannedFile = file;
                sample.Preview.Source = bmp.ToBitmapImage();
                sample.TopText.Text = videotag.Width + "x" + videotag.Height;
                sample.Codec.Text = videotag.CodecName;
                var lang = videotag.Tags.Where(x => x.Key == "language" || x.Key == "Language" || x.Key == "lang" || x.Key == "Lang").FirstOrDefault();
                sample.Language.Text = !String.IsNullOrEmpty(lang.Value) ? lang.Value : "-";
                sample.Fps.Text = videotag.FrameRate.ToString("##.##") + "FPS";
                sample.Pixel.Text = videotag.PixelFormat;
                sample.Created.Text = File.GetCreationTime(file.NewName).ToString("HH:mm:ss, dd. MM. yyyy");
                sample.AudioCodec.Text = audiotag.CodecName;
                return sample;
            }));
        }
예제 #3
0
        public AboutVideoForm(string fileName)
        {
            InitializeComponent();
            var       ffProbe   = new FFProbe();
            MediaInfo videoInfo = ffProbe.GetMediaInfo(fileName);

            MediaInfo.StreamInfo videoStream = videoInfo.Streams.FirstOrDefault(item => item.CodecType == "video");
            if (videoStream == null)
            {
                Close();
                MessageBox.Show("Video stream doesn't found");
                return;
            }
            FileInfo      file = new FileInfo(fileName);
            StringBuilder sb   = new StringBuilder();

            sb.AppendLine(string.Format("Name: {0}", file.Name));
            sb.AppendLine(string.Format("Duration: {0}", videoInfo.Duration));
            sb.AppendLine(string.Format("Size: {0}x{1}", videoStream.Width, videoStream.Height));
            sb.AppendLine(string.Format("Frame rate: {0}", videoStream.FrameRate));
            sb.AppendLine(string.Format("Video codec: {0} ({1})", videoStream.CodecName, videoStream.CodecLongName));
            sb.AppendLine(string.Format("Pixel format: {0}", videoStream.PixelFormat));
            if (videoStream.Tags.Any())
            {
                sb.AppendLine(string.Format("Tags: {0}", string.Join(", ", videoStream.Tags.Select(item => item.Key + " = " + item.Value))));
            }

            textBox.Text            = sb.ToString();
            textBox.SelectionStart  = 0;
            textBox.SelectionLength = 0;
        }
예제 #4
0
        private void DebugMetadata(string videoUri)
        {
            var probe = new FFProbe();
            var info  = probe.GetMediaInfo(videoUri);

            Console.WriteLine($"Duration={info.Duration}");
            Console.WriteLine($"FormatName={info.FormatName}");
            Console.Write($"FormatTags=");
            foreach (var tag in info.FormatTags)
            {
                Console.Write($"{tag.Key}={tag.Value};");
            }
            Console.WriteLine($"");
            foreach (var stream in info.Streams)
            {
                Console.WriteLine($"Index={stream.Index}");
                Console.WriteLine($"CodecName={stream.CodecName}");
                Console.WriteLine($"CodecType={stream.CodecType}");
                Console.WriteLine($"FrameRate={stream.FrameRate}");
                Console.WriteLine($"Height={stream.Height}");
                Console.WriteLine($"Width={stream.Width}");
                Console.WriteLine($"PixelFormat={stream.PixelFormat}");

                Console.Write($"Tags=");
                foreach (var tag in stream.Tags)
                {
                    Console.Write($"{tag.Key}={tag.Value};");
                }
                Console.WriteLine($"");
            }
            Console.ReadKey();
        }
예제 #5
0
        static void Main(string[] args)
        {
            var filePath = args.Length > 0 ? args[0] : "gizmo.mp4";

            var ffProbe   = new FFProbe();
            var videoInfo = ffProbe.GetMediaInfo(filePath);

            Console.WriteLine("Media information for: {0}", filePath);
            Console.WriteLine("File format: {0}", videoInfo.FormatName);
            Console.WriteLine("Duration: {0}", videoInfo.Duration);
            foreach (var tag in videoInfo.FormatTags)
            {
                Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
            }

            foreach (var stream in videoInfo.Streams)
            {
                Console.WriteLine("Stream {0} ({1})", stream.CodecName, stream.CodecType);
                if (stream.CodecType == "video")
                {
                    Console.WriteLine("\tFrame size: {0}x{1}", stream.Width, stream.Height);
                    Console.WriteLine("\tFrame rate: {0:0.##}", stream.FrameRate);
                }
                foreach (var tag in stream.Tags)
                {
                    Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
                }
            }

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
        // This gets a list of default required tags a video file has
        // For now, this means the system tags (ids 1-4), thumbnail (9) and color (8).
        public static List<TagEntry> GetDefaultTags(FileInfo file)
        {
            List<TagEntry> defaultTags = new List<TagEntry>();
            var ffprobe = new FFProbe();
            var videoInfo = ffprobe.GetMediaInfo(file.FullName);
            defaultTags.Add(new TagEntry( // display name
                1, file.Name
                ));
            defaultTags.Add(new TagEntry( // file type/extension
                2, file.Extension.Replace(".","")));
            defaultTags.Add(new TagEntry( // file length
                3, videoInfo.Duration.TotalMilliseconds.ToString()));
            // note: file framerate applies to first video stream detected for now
            defaultTags.Add(new TagEntry( // file framerate
                4, videoInfo.Streams[0].FrameRate.ToString()
             ));

            var prefColor = Preferences.Lookup(4);
            var strColor = (prefColor != null) ? prefColor.Data : "000000";
            defaultTags.Add(new TagEntry( // default tag color
                8, strColor));
            // generate and save thumbnail
            defaultTags.Add(Tags.GenerateThumbnail(file));
            return defaultTags;
        }
예제 #7
0
        private void ReadFile()
        {
            try
            {
                FFProbe   probe = new FFProbe();
                MediaInfo info  = probe.GetMediaInfo(Path);
                _size = new FileInfo(Path).Length;

                Duration  = info.Duration;
                FileTypes = info.FormatName.Split(',');

                foreach (var stream in info.Streams)
                {
                    if (stream.CodecType == "video")
                    {
                        videoCodec.codec     = stream.CodecName;
                        videoCodec.codecType = CodecInfo.CodecType.Video;
                        Width     = stream.Width;
                        Height    = stream.Height;
                        FrameRate = stream.FrameRate;
                    }
                    else if (stream.CodecType == "audio")
                    {
                        audioCodec.codec     = stream.CodecName;
                        audioCodec.codecType = CodecInfo.CodecType.Audio;
                    }
                }
            }
            catch (FileNotFoundException)
            {
                throw new FileNotFoundException("Unable to locate the specific file. path is supplied as " + Path);
            }
        }
예제 #8
0
        /// <summary>
        /// دریافت اطلاعات فایل ویدیویی
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task <MediaInfo> ResolveMetadataAsync(string filePath)
        {
            var ffProbe   = new FFProbe();
            var videoInfo = ffProbe.GetMediaInfo(filePath);

            return(videoInfo);
        }
        // This gets a list of default required tags a video file has
        // For now, this means the system tags (ids 1-4), thumbnail (9) and color (8).
        public static List <TagEntry> GetDefaultTags(FileInfo file)
        {
            List <TagEntry> defaultTags = new List <TagEntry>();
            var             ffprobe     = new FFProbe();
            var             videoInfo   = ffprobe.GetMediaInfo(file.FullName);

            defaultTags.Add(new TagEntry( // display name
                                1, file.Name
                                ));
            defaultTags.Add(new TagEntry( // file type/extension
                                2, file.Extension.Replace(".", "")));
            defaultTags.Add(new TagEntry( // file length
                                3, videoInfo.Duration.TotalMilliseconds.ToString()));
            // note: file framerate applies to first video stream detected for now
            defaultTags.Add(new TagEntry( // file framerate
                                4, videoInfo.Streams[0].FrameRate.ToString()
                                ));

            var prefColor = Preferences.Lookup(4);
            var strColor  = (prefColor != null) ? prefColor.Data : "000000";

            defaultTags.Add(new TagEntry( // default tag color
                                8, strColor));
            // generate and save thumbnail
            defaultTags.Add(Tags.GenerateThumbnail(file));
            return(defaultTags);
        }
예제 #10
0
 public MediaInfoParser(string fullPathToFile)
 {
     try
     {
         var ffProbe = new FFProbe();
         mediaInfo = ffProbe.GetMediaInfo(fullPathToFile);
     }
     catch { }
 }
예제 #11
0
        public static MediaInfo GetMediaInfo(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return(null);
            }

            var probe = new FFProbe();

            return(probe.GetMediaInfo(filePath));
        }
예제 #12
0
        private GoProVideoInfo ExtractMetadata(string videoUri)
        {
            var data = new GoProVideoInfo();

            var probe = new FFProbe();
            var info  = probe.GetMediaInfo(videoUri);

            data.VideoUri = videoUri;
            data.Duration = info.Duration;

            foreach (var tag in info.FormatTags)
            {
                switch (tag.Key.ToLowerInvariant())
                {
                case "creation_time":     // creation_time=2016-01-11T12:37:02.000000Z
                    data.Recorded = ExtractDateTime(tag.Value);
                    break;

                case "location":     // location=-45.0267+168.6460/;
                    data.Latitude  = ExtractLatitude(tag.Value);
                    data.Longitude = ExtractLongitude(tag.Value);
                    break;

                case "firmware":     //firmware=HD7.01.01.61.00
                    data.Firmware = tag.Value;
                    break;
                }
            }

            var stream = info.Streams[0];

            data.CodecName = stream.CodecName;
            data.FrameRate = stream.FrameRate;
            data.Height    = stream.Height;
            data.Width     = stream.Width;

            foreach (var tag in stream.Tags)
            {
                switch (tag.Key.ToLowerInvariant())
                {
                case "rotate":      // rotate=180
                    data.IsRotated = tag.Value == "180";
                    break;
                }
            }

            return(data);
        }
        private async void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            MainWindow.HideContent();
            Helper.DisableScreenSaver();
            MainWindow.videoPlayback = true;
            media                      = new FFProbe();
            media.ToolPath             = Environment.GetFolderPath(SpecialFolder.ApplicationData);
            VolumeSlider.Value         = Player.Volume = Properties.Settings.Default.Volume;
            VolumeSlider.ValueChanged += VolumeSlider_ValueChanged;
            Focus();
            Player.MediaOpened += (s, ev) => MediaOpenedEvent();
            while (true)
            {
                Animate();
                await Task.Run(() => {
                    Thread.Sleep(1080);
                });

                file = GetSource();
                if (file != null && downloader.Status.Progress > 0.01)
                {
                    try {
                        var duration   = media.GetMediaInfo(file).Duration.TotalSeconds;
                        var downloaded = duration * downloader.Status.Progress;
                        if (File.Exists(file) && duration != 0 && downloaded > 10)
                        {
                            Player.Source = new Uri(file);
                            Player.Stop();
                            break;
                        }
                    } catch (Exception) { }
                }
            }
            TorrentDatabase.Save(downloader.TorrentSource);

            Animate();
            await Task.Delay(1080);

            Player.MediaFailed += (s, ev) => MediaFailedEvent();
            Player.MediaEnded  += (s, ev) => MediaFinishedEvent();
            var sb    = (Storyboard)FindResource("OpacityDown");
            var clone = sb.Clone();

            clone.Completed += (s, ev) => {
                Middle.Visibility = Visibility.Collapsed;
            };
            sb.Begin(Middle);
        }
예제 #14
0
        private async Task LoadSidebar()
        {
            List <SubtitleItem> subs = new List <SubtitleItem>();

            CurrentStatus.Text = "Loading info";
            await Task.Run(() => {
                FFProbe probe  = new FFProbe();
                probe.ToolPath = Environment.GetFolderPath(SpecialFolder.ApplicationData);
                var info       = probe.GetMediaInfo(scannedFile.NewName);
                var video      = info.Streams.Where(x => x.CodecType == "video").FirstOrDefault();
                var audio      = info.Streams.Where(x => x.CodecType == "audio").FirstOrDefault();
                Dispatcher.Invoke(() => {
                    EpisodeName.Text  = episode.episodeName;
                    SeriesNumber.Text = Helper.GenerateName(episode);
                    Framerate.Text    = "Framerate: " + video.FrameRate.ToString("##.##");
                    Resolution.Text   = "Resolution: " + video.Width + "x" + video.Height;
                    VideoCodec.Text   = "Video codec: " + video.CodecLongName;
                    PixelFormat.Text  = "Pixel format: " + video.PixelFormat;
                    AudioCodec.Text   = "Audio codec: " + audio.CodecLongName;
                });
                var multiple = info.Streams.Where(x => x.CodecType == "subtitle").Where(x => x.CodecName == "srt");
                var single   = multiple.FirstOrDefault();
                if (single != null)
                {
                    FFMpegConverter converter = new FFMpegConverter();
                    converter.FFMpegToolPath  = probe.ToolPath;
                    Stream str = new MemoryStream();
                    converter.ConvertMedia(scannedFile.NewName, str, "srt");
                    FoundSubtitle fs = new FoundSubtitle(str);
                    fs.Version       = "Packed with video";
                    allSubtitles.Add(fs);
                }
                else
                {
                    var subtitles = episode.files.Where(x => x.Type == ScannedFile.FileType.Subtitles);
                    foreach (var sub in subtitles)
                    {
                        FoundSubtitle fs = new FoundSubtitle(sub.NewName);
                        fs.Version       = sub.OriginalName;
                        allSubtitles.Add(fs);
                    }
                }
                LoadSideBarSubs();
            });

            CurrentStatus.Text = "";
            RenderSubs();
        }
예제 #15
0
        public void PreTranscodeOps(string filePath, string newPath, string speed)
        {
            var ffProbe   = new FFProbe();
            var videoInfo = ffProbe.GetMediaInfo(filePath);
            var fileName  = Path.GetFileNameWithoutExtension(filePath);
            var fileExt   = Path.GetExtension(filePath);
            int width     = videoInfo.Streams[0].Width > -1 ? videoInfo.Streams[0].Width : videoInfo.Streams[1].Width;
            int height    = videoInfo.Streams[0].Height > -1 ? videoInfo.Streams[0].Height : videoInfo.Streams[1].Height;

            Logging.WriteLog($"Current video: {filePath}\n- New path is: {newPath} ");
            if (videoInfo.Duration > TimeSpan.FromMinutes(30)) // if vid is longer than 30mins return isLong = true. (right now this is not doing anything).
            {
                Transcode(fileName, filePath, newPath, fileExt, width, height, speed, true);
            }
            else
            {
                Transcode(fileName, filePath, newPath, fileExt, width, height, speed, false);
            }
        }
예제 #16
0
        /// <summary>
        /// تعیین نوع فایل های مجاز
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task GetFormatAsync(string file)
        {
            string[] format =
            {
                ".wmv", ".mov", ".qt",  ".ts",  ".3gp", ".3gpp", ".3g2",  ".3gp2", ".mpg", ".mpeg", ".mp1",
                ".mp2", ".m1v", ".m1a", ".m2a", ".mpa", ".mpv",  ".mpv2", ".mpe",  ".mp4", ".m4a",  ".m4p",".m4b",  ".m4r",
                ".m4v",
                ".avi", ".flv", ".f4v", ".f4p", ".f4a", ".f4b",  ".vob",  ".lsf",  ".lsx", ".asf",  ".asr",".asx",  ".webm",
                ".mkv"
            };
            var pathExtension = Path.GetExtension(file);

            if (format.All(fileEx => fileEx != pathExtension))
            {
                throw new ValidationException("نوع فایل مجاز نیست");
            }
            //return format.Any(fileEx => fileEx == pathExtension) ? null : "نوع فایل مجاز نیست";
            file = HttpContext.Current.Server.MapPath(file);
            // تعیین کیفیت مجاز برای فایل های ویدیویی ارسالی
            var ffProbe = new FFProbe();
            var x       = ffProbe.GetMediaInfo(file);
            var width   = 0;

            foreach (var stream in x.Streams)
            {
                if (stream.CodecType == "video")
                {
                    width = stream.Width;
                }
            }
            if (width < 360 && width > 1280)
            {
                throw new ValidationException("کیفیت نمایش خارج از محدوده مجاز است");
            }

            //تعیین حجم مجاز فایل های ویدیویی
            var size = new FileInfo(file).Length;

            if (size <= 5)
            {
                throw new ValidationException("اندازه فایل قابل قبول نیست");
            }
        }
        public bool Check(string path)
        {
            var probe = new FFProbe {
                ToolPath = ffmpegPath, ExecutionTimeout = TimeSpan.FromSeconds(1.5)
            };

            MediaInfo mediaInfo = null;

            try
            {
                mediaInfo = probe.GetMediaInfo(path);
            }
            catch (Exception e)
            {
                return(false);
            }

            return(mediaInfo != null && mediaInfo.Streams.Any(s => s.PixelFormat != null));
        }
예제 #18
0
    /// <inheritdoc />
    public DateTime ReadDate(string filePath)
    {
        try
        {
            var ffProbe   = new FFProbe();
            var videoInfo = ffProbe.GetMediaInfo(filePath);

            var creationTimePair = videoInfo.FormatTags.FirstOrDefault(x => x.Key.Equals("creation_time"));
            if (DateTime.TryParse(creationTimePair.Value, out var dateVideoTaken))
            {
                return(dateVideoTaken);
            }
        }
        catch
        {
            //---   ignore
        }

        return(ReaderHelper.GetDefault(filePath));
    }
예제 #19
0
        public bool OpenFile(string filePath)
        {
            try
            {
                var ffProbe = new FFProbe();
                this.videoInfo = ffProbe.GetMediaInfo(filePath);

                if (this.videoInfo != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #20
0
        private void ChangeContents(string[] sExt, string sContentTempPath, int iViewTime)
        {
            if (sExt.Length >= 2)
            {
                if (sExt[sExt.Length - 1] == "avi" || sExt[sExt.Length - 1] == "mp4" || sExt[sExt.Length - 1] == "wmv")
                {
                    try
                    {
                        picBox.Visible      = false;
                        mediaPlayer.Visible = true;
                        var ffProbe = new FFProbe();
                        mediaPlayer.URL = sContentTempPath;
                        var videoInfo = ffProbe.GetMediaInfo(sContentTempPath);
                        var duration  = Math.Floor(videoInfo.Duration.TotalSeconds);    //영상 조회 시간
                        mediaPlayer.Ctlcontrols.play();

                        Thread.Sleep((int)duration * 1000);
                    }
                    catch (Exception ex)
                    {
                        //파일 다운로드하는데 제대로 다운이 안되면 이 오류가 남
                        //해당 파일을 삭제하고 메인에서 파일 다운로드할때 다시 받는다
                        if (ex.Message.Contains("moov atom"))
                        {
                            FileInfo file_info = new System.IO.FileInfo(sContentTempPath);
                            file_info.Delete();
                            DID_Form._sFileList = "";
                        }
                    }
                }
                else
                {
                    picBox.Visible      = true;
                    mediaPlayer.Visible = false;
                    //mediaPlayer.Ctlcontrols.stop();
                    picBox.ImageLocation = sContentTempPath;
                    Thread.Sleep(iViewTime * 1000);
                }
            }
        }
예제 #21
0
        /// <summary> Получить продолжительность видео в секундах. Сначала через ShellFile, при неудаче - через FFProbe. </summary>
        public static int GetDuration(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return(1);
            }
            FileInfo fi = new FileInfo(path);

            if (!fi.Exists)
            {
                return(1);
            }

            object dur = null;

            try {
                var file = ShellFile.FromFilePath(path);
                dur = file?.Properties?.System?.Media?.Duration?.ValueAsObject;
            } catch (Exception ex) {
                Console.WriteLine("GetDuration() ex: " + ex.Message);
            }

            if (dur == null)
            {
                // на случай, если не смогли получить через шел
                try {
                    return((int)ffProbe.GetMediaInfo(path).Duration.TotalSeconds);
                } catch (Exception ex2) {
                    Console.WriteLine("GetDuration() ex: " + ex2.Message);
                    return(0);
                }
            }

            var t = (ulong)dur;

            return((int)TimeSpan.FromTicks((long)t).TotalSeconds);
        }
예제 #22
0
        public ChannelEntry(string provider, string inputLine, string nextLine, string epg, string extraEpg, bool skipCheck = false)
        {
            Provider    = provider;
            TvgId       = string.Empty;
            TvgName     = string.Empty;
            TvgLogo     = string.Empty;
            ChannelId   = string.Empty;
            ChannelName = string.Empty;
            GroupTitle  = string.Empty;
            StreamId    = string.Empty;
            StreamUrl   = nextLine;
            ErrorType   = "Skipped - No EPG";
            Width       = 0;
            Height      = 0;
            FrameRate   = 0;

            TvgId       = ExtractData(inputLine, "tvg-id").Replace(",", "-");
            TvgName     = ExtractData(inputLine, "tvg-name").Replace(",", "-");
            TvgLogo     = ExtractData(inputLine, "tvg-logo").Replace(",", "-");
            ChannelId   = ExtractData(inputLine, "channel-id").Replace(",", "-");
            ChannelName = inputLine.Substring(inputLine.LastIndexOf(",") + 1).Replace(",", "-");
            GroupTitle  = ExtractData(inputLine, "group-title").Replace(",", "-");

            if (string.IsNullOrEmpty(GroupTitle))
            {
                GroupTitle = "General";
            }


            //if (!StreamUrl.IsMappedChannel())
            //{
            //    ErrorType = "Channel Not Mapped";
            //}
            //else if (IsChannelToCheck(epg, extraEpg))
            //{
            if (skipCheck == true)
            {
                ErrorType = "Skipped by Request";
            }
            else
            {
                try
                {
                    ErrorType = "Bad Stream";
                    var ffProbe = new FFProbe();

                    ffProbe.ExecutionTimeout = new TimeSpan(0, 0, 10);
                    var videoInfo = ffProbe.GetMediaInfo(string.Concat("\"", nextLine, "\""));
                    //var videoInfo = ffProbe.GetMediaInfo(nextLine);
                    //var videoInfo = ffProbe.GetMediaInfo(nextLine.Replace("@", "%40"));

                    //Console.WriteLine("Media information for: {0}", nextLine);
                    //Console.WriteLine("File format: {0}", videoInfo.FormatName);
                    //Console.WriteLine("Duration: {0}", videoInfo.Duration);
                    //foreach (var tag in videoInfo.FormatTags)
                    //{
                    //    Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
                    //}

                    //foreach (var stream in videoInfo.Streams)
                    //{
                    //    Console.WriteLine("Stream {0} ({1})", stream.CodecName, stream.CodecType);
                    //    if (stream.CodecType == "video")
                    //    {
                    //        Console.WriteLine("\tFrame size: {0}x{1}", stream.Width, stream.Height);
                    //        Console.WriteLine("\tFrame rate: {0:0.##}", stream.FrameRate);
                    //    }
                    //    foreach (var tag in stream.Tags)
                    //    {
                    //        Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
                    //    }
                    //}

                    var stream = videoInfo.Streams[0];
                    Width     = stream.Width;
                    Height    = stream.Height;
                    FrameRate = stream.FrameRate;
                    //Console.WriteLine("\tFrame size: {0}x{1}", stream.Width, stream.Height);
                    //Console.WriteLine("\tFrame rate: {0:0.##}", stream.FrameRate);
                    if (Width > 0)
                    {
                        ErrorType = string.Empty;
                    }
                    //else
                    //{
                    //    videoInfo = ffProbe.GetMediaInfo(nextLine);
                    //    foreach(var subsStream in videoInfo.Streams)
                    //    {
                    //        Width = stream.Width;
                    //        Height = stream.Height;
                    //        FrameRate = stream.FrameRate;

                    //        if (Width > 0)
                    //            break;
                    //    }
                    //    //stream = videoInfo.Streams[0];


                    //    if (Width > 0)
                    //    {
                    //        ErrorType = string.Empty;
                    //    }
                    //}
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("403 Forbidden"))
                    {
                        Width     = 1;
                        Height    = 1;
                        FrameRate = 1;
                        System.Threading.Thread.Sleep(5000);
                    }
                    try
                    {
                        ErrorType = "Bad Stream";
                        var ffProbe = new FFProbe();

                        ffProbe.ExecutionTimeout = new TimeSpan(0, 0, 10);
                        var videoInfo = ffProbe.GetMediaInfo(nextLine);

                        var stream = videoInfo.Streams[0];
                        Width     = stream.Width;
                        Height    = stream.Height;
                        FrameRate = stream.FrameRate;
                        if (Width > 0)
                        {
                            ErrorType = string.Empty;
                        }
                    }
                    catch (Exception ex1)
                    {
                        if (ex1.Message.Contains("403 Forbidden"))
                        {
                            Width     = 1;
                            Height    = 1;
                            FrameRate = 1;
                        }
                    }
                }
            }


            //catch (FFProbeException fFProbeException)
            //{
            //    ErrorType = string.Concat("Bad Stream - ", fFProbeException.ErrorCode, " - ", fFProbeException.Message.Replace("\r", string.Empty).Replace("\n", string.Empty));
            //}
            //Console.WriteLine(TvgId);
            //Console.WriteLine(TvgName);
            //Console.WriteLine(TvgLogo);
            //Console.WriteLine(ChannelId);
            //Console.WriteLine(ChannelName);
            //Console.WriteLine(GroupTitle);
            //Console.WriteLine(StreamUrl);
            //Console.WriteLine(StreamId);
            //Console.WriteLine(Width);
            //Console.WriteLine(Height);
            //Console.WriteLine(string.Format("{0:N2}", FrameRate));
            //Console.ReadKey();
            //}
        }
예제 #23
0
		public static Dictionary<ColumnType, object> GetVideoDetails(string fileName)
		{
			Dictionary<ColumnType, object> info = null;
			try
			{
				var ffProbe = new FFProbe();
				var videoInfo = ffProbe.GetMediaInfo(fileName);
				Console.WriteLine("Media information for: {0}", fileName);
				Console.WriteLine("File format: {0}", videoInfo.FormatName);
				Console.WriteLine("Duration: {0}", videoInfo.Duration);
				info = new Dictionary<ColumnType, object>();
				info.Add(ColumnType.Duration, Math.Round(videoInfo.Duration.TotalSeconds));

				foreach (var tag in videoInfo.FormatTags)
				{
					Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
				}
				foreach (var stream in videoInfo.Streams)
				{
					Console.WriteLine("Stream {0} ({1})", stream.CodecName, stream.CodecType);
					if (stream.CodecType == "video")
					{
						Console.WriteLine("\tFrame size: {0}x{1}", stream.Width, stream.Height);
						Console.WriteLine("\tFrame rate: {0:0.##}", stream.FrameRate);
						info.Add(ColumnType.Width, stream.Width);
						info.Add(ColumnType.Height, stream.Height);
					}
					foreach (var tag in stream.Tags)
					{
						Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
					}
				}
			}
			catch { }
			if (info == null)
			{
				try
				{
					WindowsMediaPlayer wmp = new WindowsMediaPlayer();
					IWMPMedia mediaInfo = wmp.newMedia(fileName);
					info = new Dictionary<ColumnType, object>();
					info.Add(ColumnType.Duration, Math.Round(mediaInfo.duration));
					info.Add(ColumnType.Width, mediaInfo.imageSourceWidth);
					info.Add(ColumnType.Height, mediaInfo.imageSourceHeight);
				}
				catch { throw; }
			}
			return info;
		}
예제 #24
0
        private static void verifica_carpeta(DirectoryInfo dir_c_f, DirectoryInfo ruta_destino, int id_rv, int t_ss, Guid id_ctrl)
        {
            string ext_all, ext_mp4, ext_asf, ext_wmv, ext_pdf, usr_ini, clv_ini;

            ext_mp4 = ".mp4";
            ext_asf = ".asf";
            ext_wmv = ".wmv";
            ext_pdf = ".pdf";

            int est_matID = 0;

            Guid id_em = Guid.Empty;

            var lis_wmv = dir_c_f.GetFiles("*wmv");

            if (lis_wmv.Length > 0)
            {
                using (var edm_master = new bd_tsEntities())
                {
                    var i_master = (from c in edm_master.inf_master_jvl
                                    where c.sesion == dir_c_f.Name
                                    select c).ToList();

                    if (t_ss == 1)
                    {
                        if (i_master.Count == 0)
                        {
                            inf_master_jvl infMaster = new inf_master_jvl()
                            {
                                id_control_exp = id_ctrl,
                                sesion         = dir_c_f.Name,
                                titulo         = dir_c_f.Name,
                                err_carga      = "Ninguno",
                                id_estatus_exp = 1,
                                id_estatus_qa  = 1,
                                id_ruta_videos = id_rv,
                                fecha_registro = DateTime.Now
                            };
                            edm_master.inf_master_jvl.Add(infMaster);
                            edm_master.SaveChanges();

                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*wmv"))
                            {
                                DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);

                                if (di_destino.Exists == true)
                                {
                                }
                                else
                                {
                                    di_destino.Create();
                                }

                                File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name, true);
                                id_em = Guid.NewGuid();

                                FFProbe  ffProbe   = new FFProbe();
                                var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());

                                string f_d = date1.ToLongTimeString();

                                var g_media = new inf_exp_mat
                                {
                                    id_exp_mat     = id_em,
                                    ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ext_mp4),
                                    ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ".pdf"),
                                    duracion       = f_d,
                                    nom_archivo    = f_c_f.Name.Replace(ext_wmv, ""),
                                    id_est_mat     = 1,
                                    id_control_exp = id_ctrl,
                                    fecha_registro = DateTime.Now,
                                };
                                edm_master.inf_exp_mat.Add(g_media);
                                edm_master.SaveChanges();

                                try
                                {
                                    FFMpegConverter ffMpegConverter = new FFMpegConverter();
                                    ffMpegConverter.ConvertMedia(di_destino + "\\" + f_c_f.Name, di_destino + "\\" + f_c_f.Name.Replace(ext_wmv, ext_mp4), Format.mp4);
                                    File.Delete(di_destino + "\\" + f_c_f.Name);
                                    est_matID = 2;

                                    var a_media = (from c in edm_master.inf_exp_mat
                                                   where c.id_exp_mat == id_em
                                                   select c).FirstOrDefault();

                                    a_media.id_est_mat = est_matID;
                                    edm_master.SaveChanges();
                                }
                                catch
                                {
                                    est_matID = 3;

                                    var a_media = (from c in edm_master.inf_exp_mat
                                                   where c.id_exp_mat == id_em
                                                   select c).FirstOrDefault();

                                    a_media.id_est_mat = est_matID;
                                    edm_master.SaveChanges();
                                }
                            }
                        }
                        else
                        {
                            id_ctrl = i_master[0].id_control_exp;
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*wmv"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name.Replace(ext_wmv, ext_mp4);
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);

                                    if (di_destino.Exists == true)
                                    {
                                    }
                                    else
                                    {
                                        di_destino.Create();
                                    }

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name, true);
                                    id_em = Guid.NewGuid();

                                    FFProbe  ffProbe   = new FFProbe();
                                    var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                    DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                    string   f_d       = date1.ToLongTimeString();

                                    var g_media = new inf_exp_mat
                                    {
                                        id_exp_mat     = id_em,
                                        ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ext_mp4),
                                        ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ".pdf"),
                                        duracion       = f_d,
                                        nom_archivo    = f_c_f.Name.Replace(ext_wmv, ""),
                                        id_est_mat     = 1,
                                        id_control_exp = id_ctrl,
                                        fecha_registro = DateTime.Now,
                                    };
                                    edm_master.inf_exp_mat.Add(g_media);
                                    edm_master.SaveChanges();

                                    try
                                    {
                                        FFMpegConverter ffMpegConverter = new FFMpegConverter();
                                        ffMpegConverter.ConvertMedia(di_destino + "\\" + f_c_f.Name, di_destino + "\\" + f_c_f.Name.Replace(ext_wmv, ext_mp4), Format.mp4);
                                        File.Delete(di_destino + "\\" + f_c_f.Name);
                                        est_matID = 2;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                    catch
                                    {
                                        est_matID = 3;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        string e_f     = ruta_destino.Name.ToString();
                        var    i_em_ff = (from c in edm_master.inf_master_jvl
                                          where c.sesion == e_f
                                          select c).ToList();

                        if (i_em_ff.Count == 0)
                        {
                        }
                        else
                        {
                            id_ctrl = i_em_ff[0].id_control_exp;
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*wmv"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name.Replace(ext_wmv, ext_mp4);
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);

                                    if (di_destino.Exists == true)
                                    {
                                    }
                                    else
                                    {
                                        di_destino.Create();
                                    }

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name, true);
                                    id_em = Guid.NewGuid();

                                    FFProbe  ffProbe   = new FFProbe();
                                    var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                    DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                    string   f_d       = date1.ToLongTimeString();

                                    var g_media = new inf_exp_mat
                                    {
                                        id_exp_mat     = id_em,
                                        ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ext_mp4),
                                        ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ".pdf"),
                                        duracion       = f_d,
                                        nom_archivo    = f_c_f.Name.Replace(ext_wmv, ""),
                                        id_est_mat     = 1,
                                        id_control_exp = id_ctrl,
                                        fecha_registro = DateTime.Now,
                                    };
                                    edm_master.inf_exp_mat.Add(g_media);
                                    edm_master.SaveChanges();

                                    try
                                    {
                                        FFMpegConverter ffMpegConverter = new FFMpegConverter();
                                        ffMpegConverter.ConvertMedia(di_destino + "\\" + f_c_f.Name, di_destino + "\\" + f_c_f.Name.Replace(ext_wmv, ext_mp4), Format.mp4);
                                        File.Delete(di_destino + "\\" + f_c_f.Name);
                                        est_matID = 2;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                    catch
                                    {
                                        est_matID = 3;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            var lis_asf = dir_c_f.GetFiles("*asf");

            if (lis_asf.Length > 0)
            {
                using (var edm_master = new bd_tsEntities())
                {
                    var i_master = (from c in edm_master.inf_master_jvl
                                    where c.sesion == dir_c_f.Name
                                    select c).ToList();

                    if (t_ss == 1)
                    {
                        if (i_master.Count == 0)
                        {
                            inf_master_jvl infMaster = new inf_master_jvl()
                            {
                                id_control_exp = id_ctrl,
                                sesion         = dir_c_f.Name,
                                titulo         = dir_c_f.Name,
                                err_carga      = "Ninguno",
                                id_estatus_exp = 1,
                                id_estatus_qa  = 1,
                                id_ruta_videos = id_rv,
                                fecha_registro = DateTime.Now
                            };
                            edm_master.inf_master_jvl.Add(infMaster);
                            edm_master.SaveChanges();

                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*asf"))
                            {
                                DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);

                                if (di_destino.Exists == true)
                                {
                                }
                                else
                                {
                                    di_destino.Create();
                                }

                                File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name, true);
                                id_em = Guid.NewGuid();

                                FFProbe  ffProbe   = new FFProbe();
                                var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                string   f_d       = date1.ToLongTimeString();

                                var g_media = new inf_exp_mat
                                {
                                    id_exp_mat     = id_em,
                                    ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_asf, ext_mp4),
                                    ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_asf, ".pdf"),
                                    duracion       = f_d,
                                    nom_archivo    = f_c_f.Name.Replace(ext_asf, ""),
                                    id_est_mat     = 1,
                                    id_control_exp = id_ctrl,
                                    fecha_registro = DateTime.Now,
                                };
                                edm_master.inf_exp_mat.Add(g_media);
                                edm_master.SaveChanges();

                                try
                                {
                                    FFMpegConverter ffMpegConverter = new FFMpegConverter();
                                    ffMpegConverter.ConvertMedia(di_destino + "\\" + f_c_f.Name, di_destino + "\\" + f_c_f.Name.Replace(ext_asf, ext_mp4), Format.mp4);
                                    File.Delete(di_destino + "\\" + f_c_f.Name);
                                    est_matID = 2;

                                    var a_media = (from c in edm_master.inf_exp_mat
                                                   where c.id_exp_mat == id_em
                                                   select c).FirstOrDefault();

                                    a_media.id_est_mat = est_matID;
                                    edm_master.SaveChanges();
                                }
                                catch
                                {
                                    est_matID = 3;

                                    var a_media = (from c in edm_master.inf_exp_mat
                                                   where c.id_exp_mat == id_em
                                                   select c).FirstOrDefault();

                                    a_media.id_est_mat = est_matID;
                                    edm_master.SaveChanges();
                                }
                            }
                        }
                        else
                        {
                            id_ctrl = i_master[0].id_control_exp;
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*asf"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name.Replace(ext_asf, ext_mp4);
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);

                                    if (di_destino.Exists == true)
                                    {
                                    }
                                    else
                                    {
                                        di_destino.Create();
                                    }

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name, true);
                                    id_em = Guid.NewGuid();

                                    FFProbe  ffProbe   = new FFProbe();
                                    var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                    DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                    string   f_d       = date1.ToLongTimeString();

                                    var g_media = new inf_exp_mat
                                    {
                                        id_exp_mat     = id_em,
                                        ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_asf, ext_mp4),
                                        ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_asf, ".pdf"),
                                        duracion       = f_d,
                                        nom_archivo    = f_c_f.Name.Replace(ext_asf, ""),
                                        id_est_mat     = 1,
                                        id_control_exp = id_ctrl,
                                        fecha_registro = DateTime.Now,
                                    };
                                    edm_master.inf_exp_mat.Add(g_media);
                                    edm_master.SaveChanges();

                                    try
                                    {
                                        FFMpegConverter ffMpegConverter = new FFMpegConverter();
                                        ffMpegConverter.ConvertMedia(di_destino + "\\" + f_c_f.Name, di_destino + "\\" + f_c_f.Name.Replace(ext_asf, ext_mp4), Format.mp4);
                                        File.Delete(di_destino + "\\" + f_c_f.Name);
                                        est_matID = 2;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                    catch
                                    {
                                        est_matID = 3;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        string e_f     = ruta_destino.Name.ToString();
                        var    i_em_ff = (from c in edm_master.inf_master_jvl
                                          where c.sesion == e_f
                                          select c).ToList();

                        if (i_em_ff.Count == 0)
                        {
                        }
                        else
                        {
                            id_ctrl = i_em_ff[0].id_control_exp;
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*asf"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name.Replace(ext_asf, ext_mp4);
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);

                                    if (di_destino.Exists == true)
                                    {
                                    }
                                    else
                                    {
                                        di_destino.Create();
                                    }

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name, true);
                                    id_em = Guid.NewGuid();

                                    FFProbe  ffProbe   = new FFProbe();
                                    var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                    DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                    string   f_d       = date1.ToLongTimeString();

                                    var g_media = new inf_exp_mat
                                    {
                                        id_exp_mat     = id_em,
                                        ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_asf, ext_mp4),
                                        ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_asf, ".pdf"),
                                        duracion       = f_d,
                                        nom_archivo    = f_c_f.Name.Replace(ext_asf, ""),
                                        id_est_mat     = 1,
                                        id_control_exp = id_ctrl,
                                        fecha_registro = DateTime.Now,
                                    };
                                    edm_master.inf_exp_mat.Add(g_media);
                                    edm_master.SaveChanges();

                                    try
                                    {
                                        FFMpegConverter ffMpegConverter = new FFMpegConverter();
                                        ffMpegConverter.ConvertMedia(di_destino + "\\" + f_c_f.Name, di_destino + "\\" + f_c_f.Name.Replace(ext_asf, ext_mp4), Format.mp4);
                                        File.Delete(di_destino + "\\" + f_c_f.Name);
                                        est_matID = 2;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                    catch
                                    {
                                        est_matID = 3;

                                        var a_media = (from c in edm_master.inf_exp_mat
                                                       where c.id_exp_mat == id_em
                                                       select c).FirstOrDefault();

                                        a_media.id_est_mat = est_matID;
                                        edm_master.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            var lis_mp4 = dir_c_f.GetFiles("*mp4");

            if (lis_mp4.Length > 0)
            {
                using (var edm_master = new bd_tsEntities())
                {
                    var i_master = (from c in edm_master.inf_master_jvl
                                    where c.sesion == dir_c_f.Name
                                    select c).ToList();

                    if (t_ss == 1)
                    {
                        if (i_master.Count == 0)
                        {
                            inf_master_jvl infMaster = new inf_master_jvl()
                            {
                                id_control_exp = id_ctrl,
                                sesion         = dir_c_f.Name,
                                titulo         = dir_c_f.Name,
                                err_carga      = "Ninguno",
                                id_estatus_exp = 1,
                                id_estatus_qa  = 1,
                                id_ruta_videos = id_rv,
                                fecha_registro = DateTime.Now
                            };
                            edm_master.inf_master_jvl.Add(infMaster);
                            edm_master.SaveChanges();
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*mp4"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name;
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);
                                    di_destino.Create();

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name);

                                    var i_masterf = (from c in edm_master.inf_master_jvl
                                                     where c.id_control_exp == id_ctrl
                                                     select c).ToList();

                                    FFProbe  ffProbe   = new FFProbe();
                                    var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                    DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                    string   f_d       = date1.ToLongTimeString();

                                    var g_media = new inf_exp_mat
                                    {
                                        id_exp_mat     = Guid.NewGuid(),
                                        ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ext_mp4),
                                        ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ".pdf"),
                                        duracion       = f_d,
                                        nom_archivo    = f_c_f.Name.Replace(ext_mp4, ""),
                                        id_est_mat     = 2,
                                        id_control_exp = id_ctrl,
                                        fecha_registro = DateTime.Now,
                                    };

                                    edm_master.inf_exp_mat.Add(g_media);
                                    edm_master.SaveChanges();
                                }
                            }
                        }
                        else
                        {
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*mp4"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name;
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);
                                    di_destino.Create();

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name);

                                    var i_masterf = (from c in edm_master.inf_master_jvl
                                                     where c.id_control_exp == id_ctrl
                                                     select c).ToList();

                                    FFProbe  ffProbe   = new FFProbe();
                                    var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                    DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                    string   f_d       = date1.ToLongTimeString();

                                    var g_media = new inf_exp_mat
                                    {
                                        id_exp_mat     = Guid.NewGuid(),
                                        ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ext_mp4),
                                        ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ".pdf"),
                                        duracion       = f_d,
                                        nom_archivo    = f_c_f.Name.Replace(ext_mp4, ""),
                                        id_est_mat     = 2,
                                        id_control_exp = id_ctrl,
                                        fecha_registro = DateTime.Now,
                                    };

                                    edm_master.inf_exp_mat.Add(g_media);
                                    edm_master.SaveChanges();
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (FileInfo f_c_f in dir_c_f.GetFiles("*mp4"))
                        {
                            string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name;
                            var    i_em_f = (from c in edm_master.inf_exp_mat
                                             where c.ruta_archivo == f_f
                                             select c).ToList();

                            if (i_em_f.Count == 0)
                            {
                                DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);
                                di_destino.Create();

                                File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name);

                                var i_masterf = (from c in edm_master.inf_master_jvl
                                                 where c.id_control_exp == id_ctrl
                                                 select c).ToList();

                                FFProbe  ffProbe   = new FFProbe();
                                var      videoInfo = ffProbe.GetMediaInfo(di_destino + "\\" + f_c_f.Name.ToString());
                                DateTime date1     = DateTime.Parse(videoInfo.Duration.ToString());
                                string   f_d       = date1.ToLongTimeString();

                                var g_media = new inf_exp_mat
                                {
                                    id_exp_mat     = Guid.NewGuid(),
                                    ruta_archivo   = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ext_mp4),
                                    ruta_ext       = di_destino + "\\" + f_c_f.Name.ToString().Replace(ext_wmv, ".pdf"),
                                    duracion       = f_d,
                                    nom_archivo    = f_c_f.Name.Replace(ext_mp4, ""),
                                    id_est_mat     = 2,
                                    id_control_exp = id_ctrl,
                                    fecha_registro = DateTime.Now,
                                };

                                edm_master.inf_exp_mat.Add(g_media);
                                edm_master.SaveChanges();
                            }
                        }
                    }
                }
            }
            var lis_pdf = dir_c_f.GetFiles("*pdf");

            if (lis_pdf.Length > 0)
            {
                using (var edm_master = new bd_tsEntities())
                {
                    var i_master = (from c in edm_master.inf_master_jvl
                                    where c.sesion == dir_c_f.Name
                                    select c).ToList();

                    if (t_ss == 1)
                    {
                        if (i_master.Count == 0)
                        {
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*pdf"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name;
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);
                                    di_destino.Create();

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name);
                                }
                            }
                        }
                        else
                        {
                            foreach (FileInfo f_c_f in dir_c_f.GetFiles("*pdf"))
                            {
                                string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name;
                                var    i_em_f = (from c in edm_master.inf_exp_mat
                                                 where c.ruta_archivo == f_f
                                                 select c).ToList();

                                if (i_em_f.Count == 0)
                                {
                                    DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);
                                    di_destino.Create();

                                    File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name);
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (FileInfo f_c_f in dir_c_f.GetFiles("*pdf"))
                        {
                            string f_f    = ruta_destino + "\\" + dir_c_f.Name + "\\" + f_c_f.Name;
                            var    i_em_f = (from c in edm_master.inf_exp_mat
                                             where c.ruta_archivo == f_f
                                             select c).ToList();

                            if (i_em_f.Count == 0)
                            {
                                DirectoryInfo di_destino = new DirectoryInfo(ruta_destino + "\\" + dir_c_f.Name);
                                di_destino.Create();

                                File.Copy(f_c_f.FullName, di_destino + "\\" + f_c_f.Name);
                            }
                        }
                    }
                }
            }
        }
예제 #25
0
    void UpdateMediaInfo()
    {
        // Solution 1: cannot get width and height

        var mediaDet = (IMediaDet)new MediaDet();
        //DsError.ThrowExceptionForHR(mediaDet.put_Filename(mFileName));
        mediaDet.put_Filename(mFileName);
        // find the video stream in the file
        int index;
        var type = Guid.Empty;
        for (index = 0; index < 1000 && type != MediaType.Video; index++)
        {
            mediaDet.put_CurrentStream(index);
            mediaDet.get_StreamType(out type);
        }
        // retrieve some measurements from the video            
        mediaDet.get_FrameRate(out mFrameRate);
        var mediaType = new AMMediaType();
        var videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));
        
        // videoInfo.BmiHeader is Null here
        mWidth = videoInfo.BmiHeader.Width;
        mHeight = videoInfo.BmiHeader.Height;
        double mediaLength;
        mediaDet.get_StreamLength(out mediaLength);
        mDuration = (int)(mFrameRate * mediaLength / mFrameRate);
        DsUtils.FreeAMMediaType(mediaType);

        // Solution 2: cannot get width and height

        WindowsMediaPlayer wmp = new WindowsMediaPlayer();
        IWMPMedia mediainfo = wmp.newMedia(mFileName);
        mDuration = mediainfo.duration;
        mWidth = mediainfo.imageSourceWidth;
        mHeight = mediainfo.imageSourceHeight;
        mFrameRate = mediainfo.durationString;

        // Solution 3: don't have video-specific information

        Dictionary<int, KeyValuePair<string, string>> fileProps = GetFileProps(mFileName);
        foreach (KeyValuePair<int, KeyValuePair<string, string>> kv in fileProps)
        {
            Console.WriteLine(kv.ToString());
        }

        // Solution 4: LoadLock & x86 conflict problem

        Video video = new Video(mFileName, false);
        Size size = video.DefaultSize;
        mWidth = size.Width;
        mHeight = size.Height;
        mDuration = video.Duration;

        // Solution 5: Use Cygwin file.exe to fetch infomation

        Process p = new Process();
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        //p.StartInfo.WorkingDirectory = strWorkingDirectory;
        p.StartInfo.FileName = "file.exe";
        p.StartInfo.Arguments = "\"" + Regex.Replace(mFileName, @"(\\+)$", @"$1$1") + "\"";
        p.Start();
        string strOutput = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        Console.WriteLine("result: " + strOutput);

        // Solution 6: Use NReco.VideoInfo (wrapper of FFProbe)

        var filePath = "gizmo.mp4";
        var ffProbe = new FFProbe();
        var videoInfo = ffProbe.GetMediaInfo(filePath);

        Console.WriteLine("Media information for: {0}", filePath);
        Console.WriteLine("File format: {0}", videoInfo.FormatName);
        Console.WriteLine("Duration: {0}", videoInfo.Duration);
        foreach (var tag in videoInfo.FormatTags)
        {
            Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
        }

        foreach (var stream in videoInfo.Streams)
        {
            Console.WriteLine("Stream {0} ({1})", stream.CodecName, stream.CodecType);
            if (stream.CodecType == "video")
            {
                Console.WriteLine("\tFrame size: {0}x{1}", stream.Width, stream.Height);
                Console.WriteLine("\tFrame rate: {0:0.##}", stream.FrameRate);
            }
            foreach (var tag in stream.Tags)
            {
                Console.WriteLine("\t{0}: {1}", tag.Key, tag.Value);
            }
        }

        Console.WriteLine("\nPress any key to exit...");
        Console.ReadKey();
    }
예제 #26
0
        public static Dictionary <String, String> Upload(HttpRequestMessage Request, String SavePath, bool createThumb = false)
        {
            Dictionary <String, String> result = new Dictionary <String, String>();

            String fileName;
            Guid   id;

            Directory.CreateDirectory(SavePath);
            var streamProvider = new MultipartFormDataStreamProvider(SavePath);

            Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(p =>
            {
                foreach (MultipartFileData fileData in streamProvider.FileData)
                {
                    if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                    {
                        continue;
                    }

                    //if (new FileInfo(fileData.LocalFileName).Length > ServerSettings.MAX_SIZE_UPLOAD)
                    //{
                    //    File.Delete(fileData.LocalFileName);
                    //    continue;
                    //}

                    fileName = fileData.Headers.ContentDisposition.FileName;
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Trim('"');
                    }
                    if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                    {
                        fileName = Path.GetFileName(fileName);
                    }
                    id = Guid.NewGuid();

                    AttachmentStore.Map(id, fileName);

                    result.Add(fileName, id.ToString());

                    File.Move(fileData.LocalFileName, Path.Combine(SavePath, id.ToString()));
                    if (createThumb)
                    {
                        if (VideoExtensions.Contains(Path.GetExtension(fileName), StringComparer.OrdinalIgnoreCase))
                        {
                            var ffProbe               = new FFProbe();
                            var videoInfo             = ffProbe.GetMediaInfo(Path.Combine(SavePath, id.ToString()));
                            FFMpegConverter converter = new FFMpegConverter();
                            converter.GetVideoThumbnail(Path.Combine(SavePath, id.ToString()),
                                                        Path.Combine(SavePath, id.ToString() + "_thumb.jpg"),
                                                        (float)videoInfo.Duration.TotalSeconds / 2);
                        }

                        if (ImageExtensions.Contains(Path.GetExtension(fileName), StringComparer.OrdinalIgnoreCase))
                        {
                            Image image = Image.FromFile(Path.Combine(SavePath, id.ToString()));

                            int w = image.Width, h = image.Height;
                            if (image.Height > 300)
                            {
                                h = 300;
                                w = image.Width * 300 / image.Height;
                            }
                            else if (image.Width > 500)
                            {
                                w = 500;
                                h = image.Height * 500 / image.Width;
                            }

                            image.GetThumbnailImage(w, h, null, IntPtr.Zero).Save(Path.Combine(SavePath, id.ToString() + "_thumb.jpg"));
                            image.Dispose();
                        }
                    }
                }
            }).Wait();

            return(result);
        }
예제 #27
0
        public async Task <IActionResult> Index(IFormCollection request)
        {
            try
            {
                // Create required directories if not existing
                EnsureInit();

                // Deserialize cropping data if applicable
                CropData cropData = null;
                if (request.Str("cropData") != null)
                {
                    cropData = JsonConvert.DeserializeObject <CropData>(request.Str("cropData"));
                }


                // Original filename
                string uploadedName = request.Str("filename");

                // Generate a backend filename for the uploaded file - same extension as uploaded file.
                string filename = Guid.NewGuid().ToString() + Path.GetExtension(uploadedName);

                string fileType = request.Str("fileType");

                // Determine what type of file has been uploaded and act accordingly (may want to refactor these)

                // FOR IMAGES
                if (MediaType.MimesForCategory(MediaCategory.Image).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Images", filename);

                    // Save image and all associated versions of it.
                    var filedata = ImageUtils.SaveImage(request.Str("file")
                                                        .Split(',')[1], filepath, cropData);

                    // Create database record to track images
                    ImageMedia dbImageMedia = new ImageMedia {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = filedata["size"],
                        Title     = request.Str("title"),
                        Alt       = request.Str("alt"),
                        Width     = filedata["width"],
                        Height    = filedata["height"],
                        Versions  = filedata["versions"]
                    };

                    await _Db.AddAsync(dbImageMedia);
                }

                // FOR AUDIO
                else if (MediaType.MimesForCategory(MediaCategory.Audio).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Audio", filename);

                    // Save the audio file
                    byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes();
                    await System.IO.File.WriteAllBytesAsync(filepath, bytes);

                    // Read the audio file to determine its duration - it will either be mp3(mpeg) or wav

                    // Configure ffprobe path using appsettings values
                    FFProbe probe = new FFProbe();
                    probe.ToolPath = _Config["ffprobePath"];

                    // If running linux, look for ffprobe instaed of ffprobe.exe
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        probe.FFProbeExeName = "ffprobe";
                    }

                    // Get audio file metadata
                    MediaInfo mediaInfo = probe.GetMediaInfo(Path.Combine(_HostingEnv.ContentRootPath, filepath));

                    // Create the media database record
                    AudioMedia audioMedia = new AudioMedia
                    {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = new FileInfo(filepath).Length,
                        Duration  = Math.Round(mediaInfo.Duration.TotalSeconds)
                    };

                    await _Db.AddAsync(audioMedia);
                }

                // FOR GENERAL
                else if (MediaType.MimesForCategory(MediaCategory.General).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Documents", filename);

                    // Save the file
                    byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes();
                    System.IO.File.WriteAllBytes(filepath, bytes);

                    // Create the media database record
                    GeneralMedia generalMedia = new GeneralMedia
                    {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = new FileInfo(filepath).Length,
                    };

                    await _Db.AddAsync(generalMedia);
                }

                else
                {
                    return(new UnsupportedMediaTypeResult());
                }

                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error uploading file: {0}", ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please contact the devloper if the problem persists", ex.Message)));
            }
        }
예제 #28
0
        public async Task <LocalBeatmaps> GetLocalBeatmaps(LocalBeatmaps cachedLocalBeatmaps = null)
        {
            LocalBeatmaps localBeatmaps = cachedLocalBeatmaps is null ? new LocalBeatmaps() : new LocalBeatmaps(cachedLocalBeatmaps);
            List <string> songs         = Directory.GetDirectories(SongsPath).ToList();

            foreach (LocalBeatmap beatmap in localBeatmaps.Maps.ToList())
            {
                string song = songs.FirstOrDefault(x => new DirectoryInfo(x).Name.Split(" ")[0] == beatmap.Identifier.Value);

                if (song != null)
                {
                    songs.Remove(song);
                }
            }

            for (int i = 0; i < songs.Count; i++)
            {
                if (i > 0 && i % 10 == 0)
                {
                    localBeatmaps.LastPage++;
                }
            }

            foreach (string songFolder in songs)
            {
                string infoFile = Path.Combine(songFolder, "info.dat");
                if (!File.Exists(infoFile))
                {
                    continue;
                }

                string[]        folderName = new DirectoryInfo(songFolder).Name.Split(" ");
                LocalIdentifier identifier = folderName.Length == 1 ? new LocalIdentifier(false, folderName[0]) : new LocalIdentifier(true, folderName[0]);

                string json = await File.ReadAllTextAsync(infoFile);

                LocalBeatmap beatmap = JsonConvert.DeserializeObject <LocalBeatmap>(json);
                beatmap.Identifier = identifier;
                beatmap.FolderPath = songFolder;

                string coverImagePath = Path.Combine(songFolder, beatmap.CoverImageFilename);
                if (File.Exists(coverImagePath))
                {
                    beatmap.CoverImagePath = coverImagePath;
                }
                else
                {
                    if (beatmap.Errors is null)
                    {
                        beatmap.Errors = new List <string>();
                    }

                    beatmap.Errors.Add($"The cover image file '{beatmap.CoverImageFilename}' couldn't be found");
                }

                string songFilePath = Path.Combine(songFolder, beatmap.SongFilename);
                if (File.Exists(songFilePath))
                {
                    MediaInfo mediaInfo = ffProbe.GetMediaInfo(songFilePath);
                    beatmap.Duration = mediaInfo.Duration;
                }
                else
                {
                    if (beatmap.Errors is null)
                    {
                        beatmap.Errors = new List <string>();
                    }

                    beatmap.Errors.Add($"The song file '{beatmap.SongFilename}' couldn't be found");
                }

                foreach (DifficultyBeatmapSet difficultyBeatmapSet in beatmap.DifficultyBeatmapSets)
                {
                    if (!beatmap.Easy && difficultyBeatmapSet.DifficultyBeatmaps.Any(x => x.Difficulty == "Easy"))
                    {
                        beatmap.Easy = true;
                    }
                    if (!beatmap.Normal && difficultyBeatmapSet.DifficultyBeatmaps.Any(x => x.Difficulty == "Normal"))
                    {
                        beatmap.Normal = true;
                    }
                    if (!beatmap.Hard && difficultyBeatmapSet.DifficultyBeatmaps.Any(x => x.Difficulty == "Hard"))
                    {
                        beatmap.Hard = true;
                    }
                    if (!beatmap.Expert && difficultyBeatmapSet.DifficultyBeatmaps.Any(x => x.Difficulty == "Expert"))
                    {
                        beatmap.Expert = true;
                    }
                    if (!beatmap.ExpertPlus && difficultyBeatmapSet.DifficultyBeatmaps.Any(x => x.Difficulty == "ExpertPlus"))
                    {
                        beatmap.ExpertPlus = true;
                    }
                }

                _ = Task.Run(async() =>
                {
                    try
                    {
                        beatmap.OnlineBeatmap = await GetBeatmap(identifier);
                    }
                    catch (Exception e)
                    {
                        if (beatmap.Errors is null)
                        {
                            beatmap.Errors = new List <string>();
                        }

                        if (e.InnerException is null || string.Equals(e.Message, e.InnerException.Message))
                        {
                            beatmap.Errors.Add(e.Message);
                        }