public void Start() { Debug.WriteLine("Starting..."); if (aviStream != null || aviManager != null) { Debug.WriteLine("AviManager is not null!"); } Sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30); string time = System.DateTime.Now.ToString("hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat); string path = Path.Combine(KissHelper.GetPath(), "kiss-" + time + ".avi"); aviManager = new AviManager(path, false); BitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(ColorBitmap)); MemoryStream s = new MemoryStream(); encoder.Save(s); Bitmap b = (Bitmap)Image.FromStream(s); Avi.AVICOMPRESSOPTIONS opts = new Avi.AVICOMPRESSOPTIONS(); opts.fccType = 0; // (UInt32)Avi.mmioStringToFOURCC("mrle", 0); opts.fccHandler = 1684633187;// (UInt32)Avi.mmioStringToFOURCC("MRLE", 0); opts.dwKeyFrameEvery = 0; opts.dwQuality = 10000; // 0 .. 10000 opts.dwFlags = 10; // AVICOMRPESSF_KEYFRAMES = 4 opts.dwBytesPerSecond = 204800; opts.lpFormat = new IntPtr(0); opts.cbFormat = 0; opts.lpParms = new IntPtr(0); opts.cbParms = 4; opts.dwInterleaveEvery = 0; aviStream = aviManager.AddVideoStream(opts, 1000.0 / Properties.Settings.Default.TickMsec, b); if (OnStart != null) OnStart(null); Debug.WriteLine("Started."); }
/// <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); }
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; }
/// <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); }
// 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ı"); } }
/// <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); }
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(); }
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 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(); }
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 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!"); } }
/// <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; }
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 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(); }
public void SaveAsVideo() { Bitmap bmp = _images[0]; AviManager aviManager = new AviManager(Path.Combine(_targetPath, "video.avi"), false); VideoStream aviStream = aviManager.AddVideoStream(false, _fps, bmp); for (int n = 1; n < _images.Count; n++) { aviStream.AddFrame(_images[n]); } ClearImages(); aviManager.Close(); }
static void Main(string[] args) { Console.WriteLine("MobiConverter by Gericom"); Console.WriteLine(); if (args.Length == 0) { PrintUsage(); return; } switch (args[0]) { case "-d": { if (args.Length != 2 && args.Length != 3) goto default; if (!File.Exists(args[1])) { Console.WriteLine("Error! File not found: " + args[1]); return; } String outfile = (args.Length == 3) ? args[2] : Path.ChangeExtension(args[1], "avi"); byte[] sig = new byte[4]; Stream s = File.OpenRead(args[1]); s.Read(sig, 0, 4); s.Close(); if (sig[0] == 0x4C && sig[1] == 0x32 && sig[2] == 0xAA && sig[3] == 0xAB)//moflex { Console.WriteLine("Moflex container detected!"); Console.Write("Converting: "); Console.CursorVisible = false; MobiclipDecoder ddd = null; AviManager m = new AviManager(outfile, false); MemoryStream audio = null; FastAudioDecoder[] mFastAudioDecoders = null; int audiorate = -1; int audiochannels = 0; VideoStream vs = null; FileStream stream = File.OpenRead(args[1]); var d = new MoLiveDemux(stream); int PlayingVideoStream = -1; d.OnCompleteFrameReceived += delegate(MoLiveChunk Chunk, byte[] Data) { if ((Chunk is MoLiveStreamVideo || Chunk is MoLiveStreamVideoWithLayout) && ((PlayingVideoStream == -1) || ((MoLiveStream)Chunk).StreamIndex == PlayingVideoStream)) { if (ddd == null) { ddd = new MobiclipDecoder(((MoLiveStreamVideo)Chunk).Width, ((MoLiveStreamVideo)Chunk).Height, MobiclipDecoder.MobiclipVersion.Moflex3DS); PlayingVideoStream = ((MoLiveStream)Chunk).StreamIndex; } ddd.Data = Data; ddd.Offset = 0; Bitmap b = ddd.DecodeFrame(); if (vs == null) vs = m.AddVideoStream(false, Math.Round(((double)((MoLiveStreamVideo)Chunk).FpsRate) / ((double)((MoLiveStreamVideo)Chunk).FpsScale), 3), b); else vs.AddFrame(b); } else if (Chunk is MoLiveStreamAudio) { if (audio == null) { audio = new MemoryStream(); audiochannels = (int)((MoLiveStreamAudio)Chunk).Channel; audiorate = (int)((MoLiveStreamAudio)Chunk).Frequency; } switch ((int)((MoLiveStreamAudio)Chunk).CodecId) { case 0://fastaudio { if (mFastAudioDecoders == null) { mFastAudioDecoders = new FastAudioDecoder[(int)((MoLiveStreamAudio)Chunk).Channel]; for (int i = 0; i < (int)((MoLiveStreamAudio)Chunk).Channel; i++) { mFastAudioDecoders[i] = new FastAudioDecoder(); } } List<short>[] channels = new List<short>[(int)((MoLiveStreamAudio)Chunk).Channel]; for (int i = 0; i < (int)((MoLiveStreamAudio)Chunk).Channel; i++) { channels[i] = new List<short>(); } int offset = 0; int size = 40; while (offset + size < Data.Length) { for (int i = 0; i < (int)((MoLiveStreamAudio)Chunk).Channel; i++) { mFastAudioDecoders[i].Data = Data; mFastAudioDecoders[i].Offset = offset; channels[i].AddRange(mFastAudioDecoders[i].Decode()); offset = mFastAudioDecoders[i].Offset; } } short[][] channelsresult = new short[(int)((MoLiveStreamAudio)Chunk).Channel][]; for (int i = 0; i < (int)((MoLiveStreamAudio)Chunk).Channel; i++) { channelsresult[i] = channels[i].ToArray(); } byte[] result = InterleaveChannels(channelsresult); audio.Write(result, 0, result.Length); } break; case 1://IMA-ADPCM { IMAADPCMDecoder[] decoders = new IMAADPCMDecoder[(int)((MoLiveStreamAudio)Chunk).Channel]; List<short>[] channels = new List<short>[(int)((MoLiveStreamAudio)Chunk).Channel]; for (int i = 0; i < (int)((MoLiveStreamAudio)Chunk).Channel; i++) { decoders[i] = new IMAADPCMDecoder(); decoders[i].GetWaveData(Data, 4 * i, 4); channels[i] = new List<short>(); } int offset = 4 * (int)((MoLiveStreamAudio)Chunk).Channel; int size = 128 * (int)((MoLiveStreamAudio)Chunk).Channel; while (offset + size < Data.Length) { for (int i = 0; i < (int)((MoLiveStreamAudio)Chunk).Channel; i++) { channels[i].AddRange(decoders[i].GetWaveData(Data, offset, 128)); offset += 128; } } short[][] channelsresult = new short[(int)((MoLiveStreamAudio)Chunk).Channel][]; for (int i = 0; i < (int)((MoLiveStreamAudio)Chunk).Channel; i++) { channelsresult[i] = channels[i].ToArray(); } byte[] result = InterleaveChannels(channelsresult); audio.Write(result, 0, result.Length); } break; case 2://PCM16 { audio.Write(Data, 0, Data.Length - (Data.Length % ((int)((MoLiveStreamAudio)Chunk).Channel * 2))); } break; } } }; bool left = false; int counter = 0; while (true) { uint error = d.ReadPacket(); if (error == 73) break; //report progress if (counter == 0) { Console.Write("{0,3:D}%", stream.Position * 100 / stream.Length); Console.CursorLeft -= 4; } counter++; if (counter == 50) counter = 0; } if (audio != null) { byte[] adata = audio.ToArray(); audio.Close(); var sinfo = new Avi.AVISTREAMINFO(); sinfo.fccType = Avi.streamtypeAUDIO; sinfo.dwScale = audiochannels * 2; sinfo.dwRate = audiorate * audiochannels * 2; sinfo.dwSampleSize = audiochannels * 2; sinfo.dwQuality = -1; var sinfo2 = new Avi.PCMWAVEFORMAT(); sinfo2.wFormatTag = 1; sinfo2.nChannels = (short)audiochannels; sinfo2.nSamplesPerSec = audiorate; sinfo2.nAvgBytesPerSec = audiorate * audiochannels * 2; sinfo2.nBlockAlign = (short)(audiochannels * 2); sinfo2.wBitsPerSample = 16; unsafe { fixed (byte* pAData = &adata[0]) { m.AddAudioStream((IntPtr)pAData, sinfo, sinfo2, adata.Length); } } } m.Close(); stream.Close(); Console.WriteLine("Done!"); Console.CursorVisible = true; } else if (sig[0] == 0x4D && sig[1] == 0x4F && sig[2] == 0x44 && sig[3] == 0x53) { //mods Console.WriteLine("Mods container detected!"); Console.Write("Converting: "); Console.CursorVisible = false; AviManager m = new AviManager(outfile, false); FileStream stream = File.OpenRead(args[1]); ModsDemuxer dm = new ModsDemuxer(stream); MemoryStream audio = null; if ((dm.Header.AudioCodec == 1 || dm.Header.AudioCodec == 3) && dm.Header.NbChannel > 0 && dm.Header.Frequency > 0) { audio = new MemoryStream(); } MobiclipDecoder d = new MobiclipDecoder(dm.Header.Width, dm.Header.Height, MobiclipDecoder.MobiclipVersion.ModsDS); VideoStream vs = null; int CurChannel = 0; List<short>[] channels = new List<short>[dm.Header.NbChannel]; IMAADPCMDecoder[] decoders = new IMAADPCMDecoder[dm.Header.NbChannel]; SxDecoder[] sxd = new SxDecoder[dm.Header.NbChannel]; FastAudioDecoder[] fad = new FastAudioDecoder[dm.Header.NbChannel]; bool[] isinit = new bool[dm.Header.NbChannel]; for (int i = 0; i < dm.Header.NbChannel; i++) { channels[i] = new List<short>(); decoders[i] = new IMAADPCMDecoder(); sxd[i] = new SxDecoder(); fad[i] = new FastAudioDecoder(); isinit[i] = false; } int counter = 0; while (true) { uint NrAudioPackets; bool IsKeyFrame; byte[] framedata = dm.ReadFrame(out NrAudioPackets, out IsKeyFrame); if (framedata == null) break; d.Data = framedata; d.Offset = 0; Bitmap b = d.DecodeFrame(); if (vs == null) vs = m.AddVideoStream(false, Math.Round(dm.Header.Fps / (double)0x01000000, 3), b); else vs.AddFrame(b); if (NrAudioPackets > 0 && audio != null) { int Offset = d.Offset - 2; if (dm.Header.TagId == 0x334E && (IOUtil.ReadU16LE(framedata, 0) & 0x8000) != 0) Offset += 4; if (dm.Header.AudioCodec == 3) { if (IsKeyFrame) { for (int i = 0; i < dm.Header.NbChannel; i++) { channels[i] = new List<short>(); decoders[i] = new IMAADPCMDecoder(); sxd[i] = new SxDecoder(); fad[i] = new FastAudioDecoder(); isinit[i] = false; } } for (int i = 0; i < NrAudioPackets; i++) { channels[CurChannel].AddRange(decoders[CurChannel].GetWaveData(framedata, Offset, 128 + (!isinit[CurChannel] ? 4 : 0))); Offset += 128 + (!isinit[CurChannel] ? 4 : 0); isinit[CurChannel] = true; CurChannel++; if (CurChannel >= dm.Header.NbChannel) CurChannel = 0; } } else if (dm.Header.AudioCodec == 1) { for (int i = 0; i < NrAudioPackets; i++) { if (!isinit[CurChannel]) sxd[CurChannel].Codebook = dm.AudioCodebooks[CurChannel]; isinit[CurChannel] = true; sxd[CurChannel].Data = framedata; sxd[CurChannel].Offset = Offset; channels[CurChannel].AddRange(sxd[CurChannel].Decode()); Offset = sxd[CurChannel].Offset; CurChannel++; if (CurChannel >= dm.Header.NbChannel) CurChannel = 0; } } else if (dm.Header.AudioCodec == 2) { for (int i = 0; i < NrAudioPackets; i++) { fad[CurChannel].Data = framedata; fad[CurChannel].Offset = Offset; channels[CurChannel].AddRange(fad[CurChannel].Decode()); Offset = fad[CurChannel].Offset; CurChannel++; if (CurChannel >= dm.Header.NbChannel) CurChannel = 0; } } int smallest = int.MaxValue; for (int i = 0; i < dm.Header.NbChannel; i++) { if (channels[i].Count < smallest) smallest = channels[i].Count; } if (smallest > 0) { //Gather samples short[][] samps = new short[dm.Header.NbChannel][]; for (int i = 0; i < dm.Header.NbChannel; i++) { samps[i] = new short[smallest]; channels[i].CopyTo(0, samps[i], 0, smallest); channels[i].RemoveRange(0, smallest); } byte[] result = InterleaveChannels(samps); audio.Write(result, 0, result.Length); } } //report progress if (counter == 0) { Console.Write("{0,3:D}%", stream.Position * 100 / stream.Length); Console.CursorLeft -= 4; } counter++; if (counter == 50) counter = 0; } if (audio != null) { byte[] adata = audio.ToArray(); audio.Close(); var sinfo = new Avi.AVISTREAMINFO(); sinfo.fccType = Avi.streamtypeAUDIO; sinfo.dwScale = dm.Header.NbChannel * 2; sinfo.dwRate = (int)dm.Header.Frequency * dm.Header.NbChannel * 2; sinfo.dwSampleSize = dm.Header.NbChannel * 2; sinfo.dwQuality = -1; var sinfo2 = new Avi.PCMWAVEFORMAT(); sinfo2.wFormatTag = 1; sinfo2.nChannels = (short)dm.Header.NbChannel; sinfo2.nSamplesPerSec = (int)dm.Header.Frequency; sinfo2.nAvgBytesPerSec = (int)dm.Header.Frequency * dm.Header.NbChannel * 2; sinfo2.nBlockAlign = (short)(dm.Header.NbChannel * 2); sinfo2.wBitsPerSample = 16; unsafe { fixed (byte* pAData = &adata[0]) { m.AddAudioStream((IntPtr)pAData, sinfo, sinfo2, adata.Length); } } } m.Close(); stream.Close(); Console.WriteLine("Done!"); Console.CursorVisible = true; return; } else if (sig[0] == 0x4D && sig[1] == 0x4F && sig[2] == 0x43 && sig[3] == 0x35) { //moc5 Console.WriteLine("MOC5 container detected!"); Console.WriteLine("Error! Not supported yet!"); return; } else { Console.WriteLine("Error! Unrecognized format!"); return; } break; } case "-e": { break; } default: case "-h": PrintUsage(); return; } }
private void CreateMovie(int width, int height, string filepath, Bitmap image) { double framerate = 10; Bitmap b = (Bitmap)image.Clone(); AviManager avm = new AviManager(filepath, false); VideoStream vs = avm.AddVideoStream(false, framerate, b); for (int i = 0; i < 20; i++) { b = (Bitmap)image.Clone(); vs.AddFrame(b); } avm.Close(); }
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 ..."); }
/// <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; }
private void btnExport_Click(object sender, EventArgs e) { string path = SaveDialog("Avi Files (.avi)|*.avi"); if (path != "") { new Thread(() => { AviManager aviManager = null; try { Console.WriteLine(path); //sourcePath = openFile(); //http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library //myReadyNAS device, got files via FTP from my webcam List<PictureItem> jpgFileList = new List<PictureItem>(); PictureItem[] tempArray = new PictureItem[listBox.Items.Count]; listBox.Items.CopyTo(tempArray, 0); jpgFileList.AddRange(tempArray); this.Invoke(new Action(() => { this.toolStripProgressBar1.Maximum = jpgFileList.Count; this.tableLayoutPanel1.Enabled = false; })); //load the first image Bitmap bitmap = (Bitmap)Image.FromFile(jpgFileList.First().path); bitmap.RotateFlip(RotateFlipType.RotateNoneFlipXY); //create a new AVI file aviManager = new AviManager(path, false); //add a new video stream and one frame to the new file //set IsCompressed = false VideoStream aviStream = aviManager.AddVideoStream(true, 12, bitmap); jpgFileList.Skip(1).ToList().ForEach(file => { Console.WriteLine(file); bitmap = new Bitmap(Bitmap.FromFile(file.path)); bitmap.RotateFlip(RotateFlipType.RotateNoneFlipXY); aviStream.AddFrame(bitmap); bitmap.Dispose(); this.Invoke(new Action(() => { this.toolStripProgressBar1.Value++; })); }); aviManager.Close(); this.Invoke(new Action(() => { this.toolStripProgressBar1.Value = 0; this.tableLayoutPanel1.Enabled = true; })); } catch (Exception ex) { if (aviManager != null) aviManager.Close(); this.Invoke(new Action(() => { this.toolStripProgressBar1.Value = 0; this.tableLayoutPanel1.Enabled = true; MessageBox.Show(ex.Message); })); } }).Start(); } }
public void StartVideo(String filePath, int frameRate, int width, int height, System.Drawing.Imaging.PixelFormat pixelFormat, int bytesPerPixel, bool isCompressed) { if (isVideoCaptureRunning || isCompressionRunning) { throw new Exception("Another video is currently being recorded or processed"); } compressThread = null; this.isCompressed = isCompressed; GetVideoFileNames(filePath, out this.finalFilePath, out this.tempFilePath); isVideoCaptureRunning = true; isCompressionRunning = false; String videoFilePath = finalFilePath; if (isCompressed) { videoFilePath = tempFilePath; } videoManager = new AviManager(videoFilePath, false); stream = videoManager.AddVideoStream(false, frameRate, width * height * bytesPerPixel, width, height, pixelFormat); }
/// <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; } }
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; } }
private void compileVideo() { AviManager aviManager = new AviManager(System.IO.Path.Combine(this.folder, "VideoCompressed.avi"), false); System.Drawing.Bitmap firstBitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(System.IO.Path.Combine(this.folder, string.Format("image{0}.png", 0))); VideoStream aviStream = aviManager.AddVideoStream(true, 30, firstBitmap); //VideoStream aviStream = aviManager.AddVideoStream(true, 30, firstBitmap); System.Drawing.Bitmap bitmap; for (int i = 1; i < 178; i++) { bitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(System.IO.Path.Combine(this.folder, string.Format("image{0}.png", i))); aviStream.AddFrame(bitmap); bitmap.Dispose(); } aviManager.Close(); Debug.WriteLine("Video compiled"); }
/** 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(); }
private void btnWriteCompress_Click(object sender, System.EventArgs e) { FrameRateForm dlg = new FrameRateForm(); if(dlg.ShowDialog() == DialogResult.OK){ //load the first image Bitmap bitmap = (Bitmap)Image.FromFile(txtFileNames.Lines[0]); //create a new AVI file AviManager aviManager = new AviManager(@"..\..\testdata\new.avi", false); //add a new video stream and one frame to the new file VideoStream aviStream = aviManager.AddVideoStream(true, dlg.Rate, bitmap); int count = 0; for (int n = 1; n < txtFileNames.Lines.Length; n++) { if (txtFileNames.Lines[n].Trim().Length > 0) { bitmap = (Bitmap)Bitmap.FromFile(txtFileNames.Lines[n]); aviStream.AddFrame(bitmap); bitmap.Dispose(); count++; } } aviManager.Close(); } }
// 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(); }
private void btnWrite_Click(object sender, System.EventArgs e) { FrameRateForm dlg = new FrameRateForm(); if(dlg.ShowDialog() == DialogResult.OK){ Bitmap bmp = (Bitmap)Image.FromFile(txtFileNames.Lines[0]); AviManager aviManager = new AviManager(@"..\..\testdata\new.avi", false); VideoStream aviStream = aviManager.AddVideoStream(false, dlg.Rate, bmp); Bitmap bitmap; int count = 0; for (int n = 1; n < txtFileNames.Lines.Length; n++) { if (txtFileNames.Lines[n].Trim().Length > 0) { bitmap = (Bitmap)Bitmap.FromFile(txtFileNames.Lines[n]); aviStream.AddFrame(bitmap); bitmap.Dispose(); count++; } } aviManager.Close(); } }