vedio streaming problem

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi all.
Im making a live streaming program using directshow.net the problem occurred when I transmit the buffered image to another computer over internet the server gives me Invalid parameter in Image.FromStream.
I have tried seeking the memory stream and moving the position for the memory stream but no use here is the code
{Server:}using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace Live_stream
{
public partial class Player : Form
{
public Player()
{

InitializeComponent();
listening();

}
// intitializa nad start listinig on a port
public void listening()
{
byte[] data = new byte[1000000];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("10.0.0.1"), 25000);
Socket newsock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
bool spen = true;
Socket client = newsock.Accept();
IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;

while (spen)
{
data = ReciveVarData(client);
using (MemoryStream ms = new MemoryStream())
{
ms.Position = 1920;
ms.Read(data, 0, data.Length);
try
{

Image bmp = Image.FromStream(ms); //<<here is the error
StreamPlayer.Image = bmp;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}

if (data.Length == 0)
newsock.Listen(10);
}
client.Close();
newsock.Close();
}
//save the recived bytes to array
private static byte[] ReciveVarData(Socket s)
{

int tottal = 0;
int recv;
byte[] datasize = new byte[4];
recv = s.Receive(datasize,0,4,0);
int size = BitConverter.ToInt32(datasize, 0);

int dataleft = size;
byte[] data = new byte[size];

while (tottal < size)
{
recv = s.Receive(data, tottal, dataleft, 0);
if (recv == 0)
{
break;
}
tottal += recv;
dataleft -= recv;
}

return data;
}
}
}


{client:}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DirectShowLib;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.IO;
using System.Net;

namespace Live_Streaming
{
public partial class Player : Form, ISampleGrabberCB

{
const int GRAPH_NOTIFY=0x8000+1;
IVideoWindow vedioWind = null;
IMediaControl mediaCont = null;
IMediaEventEx mediaEventEx = null;
ICaptureGraphBuilder2 capGraphBuild = null;
IGraphBuilder graphbuilder = null;
Playstat current = Playstat.Stopped;
ISampleGrabber sampleGrab = null;
IBaseFilter BasGFilter;
DsROTEntry rot = null;


IBaseFilter sourceFilter = null;
enum Playstat
{
Running,
Puassed,
Stopped
}
public Player()
{
InitializeComponent();
captureVedio();
}
//to capture from the webcam
public void captureVedio()
{
int hr = 0;



try
{
getInterfaces();
intSampleGraber();

hr = this.capGraphBuild.SetFiltergraph(this.graphbuilder);
using(Device_Select ds = new Device_Select())
{Restart:
DialogResult res = ds.ShowDialog();
if (res == DialogResult.OK)
{
sourceFilter = ds.resDev;
if (sourceFilter == null)
{
MessageBox.Show("You must select a device");
goto Restart;
}
}
else
{
MessageBox.Show("You must select a device!");
goto Restart;
}
}

hr = this.graphbuilder.AddFilter(sourceFilter,"Video Capture");
DsError.ThrowExceptionForHR(hr);

hr = this.capGraphBuild.RenderStream(PinCategory.Preview,MediaType.Video,sourceFilter,this.BasGFilter,null);
DsError.ThrowExceptionForHR(hr);
Marshal.ReleaseComObject(sourceFilter);

setMediaSampleGrabber();

SetupVideoWindow();

this.FramEvent+= new Player.HeFrame(this.OnCaptureDone);
GrapIMG();
//sendStream();
rot = new DsROTEntry(this.graphbuilder);

hr = this.mediaCont.Run();
DsError.ThrowExceptionForHR(hr);

this.current = Playstat.Running;
}
catch(Exception e)
{
MessageBox.Show("Error Occured:n n "+e.ToString());
}

}
//initialize the buffer
public bool intSampleGraber()
{
int hr = 0;
this.sampleGrab = new SampleGrabber() as ISampleGrabber;
if (this.sampleGrab == null)
{
return false;
}

this.BasGFilter = (IBaseFilter)this.sampleGrab;




if (this.BasGFilter == null)
{
MessageBox.Show("Im here!");
Marshal.ReleaseComObject(this.sampleGrab);
this.sampleGrab = null;
}
AMMediaType media = new AMMediaType();
media.majorType = MediaType.Video;
media.subType = MediaSubType.RGB24;
media.formatPtr = IntPtr.Zero;

hr = sampleGrab.SetMediaType(media);
if (hr < 0)
{
Marshal.ThrowExceptionForHR(hr);
}

hr = this.graphbuilder.AddFilter(this.BasGFilter, "SampleGrabber");
if (hr == 0)
{
Marshal.ThrowExceptionForHR(hr);
}
hr = sampleGrab.SetBufferSamples(false);
if (hr == 0)
{
hr = sampleGrab.SetOneShot(false);
}
if (hr == 0)
{
hr = sampleGrab.SetCallback(null, 0);
}
if (hr < 0)
{
Marshal.ThrowExceptionForHR(hr);
}
return true;
}


private int snapwidth = 0;
private int snapheight = 0;
private int snapImageSize = 0;
private bool snapValid = false;
private bool AllowSampleGrabber = true;
//to initialize the vedio grabber to buffer
private void setMediaSampleGrabber()
{
AMMediaType media = new AMMediaType();
VideoInfoHeader header;
this.snapValid = false;
if ((this.BasGFilter != null) && (this.AllowSampleGrabber))
{

int hr;
hr = sampleGrab.GetConnectedMediaType(media);
if (hr < 0)
{
Marshal.ThrowExceptionForHR(hr);
}
if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero))
{
throw new NotSupportedException("Unknown Grabber Formate");
}

header = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
this.snapwidth = header.BmiHeader.Width;
this.snapheight = header.BmiHeader.Height;
this.snapImageSize = header.BmiHeader.ImageSize;
this.snapValid = true;
}
if (!this.snapValid)
{
this.snapwidth = 0;
this.snapheight = 0;
this.snapImageSize = 0;
}
}

public delegate void HeFrame(Bitmap BM);
public event HeFrame FramEvent;
private byte[] savedArray;
private int BufferedSize;
//to capture vedio and buffer it
int ISampleGrabberCB.BufferCB(double sampleTime, IntPtr Buffer,int Bufferlen)
{
this.BufferedSize = Bufferlen;
int strid = this.snapwidth * 3;
Marshal.Copy(Buffer,this.savedArray,0,Bufferlen);
GCHandle handle = GCHandle.Alloc(this.savedArray,GCHandleType.Pinned);
int scn0 = (int)handle.AddrOfPinnedObject();
scn0 += (this.snapheight - 1) * strid;
sendStream();
Bitmap b = new Bitmap(this.snapwidth, this.snapheight, -strid, System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)scn0);
handle.Free();
SetBitmap = b;

return 0;
}
//preparing the byte array to save the image inside it
public void GrapIMG()
{
if (this.savedArray == null)
{
int size = this.snapImageSize;
if ((size < 1000) || (size > 16000000))
{
return;
}
this.savedArray = new byte[size + 64000];
}
sampleGrab.SetCallback((ISampleGrabberCB)this, 1);
}
public Bitmap SetBitmap
{
set { this.FramEvent(value); }
}
//displaying the buffered image
public void OnCaptureDone(Bitmap e)
{
var bmp = new Bitmap(BufferedP.Width, BufferedP.Height);
using (var g = Graphics.FromImage(bmp))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(e, new Rectangle(Point.Empty, bmp.Size));
BufferedP.Image = bmp;

}

}
//preparing the connection and stream
public void sendStream()
{
int sent;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("10.0.0.1"), 25000);
Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
Server.Connect(ipep);
}
catch (Exception e)
{
MessageBox.Show("Didnt Connect: " + e.ToString());
}
MemoryStream ms = new MemoryStream();

ms.Write(savedArray, 0, savedArray.Length);
byte[] imgbytes = ms.GetBuffer();
sent = SendVarData(Server, imgbytes);
ms.Close();
Server.Shutdown(SocketShutdown.Both);
Server.Close();
}
//sending the data
private static int SendVarData(Socket s, byte[] data)
{
int tottal = 0;
int size = data.Length;
int dataleft = size;
int sent;

byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);

while (tottal < size)
{
sent = s.Send(data, tottal, dataleft, SocketFlags.None);
tottal += sent;
dataleft -= sent;
}
return tottal;
}

//Initializing the interfaces
public void getInterfaces()
{
int hr = 0;
this.graphbuilder = (IGraphBuilder)new FilterGraph();
this.capGraphBuild = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
this.mediaCont = (IMediaControl)this.graphbuilder;
this.vedioWind = (IVideoWindow)this.graphbuilder;
this.mediaEventEx = (IMediaEventEx)this.graphbuilder;

hr = this.mediaEventEx.SetNotifyWindow(this.Handle,GRAPH_NOTIFY,IntPtr.Zero);
DsError.ThrowExceptionForHR(hr);
}
//closing the interfaces
public void closeInterfaces()
{
if(this.mediaCont!=null)
{
this.mediaCont.StopWhenReady();
}
this.current = Playstat.Stopped;
if (this.mediaEventEx != null)
{
this.mediaEventEx.SetNotifyWindow(IntPtr.Zero,GRAPH_NOTIFY,IntPtr.Zero);
}
if (this.vedioWind != null)
{
this.vedioWind.put_Visible(OABool.False);
this.vedioWind.put_Owner(IntPtr.Zero);
}
if (this.rot != null)
{
rot.Dispose();
rot = null;
}
Marshal.ReleaseComObject(this.mediaCont);
this.mediaCont = null;
Marshal.ReleaseComObject(mediaEventEx);
this.mediaEventEx = null;
Marshal.ReleaseComObject(this.vedioWind);
this.vedioWind = null;
Marshal.ReleaseComObject(this.graphbuilder);
this.graphbuilder = null;
Marshal.ReleaseComObject(this.capGraphBuild);
this.capGraphBuild = null;
// Marshal.FinalReleaseComObject(this.sampleGrab);
// sampleGrab = null;
}
//prepare the vedio display
public void SetupVideoWindow()
{
int hr = 0;
hr = this.vedioWind.put_Owner(this.VedioP.Handle);
DsError.ThrowExceptionForHR(hr);

hr = this.vedioWind.put_WindowStyle(WindowStyle.Child|WindowStyle.ClipChildren);

ResizeVedioWind();

hr = this.vedioWind.put_Visible(OABool.True);
DsError.ThrowExceptionForHR(hr);
}
//resize the vedio display
public void ResizeVedioWind()
{
if (this.vedioWind != null)
{

this.vedioWind.SetWindowPosition(0,0,this.VedioP.Width,this.VedioP.Height);
}

}
//changing the preview
public void ChangePreviewState(bool ShowVedio)
{
int hr = 0;
if (this.mediaCont == null)
{
return;
}
if (ShowVedio)
{
if (this.current != Playstat.Running)
{
hr = this.mediaCont.Run();
this.current = Playstat.Running;
}
}
else
{
this.mediaCont.StopWhenReady();
this.current = Playstat.Stopped;
}
}
//handel graph events
public void HandlerGraphEvent()
{
int hr = 0;
EventCode code;
IntPtr evParam1, evParam2;
if (this.mediaEventEx == null)
{
return;
}
while (this.mediaEventEx.GetEvent(out code, out evParam1, out evParam2, 0) == 0)
{
hr = this.mediaEventEx.FreeEventParams(code,evParam1,evParam2);
DsError.ThrowExceptionForHR(hr);
}
}

//control window processes
protected override void WndProc(ref Message m)
{
if (m.Msg == GRAPH_NOTIFY)
{
HandlerGraphEvent();
}

if (this.vedioWind != null)
{
this.vedioWind.NotifyOwnerMessage(m.HWnd,m.Msg,m.WParam,m.LParam);
}
base.WndProc(ref m);
}

private void Player_FormClosing(object sender, FormClosingEventArgs e)
{
closeInterfaces();
}

private void Player_Resize(object sender, EventArgs e)
{
ResizeVedioWind();
}


int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
{
throw new NotImplementedException();
}
}
}


Note:for this step Im sending from client to server not other wise
many thanks
Bye Faisal

View the full article
 

Similar threads

P
Replies
0
Views
176
Policy standard local admin account with Active Di
P
A
Replies
0
Views
141
Afshan Gul
A
Back
Top