예제 #1
0
        /// <summary>
        /// برش ویدیو براساس زمان ابتدا و انتها
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task CutDownAsync(string sourceFile, int?startTime, int?endTime)
        {
            if (startTime == null)
            {
                startTime = 0;
            }
            if (endTime == null)
            {
                endTime = new FFProbe().GetMediaInfo(sourceFile).Streams.Length;
            }
            if (startTime >= endTime)
            {
                return;
            }

            var destinationFile = Path.GetFileNameWithoutExtension(sourceFile) + "_cut" + Path.GetExtension(sourceFile);
            var ffMpegConverter = new FFMpegConverter();
            var convertSettings = new ConvertSettings
            {
                Seek        = startTime,
                MaxDuration = endTime - startTime,
                VideoCodec  = "copy",
                AudioCodec  = "copy"
            };

            ffMpegConverter.ConvertMedia(sourceFile, null, destinationFile, null, convertSettings);
        }
예제 #2
0
        public void Probe_Success_FromStream()
        {
            using var stream = File.OpenRead(TestResources.WebmVideo);
            var info = FFProbe.Analyse(stream);

            Assert.AreEqual(3, info.Duration.Seconds);
        }
        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;
            }));
        }
예제 #4
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;
        }
예제 #5
0
        public async Task Video_Cancel_Async_With_Timeout()
        {
            var outputFile = new TemporaryFile("out.mp4");

            var task = FFMpegArguments
                       .FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
                                      .WithCustomArgument("-re")
                                      .ForceFormat("lavfi"))
                       .OutputToFile(outputFile, false, opt => opt
                                     .WithAudioCodec(AudioCodec.Aac)
                                     .WithVideoCodec(VideoCodec.LibX264)
                                     .WithSpeedPreset(Speed.VeryFast))
                       .CancellableThrough(out var cancel, 10000)
                       .ProcessAsynchronously(false);

            await Task.Delay(300);

            cancel();

            var result = await task;

            var outputInfo = await FFProbe.AnalyseAsync(outputFile);

            Assert.IsTrue(result);
            Assert.IsNotNull(outputInfo);
            Assert.AreEqual(320, outputInfo.PrimaryVideoStream !.Width);
            Assert.AreEqual(240, outputInfo.PrimaryVideoStream.Height);
            Assert.AreEqual("h264", outputInfo.PrimaryVideoStream.CodecName);
            Assert.AreEqual("aac", outputInfo.PrimaryAudioStream !.CodecName);
        }
예제 #6
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();
        }
예제 #7
0
        public void Video_Duration()
        {
            var video  = FFProbe.Analyse(VideoLibrary.LocalVideo.FullName);
            var output = Input.OutputLocation(VideoType.Mp4);

            try
            {
                FFMpegArguments
                .FromFileInput(VideoLibrary.LocalVideo)
                .OutputToFile(output, false, opt => opt.WithDuration(TimeSpan.FromSeconds(video.Duration.TotalSeconds - 2)))
                .ProcessSynchronously();

                Assert.IsTrue(File.Exists(output));
                var outputVideo = FFProbe.Analyse(output);

                Assert.AreEqual(video.Duration.Days, outputVideo.Duration.Days);
                Assert.AreEqual(video.Duration.Hours, outputVideo.Duration.Hours);
                Assert.AreEqual(video.Duration.Minutes, outputVideo.Duration.Minutes);
                Assert.AreEqual(video.Duration.Seconds - 2, outputVideo.Duration.Seconds);
            }
            finally
            {
                if (File.Exists(output))
                {
                    File.Delete(output);
                }
            }
        }
        // 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;
        }
예제 #9
0
        public void Probe_Success()
        {
            var info = FFProbe.Analyse(VideoLibrary.LocalVideo.FullName);

            Assert.AreEqual(13, info.Duration.Seconds);
            Assert.AreEqual(".mp4", info.Extension);
            Assert.AreEqual(VideoLibrary.LocalVideo.FullName, info.Path);

            Assert.AreEqual("5.1", info.PrimaryAudioStream.ChannelLayout);
            Assert.AreEqual(6, info.PrimaryAudioStream.Channels);
            Assert.AreEqual("AAC (Advanced Audio Coding)", info.PrimaryAudioStream.CodecLongName);
            Assert.AreEqual("aac", info.PrimaryAudioStream.CodecName);
            Assert.AreEqual("LC", info.PrimaryAudioStream.Profile);
            Assert.AreEqual(381988, info.PrimaryAudioStream.BitRate);
            Assert.AreEqual(48000, info.PrimaryAudioStream.SampleRateHz);

            Assert.AreEqual(862991, info.PrimaryVideoStream.BitRate);
            Assert.AreEqual(16, info.PrimaryVideoStream.DisplayAspectRatio.Width);
            Assert.AreEqual(9, info.PrimaryVideoStream.DisplayAspectRatio.Height);
            Assert.AreEqual("yuv420p", info.PrimaryVideoStream.PixelFormat);
            Assert.AreEqual(1280, info.PrimaryVideoStream.Width);
            Assert.AreEqual(720, info.PrimaryVideoStream.Height);
            Assert.AreEqual(25, info.PrimaryVideoStream.AvgFrameRate);
            Assert.AreEqual(25, info.PrimaryVideoStream.FrameRate);
            Assert.AreEqual("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", info.PrimaryVideoStream.CodecLongName);
            Assert.AreEqual("h264", info.PrimaryVideoStream.CodecName);
            Assert.AreEqual(8, info.PrimaryVideoStream.BitsPerRawSample);
            Assert.AreEqual("Main", info.PrimaryVideoStream.Profile);
        }
예제 #10
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);
            }
        }
예제 #11
0
        protected async Task CreateOutput(Action <double> progress, IReadOnlyList <Video> videos, string outputFile)
        {
            await Task.WhenAll(videos.Select(this.CreateOutput));

            FFMpegCore.FFMpegArguments ffmpeg = null;
            foreach (var video in videos)
            {
                if (ffmpeg == null)
                {
                    ffmpeg = FFMpegCore.FFMpegArguments.FromFileInput(GetCombineVideoPath(video));
                }
                else
                {
                    ffmpeg = ffmpeg.AddFileInput(GetCombineVideoPath(video));
                }
            }

            try {
                var duration = (await FFProbe.AnalyseAsync(GetCombineVideoPath(videos[0]))).Duration;
                await ffmpeg.OutputToFile(outputFile, true, _ => this.ApplyOption(videos, _))
                .NotifyOnProgress(progress, duration)
                .ProcessAsynchronously();
            }
            catch (Exception e) {
                Console.Error.WriteLine(e.ToString());
            }
        }
예제 #12
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);
        }
예제 #13
0
        public async Task Probe_Success_FromStream_Async()
        {
            await using var stream = File.OpenRead(TestResources.WebmVideo);
            var info = await FFProbe.AnalyseAsync(stream);

            Assert.AreEqual(3, info.Duration.Seconds);
        }
예제 #14
0
        public async Task Probe_Success_FromStream_Async()
        {
            await using var stream = File.OpenRead(VideoLibrary.LocalVideoWebm.FullName);
            var info = await FFProbe.AnalyseAsync(stream);

            Assert.AreEqual(3, info.Duration.Seconds);
        }
예제 #15
0
        public void Video_Join_Image_Sequence()
        {
            var imageSet = new List <ImageInfo>();

            Directory.EnumerateFiles(TestResources.ImageCollection)
            .Where(file => file.ToLower().EndsWith(".png"))
            .ToList()
            .ForEach(file =>
            {
                for (var i = 0; i < 15; i++)
                {
                    imageSet.Add(new ImageInfo(file));
                }
            });

            var outputFile = new TemporaryFile("out.mp4");
            var success    = FFMpeg.JoinImageSequence(outputFile, images: imageSet.ToArray());

            Assert.IsTrue(success);
            var result = FFProbe.Analyse(outputFile);

            Assert.AreEqual(3, result.Duration.Seconds);
            Assert.AreEqual(imageSet.First().Width, result.PrimaryVideoStream.Width);
            Assert.AreEqual(imageSet.First().Height, result.PrimaryVideoStream.Height);
        }
예제 #16
0
        public static async Task <TimeSpan?> GetAccumulatedTimeAsync(IEnumerable <string> filePath)
        {
            var totalTime = new TimeSpan();

            foreach (var file in filePath)
            {
                try
                {
                    var info = await FFProbe.AnalyseAsync(file);

                    if (info == null)
                    {
                        return(null);
                    }

                    totalTime += info.Duration;
                }
                catch
                {
                    return(null);
                }
            }

            return(totalTime);
        }
예제 #17
0
        public void Probe_Success_FromStream()
        {
            using var stream = File.OpenRead(VideoLibrary.LocalVideoWebm.FullName);
            var info = FFProbe.Analyse(stream);

            Assert.AreEqual(3, info.Duration.Seconds);
        }
예제 #18
0
        public void Probe_Success()
        {
            var info = FFProbe.Analyse(TestResources.Mp4Video);

            Assert.AreEqual(3, info.Duration.Seconds);

            Assert.AreEqual("5.1", info.PrimaryAudioStream !.ChannelLayout);
            Assert.AreEqual(6, info.PrimaryAudioStream.Channels);
            Assert.AreEqual("AAC (Advanced Audio Coding)", info.PrimaryAudioStream.CodecLongName);
            Assert.AreEqual("aac", info.PrimaryAudioStream.CodecName);
            Assert.AreEqual("LC", info.PrimaryAudioStream.Profile);
            Assert.AreEqual(377351, info.PrimaryAudioStream.BitRate);
            Assert.AreEqual(48000, info.PrimaryAudioStream.SampleRateHz);

            Assert.AreEqual(1471810, info.PrimaryVideoStream !.BitRate);
            Assert.AreEqual(16, info.PrimaryVideoStream.DisplayAspectRatio.Width);
            Assert.AreEqual(9, info.PrimaryVideoStream.DisplayAspectRatio.Height);
            Assert.AreEqual("yuv420p", info.PrimaryVideoStream.PixelFormat);
            Assert.AreEqual(1280, info.PrimaryVideoStream.Width);
            Assert.AreEqual(720, info.PrimaryVideoStream.Height);
            Assert.AreEqual(25, info.PrimaryVideoStream.AvgFrameRate);
            Assert.AreEqual(25, info.PrimaryVideoStream.FrameRate);
            Assert.AreEqual("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", info.PrimaryVideoStream.CodecLongName);
            Assert.AreEqual("h264", info.PrimaryVideoStream.CodecName);
            Assert.AreEqual(8, info.PrimaryVideoStream.BitsPerRawSample);
            Assert.AreEqual("Main", info.PrimaryVideoStream.Profile);
        }
예제 #19
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);
        }
예제 #21
0
        public void CTOR_Default()
        {
            var encoder = new FFMpeg();
            var probe   = new FFProbe();

            Assert.IsNotNull(encoder);
            Assert.IsNotNull(probe);
        }
예제 #22
0
        public void Video_With_Only_Audio_Should_Extract_Metadata()
        {
            var video = FFProbe.Analyse(TestResources.Mp4WithoutVideo);

            Assert.AreEqual(null, video.PrimaryVideoStream);
            Assert.AreEqual("aac", video.PrimaryAudioStream.CodecName);
            Assert.AreEqual(10, video.Duration.TotalSeconds, 0.5);
        }
예제 #23
0
        public void Probe_Success()
        {
            var output = new FFProbe();

            var info = output.ParseVideoInfo(VideoLibrary.LocalVideo.FullName);

            Assert.AreEqual(13, info.Duration.Seconds);
        }
예제 #24
0
        public async Task Produce(IBoundedQueue <MutableByteImage> sourceQueue)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(_arguments.PathToFfmpeg))
                {
                    FFMpegOptions.Configure(new FFMpegOptions
                    {
                        RootDirectory = _arguments.PathToFfmpeg
                    });
                }

                var result = await FFProbe.AnalyseAsync(_arguments.InputFile).ConfigureAwait(false);

                var width          = result.PrimaryVideoStream.Width;
                var height         = result.PrimaryVideoStream.Height;
                var bpp            = Image.GetPixelFormatSize(System.Drawing.Imaging.PixelFormat.Format24bppRgb) / 8;
                var pixelsPerFrame = width * height;

                var frameSizeInBytes = pixelsPerFrame * bpp;

                _logger.WriteLine("Input from ffmpeg currently only supports rgb24-convertable input", Verbosity.Warning);

                var chunksQueue = BoundedQueueFactory.Get <byte[]>(4, "In-ChuQ");
                using var memoryStream = new ChunkedSimpleMemoryStream(frameSizeInBytes, chunksQueue); // new MemoryStream(frameSizeInBytes);
                StreamPipeSink sink = new StreamPipeSink(memoryStream);
                var            args = FFMpegArguments
                                      .FromFileInput(_arguments.InputFile).OutputToPipe(sink, options =>
                                                                                        options.DisableChannel(FFMpegCore.Enums.Channel.Audio)
                                                                                        .UsingMultithreading(true)
                                                                                        .ForceFormat("rawvideo")
                                                                                        .WithCustomArgument(_arguments.CustomArgs ?? string.Empty)
                                                                                        .ForcePixelFormat("bgr24"))
                                      .NotifyOnProgress(
                    percent => _logger.NotifyFillstate(Convert.ToInt32(percent), "InputVideoParsing"),
                    TimeSpan.FromSeconds(1));

                var produceTask = args.ProcessAsynchronously(true).ContinueWith((_) =>
                {
                    chunksQueue.CompleteAdding();
                    sourceQueue.CompleteAdding();
                });
                var consumeTask = ParseInputStream(sourceQueue, chunksQueue, width, height, memoryStream)
                                  .ContinueWith((_) => _logger.WriteLine("finished reading", Verbosity.Info));

                await Task.WhenAll(produceTask, consumeTask);

                _logger.WriteLine("finished reading", Verbosity.Info);
            }
            catch (System.ComponentModel.Win32Exception)
            {
                _logger.WriteLine("Couldn't find ffmpeg", Verbosity.Error);
            }
            catch (Exception e)
            {
                _logger.LogException(e);
            }
        }
예제 #25
0
        public async Task Probe_Success_Subtitle_Async()
        {
            var info = await FFProbe.AnalyseAsync(TestResources.SrtSubtitle);

            Assert.IsNotNull(info.PrimarySubtitleStream);
            Assert.AreEqual(1, info.SubtitleStreams.Count);
            Assert.AreEqual(0, info.AudioStreams.Count);
            Assert.AreEqual(0, info.VideoStreams.Count);
        }
예제 #26
0
        public async Task Audio_FromStream_Duration()
        {
            var fileAnalysis = await FFProbe.AnalyseAsync(TestResources.WebmVideo);

            await using var inputStream = File.OpenRead(TestResources.WebmVideo);
            var streamAnalysis = await FFProbe.AnalyseAsync(inputStream);

            Assert.IsTrue(fileAnalysis.Duration == streamAnalysis.Duration);
        }
예제 #27
0
        public async Task Probe_Success_Disposition_Async()
        {
            var info = await FFProbe.AnalyseAsync(TestResources.Mp4Video);

            Assert.IsNotNull(info.PrimaryAudioStream);
            Assert.IsNotNull(info.PrimaryAudioStream.Disposition);
            Assert.AreEqual(true, info.PrimaryAudioStream.Disposition["default"]);
            Assert.AreEqual(false, info.PrimaryAudioStream.Disposition["forced"]);
        }
예제 #28
0
        public void Image_AddAudio()
        {
            using var outputFile = new TemporaryFile("out.mp4");
            FFMpeg.PosterWithAudio(TestResources.PngImage, TestResources.Mp3Audio, outputFile);
            var analysis = FFProbe.Analyse(TestResources.Mp3Audio);

            Assert.IsTrue(analysis.Duration.TotalSeconds > 0);
            Assert.IsTrue(File.Exists(outputFile));
        }
예제 #29
0
        public async Task <double> GetMovieLength(string filename)
        {
            var mediaAnalysis = await FFProbe.AnalyseAsync(filename);

            return(mediaAnalysis.Duration.TotalSeconds);

            //var result = await MediaToolkitService.ExecuteAsync(new FfTaskGetMetadata(filename));
            //return result.Metadata.Streams.Select(e => double.Parse(e.Duration)).Max();
        }
예제 #30
0
        public void Probe_TooLongOutput()
        {
            var output = new FFProbe(5);

            Assert.ThrowsException <JsonSerializationException>(() =>
            {
                output.ParseVideoInfo(VideoLibrary.LocalVideo.FullName);
            });
        }
        public async Task <string> Handle(CreateSnapshotCommand @event, CancellationToken cancellationToken = default)
        {
            var tempFile = _tempFileService.GetFilename("generated", ".png");
            var analysis = await FFProbe.AnalyseAsync(@event.InputVideoFilePath);

            await FFMpeg.SnapshotAsync(@event.InputVideoFilePath, tempFile, new Size(@event.Width, @event.Height), analysis !.Duration * @event.SeekPercentage);

            return(tempFile);
        }
예제 #32
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();
    }
예제 #33
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;
		}