Example #1
1
 public void Open()
 {
     _videoFileReader = new VideoFileReader();
     _videoFileReader.Open(_fileName);
     _frameCount = _videoFileReader.FrameCount;
     _frameRate = _videoFileReader.FrameRate;
     _height = _videoFileReader.Height;
     _width = _videoFileReader.Width;
 }
Example #2
0
        public void ReadFromVideo(string path)
        {
            pathToFile = new Uri(AnaglyphParameters.VideoPath.LocalPath);
            AnaglyphParameters.PathToRead  = pathToFile.LocalPath;
            AnaglyphParameters.PathToWrite = path.Split('.')[0] + "1.mp4";
            reader.Open(pathToFile.LocalPath);

            SetWriter(reader, writer);


            for (int i = 0; i < reader.FrameCount; i++)
            {
                OnOnFrameDone(i, (int)reader.FrameCount);
                try
                {
                    using (Bitmap videoFrame = reader.ReadVideoFrame(i))
                    {
                        using (Bitmap videoFrameChanged = new Fitler().Calc(videoFrame))
                        {
                            writer.WriteVideoFrame(videoFrameChanged, (uint)i);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
            }
            reader.Close();
            writer.Close();

            VideoToFrames.AddAudioToVideo(path);
            OnOnProcessDone();
        }
Example #3
0
        public static void Generate()
        {
            var reader = new VideoFileReader();

            reader.Open(VideoPath + VideoName);
            var    writer         = new VideoFileWriter();
            var    numberOfFrames = (int)reader.FrameCount;
            Bitmap probeBitmap    = reader.ReadVideoFrame(0);

            if (numberOfFrames > probeBitmap.Width)        //if user want -> fit to original width
            {
                numberOfFrames = probeBitmap.Width;
            }
            writer.Open(VideoPath + "out.mp4", numberOfFrames, probeBitmap.Height, OutputFps, VideoCodec.H265);
            for (var x = 0; x < probeBitmap.Width; x++)
            {
                var convertedBitmap = new Bitmap(numberOfFrames, probeBitmap.Height);
                reader.Open(VideoPath + VideoName);
                for (var f = 0; f < numberOfFrames; f++)
                {
                    var currentBitmap = reader.ReadVideoFrame();
                    for (var y = 0; y < probeBitmap.Height; y++)
                    {
                        convertedBitmap.SetPixel(f, y, currentBitmap.GetPixel(x, y));
                    }
                    currentBitmap.Dispose();
                }
                writer.WriteVideoFrame(convertedBitmap);
                convertedBitmap.Dispose();
            }
            reader.Dispose();
            writer.Close();
        }
Example #4
0
 public Video(string path)
 {
     _path = path;
     _reader.Open(path);
     FrameCount = _reader.FrameCount;
     FrameRate  = _reader.FrameRate;
 }
Example #5
0
        public Task <Bitmap> GetFrame(long frame)
        {
            if (!_reader.IsOpen)
            {
                _reader.Open(Path);
                CurrentFrame = 0;
            }

            if (frame < CurrentFrame)
            {
                _reader.Close();
                _reader.Open(Path);
                CurrentFrame = 0;
            }
            return(Task.Run(() =>
            {
                while (CurrentFrame < frame)
                {
                    _reader.ReadVideoFrame().Dispose();
                    CurrentFrame++;
                }
                CurrentFrame = frame;
                return _reader.ReadVideoFrame();
            }));
        }
Example #6
0
 public Video(string path)
 {
     FullPath = path;
     _reader.Open(path);
     Name       = Path.GetFileName(path);
     FrameCount = _reader.FrameCount;
     FrameRate  = _reader.FrameRate;
     Duration   = FrameCount / FrameRate;
     Tags       = new Dictionary <double, List <Tag> >();
 }
Example #7
0
        //先check有没有这个本地文件,没有返回null
        //设置reader并返回[frameRate, height, width]的header List
        //读video的时候自动导出audio
        public List <String> loadFile(String name, String type)
        {
            flush();
            if (System.IO.File.Exists(name))
            {
                List <String> header = new List <string>();
                switch (type)
                {
                case "wmv":
                    current_type = "wmv";
                    address      = name;
                    video_wmv.Open(name);
                    header.Add("" + video_wmv.FrameRate);
                    header.Add("" + video_wmv.Height);
                    header.Add("" + video_wmv.Width);
                    bmpPerStream = video_wmv.FrameRate;
                    break;

                default:
                    return(null);
                }
                AudioExtract.extract(name);
                return(header);
            }
            else
            {
                return(null);
            }
        }
Example #8
0
        }//void

        public void parcala()
        {
            VideoFileReader reader = new VideoFileReader();
            IWMPMedia       saniye = axWindowsMediaPlayer1.newMedia(ofdVideoYukle.FileName);

            videoFrameList.Clear();

            reader.Open(ofdVideoYukle.FileName);
            this._TotalFrameCount = (int)saniye.duration * reader.FrameRate;
            this._VideoFPS        = reader.FrameRate;
            progressBar1.Maximum  = this._TotalFrameCount;
            FrameSayisi           = _TotalFrameCount;
            for (int i = 0; i < this._TotalFrameCount; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                string yol        = "C://Users//BegovicTeam//Desktop//video sıkıştırma//frameparcalanmis//" + "image" + i + ".mpeg";
                convertMpeg(videoFrame, yol);
                progressBar1.Value += 1;
            }
            reader.Close();
            reader.Dispose();

            birlestir();

            frameParcala.Abort();
        }
Example #9
0
        private void dgOpenFile_FileOk(object sender, CancelEventArgs e)
        {
            String path = dgOpenFile.FileName;

            this.tbPath.Text = path;
            try
            {
                _reader = new VideoFileReader();
                _reader.Open(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                _reader = null;
            }

            tbInfo.Text = String.Empty;

            if (_reader != null)
            {
                String info = String.Format("Video info:\r\n\r\n Width-{0}\r\n Height-{1}\r\n FrameCount-{2}\r\n FrameRate-{3}\r\n Codec-{4}",
                                            _reader.Width, _reader.Height,
                                            _reader.FrameCount, _reader.FrameRate, _reader.CodecName);
                tbInfo.Text = info;
            }

            ShowNextFrame();
        }
        static void PlayVideoAForgeFFMPEG(IStreamDeck deck, string videoPath)
        {
            using (VideoFileReader reader = new VideoFileReader())
            {
                reader.Open(videoPath);
                var fr          = reader.FrameRate;
                int frameLength = (int)Math.Round(1000.0 / fr);

                while (true)
                {
                    var sw = Stopwatch.StartNew();
                    using (var frame = reader.ReadVideoFrame())
                    {
                        if (frame == null)
                        {
                            return;
                        }
                        deck.DrawFullScreenBitmap(frame);
                        var wait = frameLength - (int)sw.ElapsedMilliseconds;
                        sw.Restart();
                        if (wait > 0)
                        {
                            Thread.Sleep(wait);
                        }
                    }
                }
            }
        }
Example #11
0
        public static Vector3[,] Medium(string path, int steps = 100)
        {
            VideoFileReader reader = new VideoFileReader();

            reader.Open(path);

            Vector3[,] data = new Vector3[reader.Width, reader.Height];

            var temp = new Image <Rgb, float>(reader.Width, reader.Height);


            for (int i = 0; i < steps; i++)
            {
                using (Bitmap img = reader.ReadVideoFrame(i * (int)reader.FrameCount / steps))
                {
                    var arr = new Image <Rgb, float>(img);
                    temp.Accumulate(arr);
                    //temp.WriteRGB(img);
                    //data.ForEach(temp, (m, v) => m.Add(v));
                }
            }

            for (int x = 0; x < reader.Width; x++)
            {
                for (int y = 0; y < reader.Height; y++)
                {
                    Rgb rgb = temp[y, x];
                    data[x, y] = new Vector3((float)rgb.Red / steps / 255, (float)rgb.Green / steps / 255, (float)rgb.Blue / steps / 255);
                }
            }

            reader.Close();

            return(data);
        }
Example #12
0
        /* ---------------------------------------------------------------------
         * readVideo
         * ---------------------------------------------------------------------
         * Reads the video, saving all its frames and creating the intensity
         * matrix for each one.
         * Preconditions:
         *  -video of specified name exists
         */
        private void readVideo()
        {
            String VideoPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

            VideoPath = VideoPath + "\\Resources\\20020924_juve_dk_02a.avi";
            bool intensityExists = readIntensityFile();

            using (var vFReader = new VideoFileReader())
            {
                vFReader.Open(VideoPath);

                // get video info to remake video when done
                this.vWidth     = vFReader.Width;
                this.vHeight    = vFReader.Height;
                this.vFramerate = vFReader.FrameRate;

                // store each image and intensities into the arrays
                for (int i = 1000; i < 5000; i++)
                {
                    System.Drawing.Bitmap bmpBaseOriginal = vFReader.ReadVideoFrame();
                    FrameMatrix[i] = bmpBaseOriginal;
                }
                vFReader.Close();

                if (!intensityExists)
                {
                    getIntensity();
                    writeIntensityFile();
                }
            }
        }
Example #13
0
        public List <byte> GetFileBytes(int start, int end, int increment, int boxSize)
        {
            VideoFileReader reader = new VideoFileReader();

            reader.Open(_filename);

            List <byte> fileBytes = new List <byte>();

            _progressCount = 0;

            for (int i = start; i < end; i++)
            {
                Console.WriteLine("i: " + i + " < " + end);
                using (Bitmap fileImage = reader.ReadVideoFrame(i)) {
                    if (i % increment == 0)
                    {
                        GetVideoFrameBytes(fileBytes, fileImage, boxSize);

                        _progressCount++;

                        ReportProgress(increment);
                    }
                }
            }

            return(fileBytes);
        }
Example #14
0
        public void PlayAvi(string path, bool saveScreen = false)
        {
            var i = 0;

            try
            {
                var s      = new VideoFileSource(path);
                var reader = new VideoFileReader();
                var uri    = new Uri(path);
                reader.Open(uri.AbsolutePath);
                int framesToSkip = reader.FrameRate * 3600;

                var seconds = reader.FrameCount / reader.FrameRate;

                for (i = 0; i < reader.FrameCount; i++)
                {
                    try
                    {
                        var screen = reader.ReadVideoFrame();
                        Console.WriteLine(i);
                        if (i % 25 == 0)
                        {
                            screen.Save(@"screen_" + i.ToString() + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    } catch { }
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
            }
        }
        private async Task DoPlaying()
        {
            var reader = new List <VideoFileReader>();

            for (int i = 0; i < APPCONTANTS.CameraCount; i++)
            {
                var cam = new VideoFileReader();
                reader.Add(cam);
                cam.Open(ConfigurationManager.AppSettings["cam" + (i + 1)]);
            }
            while (true)
            {
                for (int i = 0; i < APPCONTANTS.CameraCount; i++)
                {
                    Bitmap frame = reader[i].ReadVideoFrame();
                    await ProcessFrame(frame, $"cam{i + 1}");
                }
                //Do whatever with the frame...
                if (!IsPlaying)
                {
                    break;
                }
                //Thread.Sleep(500);
            }
            for (int i = 0; i < APPCONTANTS.CameraCount; i++)
            {
                reader[i].Close();
            }
            //Debug.WriteLine("frame captured : " + e.DateStamp);
            //await ProcessFrame(e.ToImage(), FrameId[(sender as FrameCapture).ID]);
        }
 // Function to get one image from the file (if null returned it failed)
 public Bitmap getPreview()
 {
     Bitmap preview = null;
     VideoFileReader Temp = new VideoFileReader();
     try
     {
         Temp.Open(file);
     }
     catch
     {
         return preview;
     }
     // try if possible to extract a frame (use this one, to return for drawing)
     try
     {
         int frametotake = (int)Temp.FrameCount;
         for (int i = 0; i < (frametotake - 1) && i < 10; i++)
         {
             Temp.ReadVideoFrame();
         }
         preview = Temp.ReadVideoFrame();
     }
     catch
     {
         return preview;
     }
     return preview;
 }
Example #17
0
File: Form1.cs Project: radtek/HINO
        void AddVideo(string path)
        {
            if (Program.videos.ContainsKey(path))
            {
                MessageBox.Show("Video '" + path + "' is duplicated. It will be removed.", "Duplicated video", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            VideoFileReader reader = new VideoFileReader();
            reader.Open(path);

            listBox1.Items.Add(path);
            Program.videos.Add(path, reader);

            if (label1.Visible)
            {
                if (Settings.cutTop == -1)
                {
                    Settings.cutTop = reader.Height / 6;
                    Settings.cutBottom = reader.Height - Settings.cutTop;
                }
                start.Enabled = true;
                button1.Enabled = true;
                listBox1.SelectedIndex = 0;
                label1.Visible = false;

                Settings.saveSubsPath = Path.GetDirectoryName(path);
            }
        }
Example #18
0
        //Méthode permettant de de créer un apercu d'une image à partir d'une vidéo et la situe à l'endroit de la vidéo
        public static string createPreviewFromVideo(string pathVideo, string cameraName)
        {
            //Path de l'image qui sera créé par la suite
            string pathImage = "";

            if (!String.IsNullOrEmpty(pathVideo))
            {
                VideoFileReader reader = new VideoFileReader();
                //Ouvre la video
                reader.Open(pathVideo);
                //Lit la première image
                Bitmap videoFrame = reader.ReadVideoFrame();
                if (String.IsNullOrEmpty(cameraName))
                {
                    pathImage = Path.GetDirectoryName(pathVideo) + @"\" + Path.GetFileNameWithoutExtension(pathVideo) + "image.png";
                }
                else
                {
                    pathImage = Path.GetDirectoryName(pathVideo) + @"\" + cameraName + "image.png";
                }
                //Ecrase l'image si le nom est déjà pris
                if (File.Exists(pathImage))
                {
                    File.Delete(pathImage);
                }

                videoFrame.Save(pathImage);
                //On libère les ressources
                videoFrame.Dispose();
                reader.Close();
            }

            return(pathImage);
        }
Example #19
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            VideoFileReader reader = new VideoFileReader();

            reader.Open(fileName);
            for (int i = 0; i < reader.FrameCount; i++)
            {
                read.Add(reader.ReadVideoFrame());
                write.Add(NegativGeneralas(read[i]));
            }

            VideoFileWriter writer = new VideoFileWriter();

            writer.Open("eredmeny_" + fileName, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, reader.BitRate);
            for (int i = 0; i < write.Count; i++)
            {
                writer.WriteVideoFrame(write[i]);
            }
            reader.Close();
            writer.Close();
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);
            Console.ReadLine();
        }
Example #20
0
        //Call following function only once...
        public void ReadVideoFile()
        {
            VideoFileReader reader       = new VideoFileReader();
            List <Bitmap>   frameCapture = new List <Bitmap>();

            reader.Open(Environment.CurrentDirectory + @"\20020924_juve_dk_02a_1.avi");
            // check some of its attributes
            Console.WriteLine("width:  " + reader.Width);
            Console.WriteLine("height: " + reader.Height);
            Console.WriteLine("fps:    " + reader.FrameRate);
            Console.WriteLine("codec:  " + reader.CodecName);
            // read 100 video frames out of it
            for (int i = 0; i < 5000; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                if (i < 1000)
                {
                    continue;
                }
                videoFrame.Save(Environment.CurrentDirectory + @"/images/VideoFrameImageDetails" + i + ".bmp");
                videoFrame.Dispose();
            }

            reader.Close();
        }
Example #21
0
        protected async override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            if (!FFmpegService.FFmpegExists)
            {
                this.Enabled = false;
                await FFmepgDownload.DownloadArchive((i) =>
                {
                    this.Text = $"下载中{i}%";
                }, cancellationTokenSource.Token);

                this.Enabled = true;
            }
            videoFileReader = new VideoFileReader()
            {
                FPS = 25
            };
            videoFileReader.Open("Videos/girl.mp4");
            await Task.Run(() =>
            {
                foreach (var frame in videoFileReader.ReadVideoFrames(size: this.ClientSize, readByNativeFrame: true, cancellationToken: cancellationTokenSource.Token))
                {
                    using (frame.FrameBitmap)
                        using (Graphics g = this.CreateGraphics())
                        {
                            g.DrawImage(frame.FrameBitmap, 0, 0);
                        }
                }
            });
        }
        private static void Main()
        {
            var reader = new VideoFileReader();

            reader.Open(@"your video here");

            // video attributes
            Console.WriteLine("width:  " + reader.Width);
            Console.WriteLine("height: " + reader.Height);
            Console.WriteLine("fps:    " + reader.FrameRate);
            Console.WriteLine("codec:  " + reader.CodecName);

            // read video frames
            while (true)
            {
                using (var videoFrame = reader.ReadVideoFrame())
                {
                    if (videoFrame == null)
                    {
                        break;
                    }

                    // process the frame here
                }
            }

            reader.Close();
        }
Example #23
0
        private void convert()
        {
            try
            {
                VideoFileReader reader = new VideoFileReader();
                reader.Open(m_mp4File);
                Bitmap videoFrame  = null;
                int    frame       = 0;
                int    scratchfile = 0;
                while ((videoFrame = reader.ReadVideoFrame()) != null)
                {
                    if (frame % reader.FrameRate == 0)
                    {
                        Console.WriteLine("Frame: " + frame);

                        byte[] buffer = imageToByteArray(videoFrame);
                        m_dictionary.Add(scratchfile, getMd5Hash(buffer));
                        videoFrame.Save("C:/temp/" + scratchfile.ToString() + ".png", ImageFormat.Png);
                        videoFrame.Dispose();
                        videoFrame = null;
                        ++scratchfile;
                    }
                    ++frame;
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #24
0
        public async Task Transfer(VideoHeader header, Stream source)
        {
            Guard.NotNull(() => header, header);
            Guard.NotNull(() => source, source);

            var temp = Path.GetTempFileName();

            using (StreamWriter write = new StreamWriter(temp))
            {
                await source.CopyToAsync(write.BaseStream).ConfigureAwait(false);
            }

            try
            {
                using (VideoFileReader reader = new VideoFileReader())
                {
                    reader.Open(temp);
                    using (Bitmap videoFrame = reader.ReadVideoFrame())
                    {
                        videoFrame.Save(ResolveName(header), ImageFormat.Png);
                    }
                }
            }
            finally
            {
                File.Delete(temp);
            }
        }
Example #25
0
        private static void VideoProcessing(string videoPath, string outputFolder)
        {
            VideoFileReader videoFileReader = new VideoFileReader();

            videoFileReader.Open(videoPath);
            Console.WriteLine("Video loaded (" + videoFileReader.FrameCount + " frames)");

            Size scaledSize = new Size((int)Math.Round(videoFileReader.Width * scalingFactor), (int)Math.Round(videoFileReader.Height * scalingFactor));

            Console.WriteLine("Analyzing frames");

            for (int i = 0; i < videoFileReader.FrameCount; i++)
            {
                DrawTextProgressBar(i + 1, (int)videoFileReader.FrameCount);
                using (Bitmap frame = videoFileReader.ReadVideoFrame())
                {
                    using (Bitmap scaled = new Bitmap(frame, scaledSize))
                    {
                        float brightness = scaled.BrightnessOfBrightestPixels(0.02);
                        if (brightness > 0.09f)
                        {
                            frame.Save(outputFolder + @"\" + i.ToString().PadLeft(5, '0') + ".bmp");
                        }
                    }
                }
            }
            videoFileReader.Close();

            Console.WriteLine("Done");
        }
        // Function to get one image from the file (if null returned it failed)
        public Bitmap getPreview()
        {
            Bitmap          preview = null;
            VideoFileReader Temp    = new VideoFileReader();

            try
            {
                Temp.Open(file);
            }
            catch
            {
                return(preview);
            }
            // try if possible to extract a frame (use this one, to return for drawing)
            try
            {
                int frametotake = (int)Temp.FrameCount;
                for (int i = 0; i < (frametotake - 1) && i < 10; i++)
                {
                    Temp.ReadVideoFrame();
                }
                preview = Temp.ReadVideoFrame();
            }
            catch
            {
                return(preview);
            }
            return(preview);
        }
Example #27
0
        /// <summary>
        /// 截取视频缩略图
        /// </summary>
        /// <param name="videoPath">视频路径</param>
        /// <param name="thumbImagePath">缩略图文件路径</param>
        /// <param name="thubWidth">缩略图指定的边长(正方形)</param>
        /// <param name="thubQuality">缩略图质量</param>
        public static void VideoSnapshots(string videoPath, string thumbImagePath, int thubWidth, int thubQuality)
        {
            VideoFileReader reader = new VideoFileReader();

            try
            {
                lock (lockData)
                {
                    reader.Open(videoPath);
                }
                Bitmap bitMap = reader.ReadVideoFrame();
                //创建目录
                string dirPath = Path.GetDirectoryName(thumbImagePath);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                ImageHelper.CutForSquare(bitMap, thumbImagePath, thubWidth, thubQuality);
            }
            finally
            {
                reader.Dispose();
                reader.Close();
            }
        }
Example #28
0
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Multiselect = false;
            // dialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                System.IO.File.Copy(dialog.FileName, dialog.FileName + "temp");
                textBox2.Text = dialog.FileName;
            }
            VideoFileReader reader = new VideoFileReader();

            // open video file
            reader.Open(textBox2.Text);
            // check some of its attributes
            richTextBox1.Text += "width:  " + reader.Width + "\n";
            richTextBox1.Text += "height: " + reader.Height + "\n";
            richTextBox1.Text += "fps:    " + reader.FrameRate + "\n";
            richTextBox1.Text += "codec:  " + reader.CodecName + "\n";
            //for (int i = 0; i < reader.FrameCount; i++)
            //{
            //    Bitmap videoFrame = reader.ReadVideoFrame();
            //    // process the frame somehow
            //    // ...
            //    OldBitmaps.Add(videoFrame);
            //    // dispose the frame when it is no longer required
            //  //  videoFrame.Dispose();
            //}

            reader.Close();
        }
Example #29
0
        private Bitmap GetThumbnail(string fpath)
        {
            VideoFileReader reader = new VideoFileReader();

            // open video file
            reader.Open(fpath);
            return(reader.ReadVideoFrame());
        }
Example #30
0
 private void timer1_Tick_1(object sender, EventArgs e)
 {
     if (k == 0)
     {
         reader.Open(path);
     }
     k++;
     if (i < reader.FrameCount)
     {
         pictureBox4.Image = reader.ReadVideoFrame();
         pictureBox4.Refresh();
         i++;
     }
     else
     {
         timer1.Enabled = false;
     }
 }
Example #31
0
 public FrameProducer(string path, long desiredFramerate, long boxSize, string resultsFile)
 {
     reader.Open(path);
     videoPath        = path;
     BoxSize          = boxSize;
     DesiredFramerate = desiredFramerate;
     TotalFrames      = reader.FrameCount;
     resultsPath      = resultsFile;
 }
Example #32
0
 public void InitVideoReader(string fileName)
 {
     if (_videoFileReader != null && _videoFileReader.IsOpen)
     {
         CloseVideoReader();
     }
     _videoFileReader = new VideoFileReader();
     _videoFileReader.Open(fileName);
 }
Example #33
0
 internal void initVideo(string filePath)
 {
     videoFileReader = new VideoFileReader();
     videoFileReader.Open(filePath);
     VideoWidth = videoFileReader.Width;
     VideoHeight = videoFileReader.Height;
     VideoFrameRate = videoFileReader.FrameRate;
     motionDetector = new MotionDetector(mainWindow);
     VideoInitialized = true;
 }
Example #34
0
 public void VideoFileReaderTest()
 {
     var fileName = @"C:\Datos Lab\videos\480x360Videos\subject01.avi";
     var videoFile = new VideoFileReader();
     videoFile.Open(fileName);
     var bitmap = videoFile.ReadVideoFrame();
     var height = bitmap.Height;
     var width = bitmap.Width;
     videoFile.Close();
     Assert.IsTrue(height > 0 && width > 0);
 }
 // Function to get the length (in frames) from the file (if 0 returned it failed)
 public int getLength()
 {
     VideoFileReader Temp = new VideoFileReader();
     int result = 0;
     try
     {
         Temp.Open(file);
     }
     catch
     {
         return result;
     }
     // try if possible to extract a frame (use this one, to return for drawing)
     try
     {
         result = (int)Temp.FrameCount;
     }
     catch
     {
         return result;
     }
     return result;
 }
Example #36
0
        public void test_read()
        {
            // create instance of video reader
            VideoFileReader reader = new VideoFileReader();
            // open video file
            reader.Open("test.avi");
            // check some of its attributes
            Console.WriteLine("width:  " + reader.Width);
            Console.WriteLine("height: " + reader.Height);
            Console.WriteLine("fps:    " + reader.FrameRate);
            Console.WriteLine("codec:  " + reader.CodecName);
            // read 100 video frames out of it
            for (int i = 0; i < 100; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                // process the frame somehow
                // ...

                // dispose the frame when it is no longer required
                videoFrame.Dispose();
            }
            reader.Close();
        }
Example #37
0
        private void button2_Click(object sender, EventArgs e)
        {
            FileStream dosyamiz;
            StreamReader okuma;
            string yol = "C:\\manual_Jogging1.txt";

            dosyamiz = new FileStream(yol, FileMode.Open, FileAccess.Read);
            okuma = new StreamReader(dosyamiz);

            int n, a, b, c, d;
            int x1, x2, x3, x4;
            double xgec;

            System.Drawing.Graphics graphicsObj;

            graphicsObj = this.CreateGraphics();

            Pen myPen = new Pen(System.Drawing.Color.Red, 1);

            VideoFileReader reader = new VideoFileReader();
            IWMPMedia saniye = axWindowsMediaPlayer1.newMedia(ofVideoYukle.FileName);

            if (fbdFramePath.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("Klasör seçilmedi");
            }

            string str_FramePath = fbdFramePath.SelectedPath + @"\";
            reader.Open(ofVideoYukle.FileName);
            this.TotalFrame = (int)saniye.duration * reader.FrameRate;
            this.Videofps = reader.FrameRate;
            for (int i = 0; i < 307; i++)
            {

                textBox1.Text = okuma.ReadLine();
                textBox2.Text = textBox1.Text.Replace("		", "");

                n = Convert.ToInt32(textBox2.Text.Substring(0, 1));
                a = Convert.ToInt32(textBox2.Text.Substring(1, 3));
                b = Convert.ToInt32(textBox2.Text.Substring(4, 3));
                c = Convert.ToInt32(textBox2.Text.Substring(7, 2));
                d = Convert.ToInt32(textBox2.Text.Substring(9, 2));

                if (i > 9)
                {
                    if (i == 48 || i == 49 || i == 50 || i == 51 || i == 52 || i == 53 || i == 54 || i == 55)
                    {
                        n = Convert.ToInt32(textBox2.Text.Substring(0, 2));
                        a = Convert.ToInt32(textBox2.Text.Substring(2, 2));
                        b = Convert.ToInt32(textBox2.Text.Substring(4, 3));
                        c = Convert.ToInt32(textBox2.Text.Substring(7, 2));
                        d = Convert.ToInt32(textBox2.Text.Substring(9, 2));
                    }

                    else
                    {
                        n = Convert.ToInt32(textBox2.Text.Substring(0, 2));
                        a = Convert.ToInt32(textBox2.Text.Substring(2, 3));
                        b = Convert.ToInt32(textBox2.Text.Substring(5, 3));
                        c = Convert.ToInt32(textBox2.Text.Substring(8, 2));
                        d = Convert.ToInt32(textBox2.Text.Substring(10, 2));
                    }

                }

                if (i > 99)
                {
                    n = Convert.ToInt32(textBox2.Text.Substring(0, 3));
                    a = Convert.ToInt32(textBox2.Text.Substring(3, 3));
                    b = Convert.ToInt32(textBox2.Text.Substring(6, 3));
                    c = Convert.ToInt32(textBox2.Text.Substring(9, 2));
                    d = Convert.ToInt32(textBox2.Text.Substring(11, 2));

                }

                x1 = a - c;
                x2 = b - ((3 * d) / 2);
                x3 = 2 * c;
                xgec = (Math.Sqrt(Math.Pow(c, 2) + Math.Pow(d, 2))) * 3;
                x4 = Convert.ToInt32(xgec);

                Rectangle myRectangle = new Rectangle(x1, x2, x3, x4);
                Bitmap videoFrame = reader.ReadVideoFrame();

                using (Graphics grafik = Graphics.FromImage(videoFrame as Image))
                {

                    grafik.DrawEllipse(myPen, myRectangle);

                }

                videoFrame.Save(str_FramePath + "Image" + i + ".jpg");
                videoFrame.Dispose();
            }

            reader.Close();
            reader.Dispose();
            MessageBox.Show("Video Frame lere ayrildi");
            button4.Enabled = true;
        }
Example #38
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            btnTest.Enabled = false;
            string res = "OK";
            try
            {
                Program.FfmpegMutex.WaitOne();
                string source = cmbFile.Text;
                using (var vfr = new VideoFileReader())
                {

                    int i = source.IndexOf("://", StringComparison.Ordinal);
                    if (i > -1)
                    {
                        source = source.Substring(0, i).ToLower() + source.Substring(i);
                    }

                    vfr.Timeout = CameraControl.Camobject.settings.timeout;
                    vfr.AnalyzeDuration = (int) numAnalyseDuration.Value;
                    vfr.Cookies = CameraControl.Camobject.settings.cookies;
                    vfr.UserAgent = CameraControl.Camobject.settings.useragent;
                    vfr.Headers = CameraControl.Camobject.settings.headers;
                    vfr.RTSPMode = ddlRTSP.SelectedIndex;
                    vfr.Flags = -1;
                    vfr.NoBuffer = true;
                    vfr.Open(source);
                    var f = vfr.ReadFrame();
                    if (f == null)
                        throw new Exception("Could not read from url");
                }

            }
            catch (Exception ex)
            {
                res = ex.Message;
            }
            finally
            {
                try
                {
                    Program.FfmpegMutex.ReleaseMutex();
                }
                catch (ObjectDisposedException)
                {
                    //can happen on shutdown
                }
            }

            MessageBox.Show(res);
            btnTest.Enabled = true;
        }
Example #39
0
        private void btn_encode_Click(object sender, EventArgs e)
        {
            if (oform != null && File.Exists(oform.FileName)) { //has a filestream been opened?
                hScrollBar1.Enabled = false;
                checkBox1.Enabled = false;
                btn_encode.Enabled = false;
                // create instance of video reader
                VideoFileReader reader = new VideoFileReader();
                VideoFileWriter writer = new VideoFileWriter();
                reader.Open(oform.FileName);
                if (checkBox1.Checked) { //Is the user requesting a AVI?
                    writer.Open(apath + "output.wmv", 320, 200, reader.FrameRate, VideoCodec.WMV2);
                }
                // print some of its attributes
                logbox.Text += "Width: " + reader.Width + "px" + Environment.NewLine;
                logbox.Text += ("Height: " + reader.Height + "px" + Environment.NewLine);
                logbox.Text += ("Fps: " + reader.FrameRate + "fps"+ Environment.NewLine);
                logbox.Text += ("Codec: " + reader.CodecName + Environment.NewLine);
                logbox.Text += ("Frames: " + reader.FrameCount + Environment.NewLine);
                //start encoding classes
                TMVVideo tvid = new TMVVideo();
                TMVEncoder tmv = new TMVEncoder();
                //tmvframe.Threshold = hScrollBar1.Value;
                Bitmap videoFrame = new Bitmap(320,200);
                logbox.Text += "Conversion started @ " + DateTime.Now.ToString();
                string logtxt = logbox.Text;
                logbox.Text += "Current Frame: 0";
                TMVFont renderfont = new TMVFont(apath + "font.bin");
                TMVFrame tframe;
                for (int i = 0; i < reader.FrameCount; i++) {
                    videoFrame = resize_image(reader.ReadVideoFrame());
                    tframe = tmv.encode(videoFrame);
                    tvid.addFrame(tframe);
                    obox.Image = tframe.renderFrame(renderfont);
                    pbar.Value = (int)((i * 100) / (reader.FrameCount-1));
                    logbox.Text = logtxt + Environment.NewLine + "Current Frame: " + i + "/" + (reader.FrameCount-1);
                    if (checkBox1.Checked) { //Is the user requesting a AVI?
                        writer.WriteVideoFrame((Bitmap)obox.Image);
                    }
                    if (closing)
                    {
                        return;
                    }
                    fbox.Image = videoFrame;
                    Application.DoEvents();
                }
                logbox.Text += Environment.NewLine + "All frames converted, attempting to interleave audio.";
                if (File.Exists(apath + "temp.wav")) { //remove any previous streams
                    File.Delete(apath + "temp.wav");
                }
                AviManager aviManager = new AviManager(oform.FileName, true);
                try { //try to read the stream
                    AudioStream waveStream = aviManager.GetWaveStream();
                    logbox.Text += Environment.NewLine + "Audio stream found:";
                    logbox.Text += Environment.NewLine + "Sample Rate: " + waveStream.CountSamplesPerSecond.ToString();
                    logbox.Text += Environment.NewLine + "Bits:" + waveStream.CountBitsPerSample.ToString();
                    logbox.Text += Environment.NewLine + "Number of Channels: " + waveStream.CountChannels.ToString();
                    File.Delete(apath + "temp.wav");
                    waveStream.ExportStream(apath+"temp.wav");
                    waveStream.Close();
                    aviManager.Close();

                    byte[] audio_data = readWav(apath + "temp.wav");

                    if (reader.FrameRate > 99) { //sometimes frame rate is stored fixed point CRUDE
                        tvid.setFPS((decimal)(reader.FrameRate / 10.0));
                        tvid.loadAudio(audio_data);
                        tvid.save();
                    }
                    else {
                        tvid.setFPS(reader.FrameRate);
                        tvid.loadAudio(audio_data);
                        tvid.save();
                    }
                }
                catch { //error somewhere here, continue silent.
                    logbox.Text += Environment.NewLine+"Error, source video does not have WAV audio, video will be silent.";

                    if (reader.FrameRate > 99) { //sometimes frame rate is stored fixed point CRUDE
                        tvid.setFPS((decimal)(reader.FrameRate / 10.0));
                        tvid.loadAudio(new Byte[reader.FrameCount]);
                        tvid.save();
                    }
                    else {
                        tvid.setFPS(reader.FrameRate);
                        tvid.loadAudio(new Byte[reader.FrameCount]);
                        tvid.save();
                    }
                }

                logbox.Text += Environment.NewLine + "Conversion finished @ " + DateTime.Now.ToString();
                writer.Close();
                reader.Close();
                hScrollBar1.Enabled = true;
                checkBox1.Enabled = true;
                btn_encode.Enabled = true;

            }
            else {
                logbox.Text += Environment.NewLine + "Error: Select a file (Using File -> Open) before attempting to encode.";
            }
        }
Example #40
0
        private void FfmpegListener()
        {
            _reasonToStop = ReasonToFinishPlaying.StoppedByUser;
            _vfr = null;
            bool open = false;
            string errmsg = "";
            _realtime = !IsFileSource;
            try
            {
                Program.FFMPEGMutex.WaitOne();
                _vfr = new VideoFileReader();

                //ensure http/https is lower case for string compare in ffmpeg library
                int i = _source.IndexOf("://", StringComparison.Ordinal);
                if (i > -1)
                {
                    _source = _source.Substring(0, i).ToLower() + _source.Substring(i);
                }
                _vfr.Timeout = Timeout;
                _vfr.AnalyzeDuration = AnalyzeDuration;
                _vfr.Cookies = Cookies;
                _vfr.UserAgent = UserAgent;
                _vfr.Headers = Headers;
                _vfr.Flags = -1;
                _vfr.NoBuffer = _realtime;
                _vfr.RTSPMode = RTSPMode;
                _vfr.Open(_source);
                open = true;
            }
            catch (Exception ex)
            {
                MainForm.LogErrorToFile(ex.Message+": "+_source);
            }
            finally
            {
                try
                {
                    Program.FFMPEGMutex.ReleaseMutex();
                }
                catch (ObjectDisposedException)
                {
                    //can happen on shutdown
                }
            }

            if (_vfr == null || !_vfr.IsOpen || !open)
            {
                ShutDown("Could not open stream" + ": " + _source);
                return;
            }
            if (_stopEvent.WaitOne(0))
            {
                ShutDown("");
                return;
            }

            bool hasaudio = false;

            if (_vfr.Channels > 0)
            {
                hasaudio = true;
                RecordingFormat = new WaveFormat(_vfr.SampleRate, 16, _vfr.Channels);
                _waveProvider = new BufferedWaveProvider(RecordingFormat) {DiscardOnBufferOverflow = true, BufferDuration = TimeSpan.FromMilliseconds(500)};

                SampleChannel = new SampleChannel(_waveProvider);
                SampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter;

                if (HasAudioStream != null)
                {
                    HasAudioStream(this, EventArgs.Empty);
                }
            }
            HasAudioStream = null;

            Duration = _vfr.Duration;

            if (!_realtime)
            {
                _tOutput = new Thread(FrameEmitter) {Name="ffmpeg frame emitter"};
                _tOutput.Start();
            }
            else
            {
                _tOutput = null;
            }

            _videoframes = new List<DelayedFrame>();
            _audioframes = new List<DelayedAudio>();

            double maxdrift = 0, firstmaxdrift = 0;
            const int analyseInterval = 10;
            DateTime dtAnalyse = DateTime.MinValue;
            //LastFrame = Helper.Now;

            if (_initialSeek>-1)
                _vfr.Seek(_initialSeek);
            try
            {
                while (!_stopEvent.WaitOne(5) && !MainForm.Reallyclose && NewFrame!=null)
                {
                    _bufferFull = !_realtime && (_videoframes.Count > MAXBuffer || _audioframes.Count > MAXBuffer);
                    if (!_paused && !_bufferFull)
                    {
                        if (DecodeFrame(analyseInterval, hasaudio, ref firstmaxdrift, ref maxdrift, ref dtAnalyse)) break;
                        if (_realtime && !_stopEvent.WaitOne(0))
                        {
                            if (_videoframes.Count > 0)
                            {
                                DelayedFrame q = _videoframes[0];
                                if (q.B != null)
                                {
                                    if (NewFrame != null)
                                    {
                                        NewFrame(this, new NewFrameEventArgs(q.B));
                                    }
                                    q.B.Dispose();
                                }
                                _videoframes.RemoveAt(0);
                            }
                            if (_audioframes.Count > 0)
                            {
                                DelayedAudio q = _audioframes[0];

                                if (q.A != null)
                                {
                                    ProcessAudio(q.A);
                                }
                                _audioframes.RemoveAt(0);
                            }
                        }
                    }
                }

            }
            catch (Exception e)
            {
                MainForm.LogExceptionToFile(e);
                errmsg = e.Message;
            }

            if (SampleChannel != null)
            {
                SampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter;
                SampleChannel = null;
            }

            if (_waveProvider != null)
            {
                if (_waveProvider.BufferedBytes > 0)
                    _waveProvider.ClearBuffer();
            }

            if (_tOutput != null)
            {
                try
                {
                    if (!_tOutput.Join(TimeSpan.Zero))
                        _tOutput.Join();
                }
                catch {}
            }

            ShutDown(errmsg);
        }
Example #41
0
        private void Run_Click(object sender, EventArgs e)
        {
            VideoFileReader reader = new VideoFileReader();
            // open video file
            reader.Open(textBox1.Text);
            // check some of its attributes
            //Console.WriteLine("width:  " + reader.Width);
            //Console.WriteLine("height: " + reader.Height);
            //Console.WriteLine("fps:    " + reader.FrameRate);
            //Console.WriteLine("codec:  " + reader.CodecName);
            int[][] frameRGB = new int[reader.FrameCount][];
            // read 100 video frames out of it
            for (int i = 0; i < reader.FrameCount; i++)
            {
                //int disRed = 0;
                //int disGreen = 0;
                //int disBlue = 0;
                Bitmap videoFrame = reader.ReadVideoFrame();
                // process the frame somehow
                ImageStatistics rgbStatistics = new ImageStatistics(videoFrame);
                int[] redValues = rgbStatistics.Red.Values;
                int[] greenValues = rgbStatistics.Green.Values;
                int[] blueValues = rgbStatistics.Blue.Values;

                int[] his = new int[256];
                for (int j = 0; j < 256; j++)
                {
                    his[j] = (redValues[j] + greenValues[j] + blueValues[j]) / 3;

                }
                frameRGB[i] = his;

                //Bitmap videoFrame2 = reader.ReadVideoFrame();
                //// process the frame somehow
                //ImageStatistics rgbStatistics2 = new ImageStatistics(videoFrame2);
                //int[] redValues2 = rgbStatistics2.Red.Values;
                //int[] greenValues2 = rgbStatistics2.Green.Values;
                //int[] blueValues2 = rgbStatistics2.Blue.Values;

                //for (int j = 0; j < 256; j++)
                //{
                //    disRed = disRed + Math.Abs(redValues[j] - redValues2[j]);
                //    disGreen = disGreen + Math.Abs(greenValues[j] - greenValues2[j]);
                //    disBlue = disBlue + Math.Abs(blueValues[j] - blueValues2[j]);

                //}
                //int sumdis = disRed + disGreen + disBlue;
                //สร้างตัวแปรเก็บr+G+B เอาไว้หาค่าthredshold;กำหนดเอง
                // dispose the frame when it is no longer required
                videoFrame.Dispose();
            }

            reader.Close();
            Sdis = new int[frameRGB.Length - 1];
            for (int g = 0; g < frameRGB.Length - 1; g++)
            {
                int dis = 0;
                for (int k = 0; k < 256; k++)
                {

                    dis += Math.Abs(frameRGB[g][k] - frameRGB[g + 1][k]);
                }
                Sdis[g] = dis;
            }

            this.chart1.Titles.Add("Distance");
            Series series = this.chart1.Series.Add("Distance");
            for (int ss = 0; ss < frameRGB.Length - 1; ss++)
            {

                series.Points.AddXY(ss, Sdis[ss]);
            }
        }
        /// <summary>
        /// Reason : To read video and read frames from it
        /// </summary>
        public void VideoProcessing()
        {
            VideoFileReader reader = new VideoFileReader();
            string path = @"C:\Users\Cuelogic\Desktop\sample images\videos\drop.avi";
            reader.Open(path);

            for (int i = 0; i < 100; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                videoFrame.Dispose();
            }
            reader.Close();
        }
Example #43
0
        private void keyFrame()
        {
            VideoFileReader reader = new VideoFileReader();
            reader.Open(textBox1.Text);
            int Fcon = int.Parse(reader.FrameCount.ToString());
            int Fcount = Fcon / 2;
            for (int i = 0; i < reader.FrameCount; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                if (i == Fcount)
                {
                    hisVec(videoFrame);
                    break;
                }

            }

            reader.Close();
        }
Example #44
0
 public ReadVideoFile(string filePath)
 {
     VideoFile = new VideoFileReader();
     VideoFile.Open(filePath);
 }
 // Function to process the file
 public int doProcess(ProgressStorage progressStorage)
 {
     currentFrame = 0;
     reader = new VideoFileReader();
     try
     {
         reader.Open(file);
     }
     catch
     {
         return 1;
     }
     int frameCount = (int)reader.FrameCount;
     tracker = new Tracker(movementWindow);
     int nrofiterations = frameCount / 200;
     int i = 0;
     int nrofframes = 0;
     while (i < nrofiterations)
     {
         nrofframes = 200;
         loadinPart(nrofframes, area);
         if(i == 0) // store first frame as background frame
         {
             backgroundFrame = imageStack[0].Clone(new Rectangle(0, 0, imageStack[0].Width, imageStack[0].Height), imageStack[0].PixelFormat);
         }
         processFilePart();
         progressStorage.incrementProgress(currentFrame);
         i++;
     }
     nrofframes = frameCount - currentFrame;
     loadinPart(nrofframes, area);
     if (nrofiterations == 0) // store first frame as background frame if nrofiterations is 0
     {
         backgroundFrame = imageStack[0].Clone(new Rectangle(0, 0, imageStack[0].Width, imageStack[0].Height), imageStack[0].PixelFormat);
     }
     processFilePart();
     progressStorage.incrementProgress(currentFrame);
     tracker.closeList(currentFrame);
     reader.Close(); // close the file
     return 0;
 }
Example #46
0
        private void saveshot()
        {
            string str = Url;
            string[] sAry = str.Split('.');
            Url2 = sAry[0];

            VideoFileReader reader = new VideoFileReader();
            reader.Open(textBox1.Text);
            int co = 0;
            int end = int.Parse(reader.FrameCount.ToString());

            int countFrameCut = 0;
            VideoFileWriter writerShort = new VideoFileWriter();
            name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi";
            videoname = Url2 + "_" + countFrameCut + ".avi";
            writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);
            for (int i = 0; i < end; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                writerShort.WriteVideoFrame(videoFrame);
                videoFrame.Dispose();
                if (i == Savei[countFrameCut]) {
                    // cut short
                    writerShort.Close();

                    keyFrame();

                    if (countCutFrame != countFrameCut)
                    {
                        name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi";
                        videoname = Url2 + "_" + countFrameCut + ".avi";
                        writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);
                    }
                    countFrameCut++;
                }
            }
            writerShort.Close();
            reader.Close();

            /*
            for (int i = 0; i < Savei.Length; i++)
            {

                if (Savei[i] == 0)
                {
                    if (co == 0)
                    {
                        Savei[i] = end;
                        co = 1;
                    }
                    else
                    {

                        break;
                    }
                }

                VideoFileWriter writer = new VideoFileWriter();

                try
                {

                    name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(i) + ".avi";
                    videoname = Url2 + "_" + i + ".avi";
                    writer.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);

                    for (int j = 0; j < end; j++)
                    {
                        if (Savei[i] == j)
                        {
                            writer.Close();
                            break;
                        }
                        Bitmap videoFrame = reader.ReadVideoFrame();

                        writer.WriteVideoFrame(videoFrame);
                        videoFrame.Dispose();
                    }

                }
                catch (Exception exception)
                {
                    writer.Close();
                }

                if (i == 0)
                {
                    end = end - Savei[i];
                }
                else
                {
                    end = end - Math.Abs(Savei[i] - Savei[i - 1]);
                }

                keyFrame();

                //string constr = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
                //SqlConnection con = new SqlConnection(constr);
                //con.Open();

                //SqlCommand cmd = new SqlCommand("INSERT into CollectionShot (No,VideoName,PathVideoName,KeyFrame,HistrogrameVecter) " +
                //       " VALUES ( (Select count(*) from CollectionShot ),'" + videoname + "','" + name + "' , '" + keyF + "','" + Vechist + "')", con);
                //cmd.ExecuteNonQuery();
                //con.Close();

            }
            reader.Close();
            */
        }
Example #47
0
        private void dgOpenFile_FileOk(object sender, CancelEventArgs e)
        {
            String path = dgOpenFile.FileName;
            this.tbPath.Text = path;
            try
            {
                _reader = new VideoFileReader();
                _reader.Open(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                _reader = null;
            }

            tbInfo.Text = String.Empty;

            if (_reader != null)
            {
                String info = String.Format("Video info:\r\n\r\n Width-{0}\r\n Height-{1}\r\n FrameCount-{2}\r\n FrameRate-{3}\r\n Codec-{4}",
                    _reader.Width,_reader.Height,
                    _reader.FrameCount, _reader.FrameRate, _reader.CodecName);
                tbInfo.Text = info;
            }

            ShowNextFrame();
        }
Example #48
0
        private void keyFrame()
        {
            VideoFileReader readerShort= new VideoFileReader();
            readerShort.Open(name);

            // set many frame
            int Fcon = int.Parse(readerShort.FrameCount.ToString());
            // set frame/2
            int Fcount = Fcon / 2;

            for (int i = 0; i < readerShort.FrameCount; i++)
            {
                Bitmap videoFrame = readerShort.ReadVideoFrame();
                if (i == Fcount)
                {
                    hisVec(videoFrame);
                    keyF = ("..\\..\\..\\Keyframe\\" + Url2 + "_" + i + ".jpeg");
                    videoFrame.Save(keyF, ImageFormat.Jpeg);
                    break;
                }
                videoFrame.Dispose();
            }
            // close short video
            readerShort.Close();
        }
Example #49
0
        private void FfmpegListener()
        {
            _reasonToStop = ReasonToFinishPlaying.StoppedByUser;
            _vfr = null;
            bool open = false;
            string errmsg = "";
            _eventing = null;
            _stopping = false;
            try
            {
                Program.FfmpegMutex.WaitOne();
                _vfr = new VideoFileReader();

                //ensure http/https is lower case for string compare in ffmpeg library
                int i = _source.IndexOf("://", StringComparison.Ordinal);
                if (i > -1)
                {
                    _source = _source.Substring(0, i).ToLower() + _source.Substring(i);
                }
                _vfr.Timeout = Timeout;
                _vfr.AnalyzeDuration = AnalyzeDuration;
                _vfr.Cookies = Cookies;
                _vfr.UserAgent = UserAgent;
                _vfr.Headers = Headers;
                _vfr.Flags = -1;
                _vfr.NoBuffer = true;
                _vfr.RTSPMode = RTSPMode;
                _vfr.Open(_source);
                open = true;
            }
            catch (Exception ex)
            {
                Logger.LogExceptionToFile(ex, "FFMPEG");
            }
            finally
            {
                try
                {
                    Program.FfmpegMutex.ReleaseMutex();
                }
                catch (ObjectDisposedException)
                {
                    //can happen on shutdown
                }
            }

            if (_vfr == null || !_vfr.IsOpen || !open)
            {
                ShutDown("Could not open stream" + ": " + _source);
                return;
            }

            bool hasaudio = false;

            if (_vfr.Channels > 0)
            {
                hasaudio = true;
                RecordingFormat = new WaveFormat(_vfr.SampleRate, 16, _vfr.Channels);
                _waveProvider = new BufferedWaveProvider(RecordingFormat) { DiscardOnBufferOverflow = true, BufferDuration = TimeSpan.FromMilliseconds(500) };
                SampleChannel = new SampleChannel(_waveProvider);
                SampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter;
            }

            Duration = _vfr.Duration;

            _videoQueue = new ConcurrentQueue<Bitmap>();
            _audioQueue = new ConcurrentQueue<byte[]>();
            _eventing = new Thread(EventManager) { Name = "ffmpeg eventing", IsBackground = true };
            _eventing.Start();

            try
            {
                while (!_stopEvent.WaitOne(5) && !MainForm.ShuttingDown)
                {
                    var nf = NewFrame;
                    if (nf == null)
                        break;

                    object frame = _vfr.ReadFrame();
                    switch (_vfr.LastFrameType)
                    {
                        case 0:
                            //null packet
                            if ((DateTime.UtcNow - LastFrame).TotalMilliseconds > Timeout)
                                throw new TimeoutException("Timeout reading from video stream");
                            break;
                        case 1:
                            LastFrame = DateTime.UtcNow;
                            if (hasaudio)
                            {
                                var data = frame as byte[];
                                if (data?.Length > 0)
                                {
                                    ProcessAudio(data);
                                }
                            }
                            break;
                        case 2:
                            LastFrame = DateTime.UtcNow;

                            var bmp = frame as Bitmap;
                            if (bmp != null)
                            {
                                if (_videoQueue.Count<20)
                                    _videoQueue.Enqueue(bmp);
                            }
                            break;
                    }
                }

            }
            catch (Exception e)
            {
                Logger.LogExceptionToFile(e, "FFMPEG");
                errmsg = e.Message;
            }

            _stopEvent.Set();
            _eventing.Join();

            if (SampleChannel != null)
            {
                SampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter;
                SampleChannel = null;
            }

            if (_waveProvider?.BufferedBytes > 0)
                _waveProvider?.ClearBuffer();

            ShutDown(errmsg);
        }
        private void prepareForPlay(string path)
        {
            if ((path != null) || (path.Length != 0))
            {
                processMovieThread = new Thread(new ThreadStart(processMovie));
                processMovieThread.Name = Properties.Resources.PROCESS_MOVIE_THREAD_TITLE;

                processor = new VideoProcessor();
                videoReader = new VideoFileReader();

                videoReader.Open(path);
            }
        }