Beispiel #1
0
 /// <summary>Add a wave audio stream from another file to this file</summary>
 /// <param name="waveFileName">Name of the wave file to add</param>
 /// <param name="startAtFrameIndex">Index of the video frame at which the sound is going to start</param>
 public void AddAudioStream(String waveFileName, int startAtFrameIndex)
 {
     AviManager audioManager = new AviManager(waveFileName, true);
     AudioStream newStream = audioManager.GetWaveStream();
     AddAudioStream(newStream, startAtFrameIndex);
     audioManager.Close();
 }
Beispiel #2
0
        public VideoFrames(string fileLocation)
        {
            if (fileLocation == null)
            {
                _mode = Mode.None;
                return;
            }

            string lower = fileLocation.ToLower();
            fileloc = fileLocation;
            if (lower.EndsWith(".avi"))
            {
                _aviManager = new AviManager(fileLocation, true);
                _aviStream = _aviManager.GetVideoStream();
                _aviStream.GetFrameOpen();
                _mode = Mode.Video;
            }
            else if (lower.EndsWith(".png"))
            {
                _singleFrame = new System.Drawing.Bitmap(fileLocation);
                _mode = Mode.SingleFrame;
            }
            else
            {
                _mode = Mode.None;
            }
        }
        /// <summary>Copy all frames into a new file</summary>
        /// <param name="fileName">Name of the new file</param>
        /// <param name="recompress">true: Compress the new stream</param>
        /// <param name="newStream2"></param>
        /// <returns>AviManager for the new file</returns>
        /// <remarks>Use this method if you want to append frames to an existing, compressed stream</remarks>
        public AviManager DecompressToNewFile(String fileName, bool recompress, out VideoStream newStream2)
        {
            AviManager newFile = new AviManager(fileName, false);

            GetFrameOpen();

            Bitmap      frame     = GetBitmap(0);
            VideoStream newStream = newFile.AddVideoStream(recompress, frameRate, frame);

            frame.Dispose();

            for (int n = 1; n < countFrames; n++)
            {
                frame = GetBitmap(n);
                newStream.AddFrame(frame);
                frame.Dispose();
            }
            //TEST

            /*Bitmap test = new Bitmap("..\\..\\testdata\\test.bmp");
             * newStream.AddFrame(frame);
             * test.Dispose();*/

            GetFrameClose();

            newStream2 = newStream;
            return(newFile);
        }
Beispiel #4
0
        public ScreenCapture(int fps, Screen screen)
        {
            string x = System.DateTime.Now.ToString();
            x = x.Replace(@"/", ".");
            x = x.Replace(@":", ".");

            strPath = @"/Videos/";

            intTop = screen.Bounds.X;
            intleft = screen.Bounds.Y;
            intWidth = screen.Bounds.Width;
            intHeight = screen.Bounds.Height;
            size = screen.Bounds.Size;

            capture();

            aviMan = new AviManager(x + ".avi", false);
            videoStream = aviMan.AddVideoStream(true, 30, printscreen);
            printscreen.Dispose();

            Console.WriteLine(strPath);
            System.IO.Directory.CreateDirectory(strPath);

            System.Timers.Timer aTimer;
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 1000 / fps;
            aTimer.Enabled = true;
        }
Beispiel #5
0
 private void AddFile()
 {
     if (System.IO.File.Exists(uiAviFileNameTextBox.Text))
     {
         try
         {
             var aviManager = new AviManager(uiAviFileNameTextBox.Text, true);
             VideoStream aviStream = aviManager.GetVideoStream();
             aviStream.GetFrameOpen();
             Bitmap bmp = aviStream.GetBitmap(aviStream.CountFrames/2);
             var videoStreamControl = new VideoStreamBrowseControl {Dock = DockStyle.Top};
             videoStreamControl.SetFileName(GetCurrentFileName());
             videoStreamControl.SetFrame(GetResizedBitmap(bmp, 50, 50));
             videoStreamControl.VideoStream = aviStream;
             videoStreamControl.SelectVideoStream += SelectVideoStreamControl;
             uiVideoListPanel.Controls.Add(videoStreamControl);
             _selectedVideoStreamBrowseControl = videoStreamControl;
             foreach (VideoStreamBrowseControl browseControl in uiVideoListPanel.Controls.OfType<VideoStreamBrowseControl>())
             {
                 (browseControl).uiMainPanel.BackColor = Color.Lavender;
             }
             videoStreamControl.uiMainPanel.BackColor = Color.Aquamarine;
             aviManager.Close();
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.ToString());
         }
     }
 }
        private void btnAppend_Click(object sender, System.EventArgs e)
        {
            //open file
            Bitmap bmp = (Bitmap)Image.FromFile(txtFileNames.Lines[0]);
            AviManager aviManager = new AviManager(txtAviFileName.Text, true);
            VideoStream aviStream = aviManager.GetVideoStream();

            //streams cannot be edited - copy to a new file
            VideoStream newStream;
            AviManager newManager = aviStream.DecompressToNewFile(@"..\..\testdata\temp.avi", true, out newStream);
            aviStream = newStream; //newManager.GetOpenStream(0);

            //add images
            Bitmap bitmap;
            for (int n = 0; n < txtFileNames.Lines.Length; n++) {
                if (txtFileNames.Lines[n].Trim().Length > 0) {
                    bitmap = (Bitmap)Bitmap.FromFile(txtFileNames.Lines[n]);
                    aviStream.AddFrame(bitmap);
                    bitmap.Dispose();
                }
            }

            //close old file
            aviManager.Close();
            //save and close new file
            newManager.Close();

            //delete old file, replace with new file
            System.IO.File.Delete(txtAviFileName.Text);
            System.IO.File.Move(@"..\..\testdata\temp.avi", txtAviFileName.Text);
        }
Beispiel #7
0
        /// <summary>Add a wave audio stream from another file to this file</summary>
        /// <param name="waveFileName">Name of the wave file to add</param>
        public void AddAudioStream(String waveFileName)
        {
            AviManager  audioManager = new AviManager(waveFileName, true);
            AudioStream newStream    = audioManager.GetWaveStream();

            AddAudioStream(newStream);
            audioManager.Close();
        }
Beispiel #8
0
        /// <summary>Add a wave audio stream from another file to this file</summary>
        /// <param name="waveFileName">Name of the wave file to add</param>
        /// <param name="startAtFrameIndex">Index of the video frame at which the sound is going to start</param>
        public void AddAudioStream(String waveFileName, int startAtFrameIndex)
        {
            AviManager  audioManager = new AviManager(waveFileName, true);
            AudioStream newStream    = audioManager.GetWaveStream();

            AddAudioStream(newStream, startAtFrameIndex);
            audioManager.Close();
        }
Beispiel #9
0
        /// <summary>Copy a piece of video and wave sound int a new file</summary>
        /// <param name="newFileName">File name</param>
        /// <param name="startAtSecond">Start copying at second x</param>
        /// <param name="stopAtSecond">Stop copying at second y</param>
        /// <returns>AviManager for the new video</returns>
        public AviManager CopyTo(String newFileName, float startAtSecond, float stopAtSecond)
        {
            AviManager newFile = new AviManager(newFileName, false);

            try {
                //copy video stream

                VideoStream videoStream = GetVideoStream();

                int startFrameIndex = (int)(videoStream.FrameRate * startAtSecond);
                int stopFrameIndex  = (int)(videoStream.FrameRate * stopAtSecond);

                videoStream.GetFrameOpen();
                Bitmap      bmp       = videoStream.GetBitmap(startFrameIndex);
                VideoStream newStream = newFile.AddVideoStream(false, videoStream.FrameRate, bmp);
                for (int n = startFrameIndex + 1; n <= stopFrameIndex; n++)
                {
                    bmp = videoStream.GetBitmap(n);
                    newStream.AddFrame(bmp);
                }
                videoStream.GetFrameClose();

                //copy audio stream

                AudioStream waveStream = GetWaveStream();

                Avi.AVISTREAMINFO streamInfo   = new Avi.AVISTREAMINFO();
                Avi.PCMWAVEFORMAT streamFormat = new Avi.PCMWAVEFORMAT();
                int    streamLength            = 0;
                IntPtr ptrRawData = waveStream.GetStreamData(
                    ref streamInfo,
                    ref streamFormat,
                    ref streamLength);

                int startByteIndex = (int)(startAtSecond * (float)(waveStream.CountSamplesPerSecond * streamFormat.nChannels * waveStream.CountBitsPerSample) / 8);
                int stopByteIndex  = (int)(stopAtSecond * (float)(waveStream.CountSamplesPerSecond * streamFormat.nChannels * waveStream.CountBitsPerSample) / 8);

                IntPtr ptrWavePart = new IntPtr(ptrRawData.ToInt32() + startByteIndex);

                byte[] rawData = new byte[stopByteIndex - startByteIndex];
                Marshal.Copy(ptrWavePart, rawData, 0, rawData.Length);
                Marshal.FreeHGlobal(ptrRawData);

                streamInfo.dwLength = rawData.Length;
                streamInfo.dwStart  = 0;

                IntPtr unmanagedRawData = Marshal.AllocHGlobal(rawData.Length);
                Marshal.Copy(rawData, 0, unmanagedRawData, rawData.Length);
                newFile.AddAudioStream(unmanagedRawData, streamInfo, streamFormat, rawData.Length);
                Marshal.FreeHGlobal(unmanagedRawData);
            } catch (Exception ex) {
                newFile.Close();
                throw ex;
            }

            return(newFile);
        }
Beispiel #10
0
    public void Generate(VideoMaker videoMaker)
    {
        aviManager = new AviFile.AviManager(fileName, false);
        Console.WriteLine("Video ID:" + this.Id + " with name: " + fileName);
        Console.WriteLine("Number of Sequences: " + this.Sequences.Length);
        int sequenceNumber = 1;

        foreach (var sequence in Sequences)
        {
            Console.WriteLine("Processing Video " + sequenceNumber.ToString() + " : " + sequence.Id);
            ++sequenceNumber;
        }
    }
Beispiel #11
0
         public CaptureThread(string saveLoc)
        {
            _saveLoc = saveLoc;
            _aviManager = new AviManager(saveLoc, false);

            _windowCapture = new WindowStreamCapture();

            _exitEvent = new AutoResetEvent(false);
            _pool = new BitmapPool();
            _running = false;
            UsePrintWindow = true;

             frame_num = 0;
        }
        // Aforge kütüphanesi ile bu şekilde yapılıyor.
        /*public void create_video_from_bitmaps(Bitmap[] BitmapStream,int Height,int Width)
        {
            // instantiate AVI writer, use WMV3 codec
            VideoFileWriter writer = new VideoFileWriter();
            // create new AVI file and open it
            writer.Open("C:\\yazlab\\processed_frames\\result.avi", Width, Height);
            // create frame image

            foreach(Bitmap Frame in BitmapStream)
            {
                writer.WriteVideoFrame(Frame);
            }
            writer.Close();

        }
        */
        public void create_video_from_bitmaps(Bitmap[] BitmapStream)
        {
            try{
                AviManager aviManager = new AviManager(@"C:\\yazlab\\processed_frames\\result.avi", false);
                //add a new video stream and one frame to the new file
                VideoStream aviStream = aviManager.AddVideoStream(true, 0.2, BitmapStream[0]);

                foreach (Bitmap Frame in BitmapStream) {
                    aviStream.AddFrame(Frame);
                }
                aviManager.Close();
            }catch(Exception Exp){

                System.Windows.Forms.MessageBox.Show(Exp.ToString(),"AviFileHatası");
            }
        }
Beispiel #13
0
        /// <summary>Copy all frames into a new file</summary>
        /// <param name="fileName">Name of the new file</param>
        /// <param name="recompress">true: Compress the new stream</param>
        /// <returns>AviManager for the new file</returns>
        /// <remarks>Use this method if you want to append frames to an existing, compressed stream</remarks>
        public AviManager DecompressToNewFile(String fileName, bool recompress, out VideoStream newStream2)
        {
            AviManager newFile = new AviManager(fileName, false);

            this.GetFrameOpen();
            Bitmap      frame     = this.GetBitmap(0);
            VideoStream newStream = newFile.AddVideoStream(recompress, this.frameRate, frame);

            frame.Dispose();
            for (int n = 1; n < this.countFrames; n++)
            {
                frame = this.GetBitmap(n);
                newStream.AddFrame(frame);
                frame.Dispose();
            }
            this.GetFrameClose();
            newStream2 = newStream;
            return(newFile);
        }
Beispiel #14
0
 private void flush()
 {
     Console.WriteLine("Writing avi.  {0} frames to process", parallelScreens.Count);
     AviManager aviManager = new AviManager(Path.ChangeExtension(Path.Combine(filePath, Guid.NewGuid().ToString()), "avi"), false);
     IScreenShot screenShot;
     parallelScreens.TryDequeue(out screenShot);
     VideoStream aviStream = aviManager.AddVideoStream(true, fps, screenShot.GetBitmap());
     IScreenShot[] screenShots = parallelScreens.ToArray();
     for (var i = 1; i < screenShots.Length; i++)
     {
         using (Bitmap frame = screenShots[i].GetBitmap())
         {
             aviStream.AddFrame(frame);
         }
         screenShots[i].Delete();
         Console.Write("{0}, ", i);
     }
     aviManager.Close();
 }
Beispiel #15
0
        private void btnAddFrame_Click(object sender, EventArgs e)
        {
            String tempFileName = System.IO.Path.GetTempFileName() + ".avi";
            AviManager tempFile = new AviManager(tempFileName, false);

            Bitmap bitmap = (Bitmap)Image.FromFile(txtNewFrameFileName.Lines[0].Trim());
            tempFile.AddVideoStream(false, 1, bitmap);
            VideoStream stream = tempFile.GetVideoStream();

            for (int n = 1; n < txtNewFrameFileName.Lines.Length; n++) {
                if (txtNewFrameFileName.Lines[n].Trim().Length > 0) {
                    stream.AddFrame((Bitmap)Image.FromFile(txtNewFrameFileName.Lines[n]));
                }
            }

            editableStream.Paste(stream, 0, (int)numPastePositionBitmap.Value, stream.CountFrames);

            tempFile.Close();
            try { File.Delete(tempFileName); } catch (IOException) { }
        }
 private void btnAddSound_Click(object sender, System.EventArgs e)
 {
     String fileName = GetFileName("Sounds (*.wav)|*.wav");
     if (fileName != null) {
         txtReportSound.Text = "Adding to sound.wav to " + txtAviFileName.Text + "...\r\n";
         AviManager aviManager = new AviManager(txtAviFileName.Text, true);
         try {
             int countFrames = aviManager.GetVideoStream().CountFrames;
             if (countFrames > numInsertWavePosition.Value) {
                 aviManager.AddAudioStream(fileName, (int)numInsertWavePosition.Value);
             } else {
                 MessageBox.Show(this, "Frame " + numInsertWavePosition.Value + " does not exists. The video stream contains frame from 0 to " + (countFrames - 1) + ".");
             }
         } catch (Exception ex) {
             MessageBox.Show(this, "The file does not accept the new wave audio stream.\r\n" + ex.ToString(), "Error");
         }
         aviManager.Close();
         txtReportSound.Text += "...finished.";
     }
 }
 private void openFile_Click(object sender, EventArgs e)
 {
     inputFileDlg.Filter = "Media Files|*.avi;|All files|*.*;";
     if (DialogResult.OK == inputFileDlg.ShowDialog())
     {
         fileNameText.Text = inputFileDlg.FileName;
         try
         {
             AviManager aviManager = new AviManager(fileNameText.Text, true);
             VideoStream stream = aviManager.GetVideoStream();
             startPointTracker.Maximum = stream.CountFrames;
             endPointTracker.Maximum = stream.CountFrames;
             ShowFrameTrackOne();
             ShowFrameTrackTwo();
         }
         catch(Exception ew)
         {
             MessageBox.Show("L�tfen avi formatinda bis dosya se�in");
         }
     }
 }
 private void CreateVideo(string fileName, FileInfo[] files, bool isCompressed)
 {
     try
     {
         var bmp = new Bitmap(1120, 480, PixelFormat.Format24bppRgb);
         var aviManager = new AviManager(fileName, false);
         var aviStream = aviManager.AddVideoStream(isCompressed, 25, bmp);
         foreach (var file in files)
         {
             bmp = (Bitmap)Bitmap.FromFile(file.FullName);
             aviStream.AddFrame(bmp);
             bmp.Dispose();
         }
         aviManager.Close();
     }
     catch (Exception e)
     {
         logger.Error(e);
         throw e;
     }
 }
        // constructor
        public AviWriter(List<frame> Frame, String filename)
        {
            Console.WriteLine("Frame.Count: {0}", Frame.Count);

            for (int i = 0; i < Frame.Count; i++)
            {
                del.Add((((double)Frame[i].delay) / 1000.00));
                string FileName  = Frame[i].src;
                Image img = Image.FromFile(FileName);
                Bitmap bitmap = new Bitmap(img, width, height);
                bitmaps.Add(bitmap);

                Console.WriteLine("Frame: {0}", i, " delay: {1}", ((double)Frame[i].delay / 1000.00), "src: {2}", Frame[i].src);
            }

            min = del.Min();
            AviManager aviManager = new AviManager(filename, false);
            VideoStream aviStream = aviManager.AddVideoStream(false, 2, bitmaps[0]);
            Console.WriteLine("min: {0}", min);     
     
            for(int i = 1; i < Frame.Count; i++)
            {

                aviStream.AddFrame(bitmaps[i]);
                Console.WriteLine("Frame added");
                
                for(double j = min; j <= del[i];)
                {
                    aviStream.AddFrame(bitmaps[i]);
                    j = j + min;

                    Console.WriteLine("j: {0}", j);
                }
            }

            aviManager.Close();
            del.Clear();
        }
Beispiel #20
0
        public static bool CheckForVideo(KernelManager kernelManager)
        {
            if (_frame == null)
                return false;
            var i = _frame.Value / StepsPerPoint;
            if (i >= Frames.Count - 1)
            {
                _frame = null;
                _aviManager.Close();
                RenderWindow.SetStatus("Finished video");
                return false;
            }
            RenderWindow.SetStatus("Rendering frame " + _frame.Value + " of " + (Frames.Count - 1) * StepsPerPoint);
            var d0 = i == 0 ? Frames[0] : Frames[i - 1];
            var d1 = Frames[i];
            var d2 = Frames[i + 1];
            var d3 = i == Frames.Count - 2 ? Frames[Frames.Count - 1] : Frames[i + 2];
            var t = (float)(_frame.Value % StepsPerPoint) / StepsPerPoint;
            var config = CameraConfig.CatmullRom(d0, d1, d2, d3, t);
            var bmp = kernelManager.GetScreenshot(config, 720, 2);

            if (_frame.Value % 256 == 0 || _aviManager == null)
            {
                if (_aviManager != null)
                    _aviManager.Close();
                _videoStream = null;
                _aviManager = new AviManager(Ext.UniqueFilename("video", "avi"), false);
            }
            if (_videoStream == null)
                _videoStream = _aviManager.AddVideoStream(false, 25, bmp);
            else
                _videoStream.AddFrame(bmp);

            _frame = _frame.Value + 1;

            return true;
        }
 public void makeAvi()
 {
     FrameRateForm dlg = new FrameRateForm();
     if (DialogResult.OK == dlg.ShowDialog())
     {
         int framelength = 0;
         SaveFileDialog saveAvi = new SaveFileDialog();
         Bitmap bmp = null;
         if (saveAvi.ShowDialog() == DialogResult.OK)
         {
             bmp = (Bitmap)Image.FromFile(pathBox.Items[0].ToString());
             AviManager manageAVIFile = new AviManager(saveAvi.FileName.ToString()+ ".avi", false);
             aviStream = manageAVIFile.AddVideoStream(true, dlg.Rate, bmp);
             Bitmap bitmap;
             for (framelength = 1; framelength < pathBox.Items.Count - 1; framelength++)
             {
                 bitmap = (Bitmap)Bitmap.FromFile(pathBox.Items[framelength].ToString());
                 aviStream.AddFrame(bitmap);
                 bitmap.Dispose();
             }
             manageAVIFile.Close();
         }
     }
 }
        public void CreateVideo(int iCount)
        {
            if (iCount == 0)
            {
                MessageBox.Show("This game has no moving!");
                return;
            }

            SaveFileDialog fdlg = new SaveFileDialog
            {
                DefaultExt = "AVI",
                Title = "Save As",
                Filter = "AVI(*.AVI)|.AVI",
                FilterIndex = 1,
                FileName = "Untitled",
                AddExtension = true,
            };
            bool? result = fdlg.ShowDialog();
            if (result.HasValue && result.Value)
            {
                var watch = Stopwatch.StartNew();
                DependencyObject parentObject = Window.GetWindow(this);
                MainWindow parent = parentObject as MainWindow;
                if (parent != null)
                {
                    parent.m_statusProgressBar.Visibility = System.Windows.Visibility.Visible;
                }

                m = new Model();
                for (int i = 0; i < iCount; i++)
                {
                    parent.m_moveViewer.listViewMoveList.SelectedIndex = i;
                    RenderWithoutFilename();
                    parent.m_statusProgressBar.Value = i;
                    Thread.Sleep(100);
                }
                System.Drawing.Bitmap bmp = Helper.BitmapHelper.GetBitmap(m.ImageCollection[0]);
                AviManager aviManager = new AviManager(fdlg.FileName, false);
                double frameRate = System.Math.Round((double)1 / this.Step, 1);
                VideoStream aviStream = aviManager.AddVideoStream(false, frameRate, bmp);
                for (int i = 0; i < m.ImageCollection.Count; i++ )
                {
                    BitmapSource bms = m.ImageCollection[i] as BitmapSource;
                    System.Drawing.Bitmap b = Helper.BitmapHelper.GetBitmap(bms);
                    aviStream.AddFrame(b);
                    b.Dispose();

                    parent.m_statusProgressBar.Value = i;
                    Thread.Sleep(100);
                }

                aviManager.Close();
                watch.Stop();
                var elapsedMs = watch.Elapsed.Seconds;
                parent.m_statusLabelCheck.Content = string.Format("Render Complete in: {0} s", elapsedMs);

                parent.m_statusProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
 /** Metoda care se foloseste de bibliotecile AviManager pentru a
  * crea un stream video dintr-o lista de imagini format bitmap.
  **/
 private void createMovie(String fileName, List<Bitmap> images)
 {
     AviManager aviManager = new AviManager(fileName, false);
     VideoStream videoStream = aviManager.AddVideoStream(false, 30, images.ElementAt(0));
     foreach (var image in images)
     {
         if (finalFrames.IndexOf(image) != 0)
         {
             videoStream.AddFrame(image);
         }
     }
     aviManager.Close();
 }
Beispiel #24
0
        private void doExporting(string tmpFilePath, DicomElement dicomElement, BackgroundWorker worker)
        {
            //create a new AVI file
            AviManager aviManager = new AviManager(tmpFilePath, false);
            //add a new video stream and one frame to the new file
            // todo mozda ce moci drugaciji konstruktor...
            Bitmap bitmap = dicomElement.GetBitmap(1);
            VideoStream aviStream = aviManager.AddVideoStream(createCompressedOptions(), Settings.Default.Fps, bitmap);
            bitmap.Dispose();
            worker.ReportProgress(1);

            for (int n = 2; n <= dicomElement.FrameCount; n++)
            {
                bitmap = dicomElement.GetBitmap(n);
                aviStream.AddFrame(bitmap);
                bitmap.Dispose();
                worker.ReportProgress(1);
            }

            aviManager.Close();
        }
 public void RenderBmps(int iCount)
 {
     SaveFileDialog fdlg = new SaveFileDialog
     {
         DefaultExt = "AVI",
         Title = "Save As",
         Filter = "AVI(*.AVI)|.AVI",
         FilterIndex = 1,
         FileName = "Untitled",
         AddExtension = true,
     };
     bool? result = fdlg.ShowDialog();
     if (result.HasValue && result.Value)
     {
         m = new Model();
         for (int i = 0; i < iCount; i++)
         {
             RaiseComment("Title " + i, "Content " + i);
             RenderWithFilename(@"..\..\testdata\img" + i + ".BMP");
         }
         System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(@"..\..\testdata\img0.BMP");
         AviManager aviManager = new AviManager(fdlg.FileName, false);
         double frameRate = System.Math.Round((double)1 / this.Step, 1);
         VideoStream aviStream = aviManager.AddVideoStream(false, frameRate, bmp);
         foreach (BitmapSource bms in m.ImageCollection)
         {
             System.Drawing.Bitmap b = Helper.BitmapHelper.GetBitmap(bms);
             aviStream.AddFrame(b);
             b.Dispose();
         }
         aviManager.Close();
         MessageBox.Show("Complete!");
     }
 }
Beispiel #26
0
        /// <summary>Copy all frames into a new file</summary>
        /// <param name="fileName">Name of the new file</param>
        /// <param name="recompress">true: Compress the new stream</param>
        /// <returns>AviManager for the new file</returns>
        /// <remarks>Use this method if you want to append frames to an existing, compressed stream</remarks>
        public AviManager DecompressToNewFile(String fileName, bool recompress, out VideoStream newStream2)
        {
            AviManager newFile = new AviManager(fileName, false);

            this.GetFrameOpen();

            Bitmap frame = GetBitmap(0);
            VideoStream newStream = newFile.AddVideoStream(recompress, frameRate, frame);
            frame.Dispose();

            for(int n=1; n<countFrames; n++){
                frame = GetBitmap(n);
                newStream.AddFrame(frame);
                frame.Dispose();
            }

            this.GetFrameClose();

            newStream2 = newStream;
            return newFile;
        }
Beispiel #27
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog oFD1 = new OpenFileDialog();
            oFD1.Multiselect = true;

            if (oFD1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                files = oFD1.SafeFileNames; //Save only the names
                paths = oFD1.FileNames; //Save the full paths
                for (int i = 0; i < files.Length; i++)
                {
                    //listBox1.Items.Add(files[i]); //Add songs to the listbox
                    ext = Path.GetExtension(oFD1.FileName);
                    if (ext == ".avi")
                    {
                        //Convert Avi to wav
                        AviManager aviManager = new AviManager(oFD1.FileName, true);
                        AudioStream audioStream = aviManager.GetWaveStream();
                        audioStream.ExportStream(oFD1.FileName + ".wav");
                        filepath = oFD1.FileName + ".wav";
                        aviManager.Close();
                        listBox1.Items.Add(files[i]); //Add songs to the listbox
                    }
                    else if (ext == ".wav")
                    {
                        filepath = oFD1.FileName;
                        listBox1.Items.Add(files[i]); //Add songs to the listbox
                    }
                }
            }

            NAudio.Wave.WaveChannel32 wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(filepath));
            WaveFileReader wavFile = new WaveFileReader(filepath);
            byte[] mainBuffer = new byte[wave.Length];

            float fileSize = (float)wavFile.Length / 1048576;
            if (fileSize < 2)
                window = 8;
            else if (fileSize > 2 && fileSize < 4)
                window = 16;
            else if (fileSize > 4 && fileSize < 8)
                window = 32;
            else if (fileSize > 8 && fileSize < 12)
                window = 128;
            else if (fileSize > 12 && fileSize < 20)
                window = 256;
            else if (fileSize > 20 && fileSize < 30)
                window = 512;
            else
                window = 2048;

            float[] fbuffer = new float[mainBuffer.Length / window];
            wave.Read(mainBuffer, 0, mainBuffer.Length);

            for (int i = 0; i < fbuffer.Length; i++)
            {
                fbuffer[i] = (BitConverter.ToSingle(mainBuffer, i * window));
            }

            double time = wave.TotalTime.TotalSeconds;
            GraphPane myPane1 = zedGraphControl2.GraphPane;
            PointPairList list1 = new PointPairList();
            PointPairList list2 = new PointPairList();
            for (int i = 0; i < fbuffer.Length; i++)
            {
                list1.Add(i, fbuffer[i]);
            }
            list2.Add(0, 0);
            list2.Add(time, 0);
            if (myCurve1 != null && myCurve2 != null)
            {
                myCurve1.Clear();
                myCurve2.Clear();
            }
            GraphPane myPane2 = zedGraphControl2.GraphPane;
            myPane2.Title.Text = "Audio Sound Wave";
            myPane2.XAxis.Title.Text = "Time, Seconds";
            myPane2.YAxis.Title.Text = "Sound Wave Graph";
            myCurve1 = myPane1.AddCurve(null, list1, System.Drawing.Color.Blue, SymbolType.None);
            myCurve1.IsX2Axis = true;
            myCurve2 = myPane1.AddCurve(null, list2, System.Drawing.Color.Black, SymbolType.None);
            myPane1.XAxis.Scale.MaxAuto = true;
            myPane1.XAxis.Scale.MinAuto = true;

            //Threshold Line
            double threshHoldY = -1.2;
            double threshHoldX = 1.2;
            LineObj threshHoldLine = new LineObj(System.Drawing.Color.Red, myPane2.XAxis.Scale.Min, threshHoldY, myPane2.XAxis.Scale.Max, threshHoldY);
            LineObj threshHoldLine2 = new LineObj(System.Drawing.Color.Red, myPane2.XAxis.Scale.Min, threshHoldX, myPane2.XAxis.Scale.Max, threshHoldX);
            myPane2.GraphObjList.Add(threshHoldLine);
            myPane2.GraphObjList.Add(threshHoldLine2);

            // Add a text box with instructions
            TextObj text = new TextObj(
                "Ratio Conversion: 1:100\nRed Lines: Threshold\nZoom: left mouse & drag\nContext Menu: right mouse",
                0.05f, 0.95f, CoordType.ChartFraction, AlignH.Left, AlignV.Bottom);
            text.FontSpec.StringAlignment = StringAlignment.Near;
            myPane2.GraphObjList.Add(text);

            // Show the x axis grid
            myPane2.XAxis.MajorGrid.IsVisible = true;
            myPane2.YAxis.MajorGrid.IsVisible = true;
            // Just manually control the X axis range so it scrolls continuously
            // instead of discrete step-sized jumps
            //myPane2.XAxis.Scale.Format = @"00:00:00";
            myPane2.XAxis.Scale.IsSkipCrossLabel = true;
            myPane2.XAxis.Scale.IsPreventLabelOverlap = true;
            myPane2.XAxis.Type = ZedGraph.AxisType.Linear;
            myPane2.XAxis.Scale.Min = 0;
            myPane2.XAxis.Scale.Max = 1.2;
            myPane2.AxisChange();

            // turn off the opposite tics so the Y tics don't show up on the Y2 axis
            myPane2.YAxis.MajorTic.IsOpposite = false;
            myPane2.YAxis.MinorTic.IsOpposite = false;
            // Don't display the Y zero line
            myPane2.YAxis.MajorGrid.IsZeroLine = false;
            // Align the Y axis labels so they are flush to the axis
            myPane2.YAxis.Scale.Align = AlignP.Inside;
            // Manually set the axis range
            myPane2.YAxis.Scale.Min = -1.5;
            myPane2.YAxis.Scale.Max = 1.5;

            zedGraphControl2.AxisChange();
            zedGraphControl2.Invalidate();
        }
        private void btnExtractPart_Click(object sender, EventArgs e)
        {
            AviManager aviManager = new AviManager(txtAviFileName.Text, true);
            VideoStream aviStream = aviManager.GetVideoStream();

            CopyForm dialog = new CopyForm(0, (int)Math.Floor(aviStream.CountFrames / aviStream.FrameRate));
            if (dialog.ShowDialog() == DialogResult.OK) {
                int startSecond = dialog.Start;
                int stopSecond = dialog.Stop;

                txtReportCopy.Text = "Cutting seconds from " + txtAviFileName.Text + " to video.avi...\r\n";
                AviManager newFile = aviManager.CopyTo("..\\..\\testdata\\video.avi", startSecond, stopSecond);
                newFile.Close();
                txtReportCopy.Text += "...finished.";
            }
            aviManager.Close();
        }
        /// <summary>
        /// Создание анимации из файла *.avi (при этом палитра если возможно берется из одноименного файла *.pal) (TODO: поддрежка формата *.gif)
        /// </summary>
        /// <param name="file"></param>
        public void ImportFromFile(string file)
        {
            if (!File.Exists(file)) return;
            //Palette = new ushort[0x100];
            //Frames = new List<FrameEdit>();
            //idxextra = 0x00000000; // хз

            ClearFrames();
            switch(Path.GetExtension(file)) {
                case ".avi" :
                    var filename = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file));
                    var avi = new AviManager(filename+".avi", true);
                    var stream = avi.GetVideoStream();
                    stream.GetFrameOpen();
                    var frames = new Bitmap[stream.CountFrames];
                    for (int pos = 0; pos < stream.CountFrames; ++pos)
                        frames[pos] = stream.GetBitmap(pos);
                    stream.GetFrameClose();
                    avi.Close();

                    if (File.Exists(filename+".pal"))
                        this.GetPalPalette(filename+".pal");
                    else this.GetImagePalette(frames);

                    if (Frames == null)
                        Frames = new List<FrameEdit>();
                    foreach (var frame in frames)
                        Frames.Add(new FrameEdit(frame, FrameEdit.GetSingleRect(frame), Palette, frame.Width/2, -frame.Height/4));
                        //this.AddFrame(frame);

                    break;
                case ".gif" :
                    throw new NotImplementedException();
                    break;
                default : throw new FileFormatException();
            }
        }
        public void ExportToAVI(string file, bool createPal = false)
        {
            var frames = this.GetFrames(true);
            if (frames == null || frames.Length <= 0) return;
            if (createPal) SavePalPalette(Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)+".pal"));

            var avi = new AviManager(file, false);
            var bitdat = frames[0].LockBits(new Rectangle(0, 0, frames[0].Width, frames[0].Height), ImageLockMode.ReadOnly, PixelFormat.Format16bppArgb1555);
            var size = bitdat.Stride * frames[0].Height;
            frames[0].UnlockBits(bitdat);
            var stream = avi.AddVideoStream(false, 10.0, size, frames[0].Width, frames[0].Height, PixelFormat.Format16bppArgb1555);
            foreach (var frame in frames) {
                stream.AddFrame(frame);
            }
            avi.Close();
        }
Beispiel #31
0
        /// <summary>
        /// 
        /// </summary>
        public override void SetAnimation()
        {
            // Set canvas
            _canvas = _control.Canvas;
            // Avi
            if (_aviManager != null || _isLimit || !outputCheckBox.Checked)
                return;

            // Set AviManager.
            string filename = this.aviFileName.FileName;
            try
            {
                // Delete File.
                if (File.Exists(filename))
                    File.Delete(filename);
                // Create dir.
                if (!Directory.Exists(Path.GetDirectoryName(filename)))
                    Directory.CreateDirectory(Path.GetDirectoryName(filename));
                // Create Movie.
                _aviManager = new AviManager(filename, false);
                Bitmap bmp = new Bitmap(_canvas.PCanvas.Camera.ToImage(640, 480, _canvas.BackGroundBrush));
                _stream = _aviManager.AddVideoStream(false, 10, bmp);
            }
            catch (Exception e)
            {
                Util.ShowErrorDialog(MessageResources.ErrCreateAvi + "\n" + e.Message);
                outputCheckBox.Checked = false;
                _stream = null;
                _aviManager = null;
            }
        }
        // constructor
        public AviWriter(List<frame> Frame, String filename)
        {
            Console.WriteLine("Frame.Count: {0}", Frame.Count);
            string path = Environment.CurrentDirectory + "\\Images\\169.png";
            Image blank = Image.FromFile(path);
            Bitmap blankbuf = new Bitmap(blank, width, height);

            bitmaps.Add(blankbuf);

            del.Add(0.1);

            for (int i = 0; i < Frame.Count; i++)
            {
                del.Add((((double)Frame[i].delay) / 1000.00));
                string FileName  = Frame[i].src;
                Image img = Image.FromFile(FileName);
                Bitmap bitmap = new Bitmap(img, width, height);
                bitmaps.Add(bitmap);

                Console.WriteLine("Frame: {0}", i, " delay: {1}", ((double)Frame[i].delay / 1000.00), "src: {2}", Frame[i].src);
            }

            min = del.Min();
            opfr = 1000 / (min * 1000);
            AviManager aviManager = new AviManager(filename, false);
            VideoStream aviStream = aviManager.AddVideoStream(false, opfr, bitmaps[0]);
            Console.WriteLine("min: {0}", min);
            

            


            for(int i = 0; i < bitmaps.Count; i++)
            {

                if (del[i] > min)
                {
                    double j = del[i];
                    while ( j > min)
                    {
                        aviStream.AddFrame(bitmaps[i]);
                        j = j - min;
                    }

                }
                else
                {
                    aviStream.AddFrame(bitmaps[i]);
                }

                
                //Console.WriteLine("Frame added");
             /*   
                for(double j = min; j <= del[i];)
                {
                    aviStream.AddFrame(bitmaps[i]);
                    j = j + min;

                    Console.WriteLine("j: {0}", j);
                }
              */
            }

            aviManager.Close();
            del.Clear();
        }
Beispiel #33
0
 private void CloseMovie()
 {
     if (_aviManager != null)
     {
         _stream = null;
         _aviManager.Close();
         _aviManager = null;
     }
 }
Beispiel #34
0
        public static void StartRecording()
        {
            Console.WriteLine("Start Recording ...");

            var videoTransfert = new InterProcessCommunication.VideoTranfert();

            VideoStream aviStream = null;
            AviManager aviManager = null;

            bool endOfReccord = false;
            string lastFileReccord = "";

            do
            {
                // Récupère le frame suivant
                Console.Write("Reading frame");
                var frame = videoTransfert.ReadFrame();
                Console.WriteLine(" ...");

                // Vérfie que nous somme pas à la fin de l'enregistrement
                endOfReccord = frame.EndOfRecord;
                if(!endOfReccord)
                {
                    var bitmap = frame.Bitmap;
                    // Si le nom du fichier d'enregistrement est changé un nouveau fichier vidéo doit être créé
                    if (lastFileReccord.Equals(frame.FileName) == false)
                    {

                        // Ferme le fichier s'il y en a un d'ouvert
                        if (aviManager != null)
                        {
                            Console.WriteLine(@"Close video stream ""{0}"" ...", lastFileReccord);
                            aviManager.Close();
                        }

                        lastFileReccord = frame.FileName;

                        Console.Write(@"Creating video stream ""{0}"" ...", lastFileReccord);

                        // Si le fichier est déjà existant on le supprime
                        if (System.IO.File.Exists(lastFileReccord))
                            System.IO.File.Delete(lastFileReccord);

                        aviManager = new AviManager(lastFileReccord, false);
                        aviStream = aviManager.AddVideoStream(false,frame.FrameRate, bitmap); //bitmap étant la première image, elle sert a sizer le format du vidéo de sorti
                        Console.WriteLine(" ...");

                    }
                    else
                    {
                        Console.Write("Add frame to stream");
                        aviStream.AddFrame(bitmap);
                        Console.WriteLine(" ...");

                    }
                    bitmap.Dispose();
                }

            } while (!endOfReccord);

            // Ferme le fichier s'il y en a un d'ouvert
            if (aviManager != null)
            {
                Console.WriteLine(@"Close video stream ""{0}"" ...", lastFileReccord);
                aviManager.Close();
            }

            Console.WriteLine("End Recording ...");
        }
Beispiel #35
0
        private void BUT_start_Click(object sender, EventArgs e)
        {
            saveconfig();
            try
            {
                m_mediaCtrl.Stop();
            }
            catch
            {
            }
            try
            {
                frame = framecount;
                th.Abort();
            }
            catch
            {
            }

            try
            {
                newManager =
                    new AviManager(
                        System.IO.Path.GetDirectoryName(txtAviFileName.Text) + System.IO.Path.DirectorySeparatorChar +
                        System.IO.Path.GetFileNameWithoutExtension(txtAviFileName.Text) + "-overlay.avi", false);
            }
            catch
            {
                CustomMessageBox.Show(Strings.InvalidFileName, Strings.ERROR);
                return;
            }


            //newManager.Close();

            startup();

            this.MaximumSize = this.Size;
            this.MinimumSize = this.Size;
        }
Beispiel #36
0
        /// <summary>Copy a piece of video and wave sound int a new file</summary>
        /// <param name="newFileName">File name</param>
        /// <param name="startAtSecond">Start copying at second x</param>
        /// <param name="stopAtSecond">Stop copying at second y</param>
        /// <returns>AviManager for the new video</returns>
        public AviManager CopyTo(String newFileName, float startAtSecond, float stopAtSecond) {
            AviManager newFile = new AviManager(newFileName, false);

            try {
                //copy video stream

                VideoStream videoStream = GetVideoStream();

                int startFrameIndex = (int)(videoStream.FrameRate * startAtSecond);
                int stopFrameIndex = (int)(videoStream.FrameRate * stopAtSecond);

                videoStream.GetFrameOpen();
                Bitmap bmp = videoStream.GetBitmap(startFrameIndex);
                VideoStream newStream = newFile.AddVideoStream(false, videoStream.FrameRate, bmp);
                for (int n = startFrameIndex + 1; n <= stopFrameIndex; n++) {
                    bmp = videoStream.GetBitmap(n);
                    newStream.AddFrame(bmp);
                }
                videoStream.GetFrameClose();

                //copy audio stream

                AudioStream waveStream = GetWaveStream();

                Avi.AVISTREAMINFO streamInfo = new Avi.AVISTREAMINFO();
                Avi.PCMWAVEFORMAT streamFormat = new Avi.PCMWAVEFORMAT();
                int streamLength = 0;
                IntPtr ptrRawData = waveStream.GetStreamData(
                    ref streamInfo,
                    ref streamFormat,
                    ref streamLength);

				int startByteIndex = (int)( startAtSecond * (float)(waveStream.CountSamplesPerSecond * streamFormat.nChannels * waveStream.CountBitsPerSample) / 8);
				int stopByteIndex = (int)( stopAtSecond * (float)(waveStream.CountSamplesPerSecond * streamFormat.nChannels * waveStream.CountBitsPerSample) / 8);

                IntPtr ptrWavePart = new IntPtr(ptrRawData.ToInt32() + startByteIndex);

                byte[] rawData = new byte[stopByteIndex - startByteIndex];
				Marshal.Copy(ptrWavePart, rawData, 0, rawData.Length);
				Marshal.FreeHGlobal(ptrRawData);

                streamInfo.dwLength = rawData.Length;
                streamInfo.dwStart = 0;

                IntPtr unmanagedRawData = Marshal.AllocHGlobal(rawData.Length);
                Marshal.Copy(rawData, 0, unmanagedRawData, rawData.Length);
                newFile.AddAudioStream(unmanagedRawData, streamInfo, streamFormat, rawData.Length);
				Marshal.FreeHGlobal(unmanagedRawData);
            } catch (Exception ex) {
                newFile.Close();
                throw ex;
            }

            return newFile;
        }