AccessViolationException when trying to connect filters

0

I am trying to implement a filtergraph in c# code. The filter is perfectly ok in graphstudionext and works, but when trying to connect the last two filters (the mpeg-mux filter and the file writer filter) i get an AccessViolationException.

What can be the reason for an accessviolation error? When does it usually happens. How do you figure out how to fix it? Could it be that the cause of the error is not my code but the filter?

filtergraph The link error happens between Mpeg-4 Multiplexor and Filewriter Here is my code: (the error happens at the bottom)

  private void init()
        {
            m_filterGraph = new FilterGraph() as IFilterGraph2;
            mediaControl = (IMediaControl)m_filterGraph;
            mediaEvent = (IMediaEvent)m_filterGraph;


            int hr;
            DsDevice[] audiDevices;

            audiDevices = DsDevice.GetDevicesOfCat(FilterCategory.AudioInputDevice);
            List<IPin> audioOutputs = new List<IPin>();

            DsDevice[] capDevices;

            // Get the collection of video devices
            capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            if (capDevices.Count() < 2)
            {
                throw new Exception("Not enough video input devices found");
            }
            ISampleGrabber sampGrabber = null;
            IBaseFilter baseGrabFlt = null;
            List<IBaseFilter> capFilter = new List<IBaseFilter>();
            IBaseFilter muxFilter = null;
            IFileSinkFilter fileWriterFilter = null;
            ICaptureGraphBuilder2 capGraph = null;

            try
            {
                capGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
                hr = capGraph.SetFiltergraph(m_filterGraph);
                DsError.ThrowExceptionForHR(hr);
                for (int i = 0; i < Math.Min(capDevices.Count(), 2); i++)
                {
                    IBaseFilter _capFIlter;
                    hr = m_filterGraph.AddSourceFilterForMoniker(capDevices[i].Mon, null, capDevices[i].Name, out _capFIlter);

                    DsError.ThrowExceptionForHR(hr);
                    capFilter.Add(_capFIlter);
                }


                DsError.ThrowExceptionForHR(hr);

                for (int i = 0; i < Math.Min(audiDevices.Length, 1); i++)
                {
                    IBaseFilter _audioFilter;
                    hr = m_filterGraph.AddSourceFilterForMoniker(audiDevices[i].Mon, null, audiDevices[i].Name,
                        out _audioFilter);
                    IPin audiooutpin = FindPinByDirection(_audioFilter, PinDirection.Output);
                    audioOutputs.Add(audiooutpin);
                }

                //MJPEG Decompressor
                IBaseFilter mjpeg_dec0 = null;
                IBaseFilter mjpeg_dec1 = null;
                Guid mjpegguid = Guid.Parse("301056D0-6DFF-11D2-9EEB-006008039E37");
                Type t1 = Type.GetTypeFromCLSID(mjpegguid);
                mjpeg_dec0 = (IBaseFilter) Activator.CreateInstance(t1);
                mjpeg_dec1 = (IBaseFilter) Activator.CreateInstance(t1);
                hr = m_filterGraph.AddFilter(mjpeg_dec0, "MJPEG0");
                hr = m_filterGraph.AddFilter(mjpeg_dec1, "MJPEG1");
                IPin cam1out;
                IPin cam2out;

                IPin pinmjpegIn = FindPinByDirection(mjpeg_dec0, PinDirection.Input);
                IPin pinjmpegIn1 = FindPinByDirection(mjpeg_dec1, PinDirection.Input);

                if (capFilter.Count < 1 || capFilter[0] == null)
                {
                    throw new Exception("No input devices found!");
                }
                IPin cam0Out = FindPinByDirection(capFilter[0], PinDirection.Output);
                m_filterGraph.Connect(cam0Out, pinmjpegIn);

                if (capFilter.Count >= 1 && capFilter[1] != null)
                {
                    cam1out = FindPinByDirection(capFilter[1], PinDirection.Output);
                    m_filterGraph.Connect(cam1out, pinjmpegIn1);
                }


                //MyFilter
                IPin mjpegOut = FindPinByDirection(mjpeg_dec0, PinDirection.Output);
                IPin mjpegout1 = FindPinByDirection(mjpeg_dec1, PinDirection.Output);





                IBaseFilter myfitlter = null;


                Guid myfilterGuid = Guid.Parse("067216DE-E6A1-49C9-A016-074624C20FE5");
                Type t = Type.GetTypeFromCLSID(myfilterGuid);
                myfitlter = (IBaseFilter)Activator.CreateInstance(t);

                var imyfilter = (IMyFilter)myfitlter;

                //int result = imyfilter.SetIntervalText("THis is intervall test");
                //int result2 = imyfilter.SetIntroText("This is intro text test");

                hr = m_filterGraph.AddFilter(myfitlter, "MyFilter");
                DsError.ThrowExceptionForHR(hr);
                IPin mypin0;
                hr = myfitlter.FindPin("PIN0", out mypin0);
                DsError.ThrowExceptionForHR(hr);
                IPin mypin1;
                hr = myfitlter.FindPin("PIN1", out mypin1);
                DsError.ThrowExceptionForHR(hr);
                IPin mypinin2;

                IPin mypinout;
                hr = myfitlter.FindPin("PINOUT0", out mypinout);

                hr = m_filterGraph.Connect(mjpegOut, mypin0);
                DsError.ThrowExceptionForHR(hr);
                hr = m_filterGraph.Connect(mjpegout1, mypin1);
                DsError.ThrowExceptionForHR(hr);



                //Color space convertor

                IBaseFilter colorSpance = null;
                Guid csGUID = Guid.Parse("1643E180-90F5-11CE-97D5-00AA0055595A");
                Type t2 = Type.GetTypeFromCLSID(csGUID);
                colorSpance = (IBaseFilter)Activator.CreateInstance(t2);
                hr = m_filterGraph.AddFilter(colorSpance, "ColorSpaceConvertor");
                IPin csIn = FindPinByDirection(colorSpance, PinDirection.Input);
                IPin csOut = FindPinByDirection(colorSpance, PinDirection.Output);

                hr = m_filterGraph.Connect(mypinout, csIn);
                DsError.ThrowExceptionForHR(hr);



                IBaseFilter ffdshowfilter = null;
                Guid ffdshowguid = Guid.Parse("4DB2B5D9-4556-4340-B189-AD20110D953F");
                Type ffdshowtype = Type.GetTypeFromCLSID(ffdshowguid);
                ffdshowfilter = (IBaseFilter)Activator.CreateInstance(ffdshowtype);
                m_filterGraph.AddFilter(ffdshowfilter, "FFD");
                IPin pinffdin = FindPinByDirection(ffdshowfilter, PinDirection.Input);
                IPin pinffdout = FindPinByDirection(ffdshowfilter, PinDirection.Output);
                hr = m_filterGraph.Connect(csOut, pinffdin);
                DsError.ThrowExceptionForHR(hr);


                IBaseFilter mpegmuxfilter = null;
                Guid mpegmux = Guid.Parse("5FD85181-E542-4E52-8D9D-5D613C30131B");
                Type mpegmuxType = Type.GetTypeFromCLSID(mpegmux);
                mpegmuxfilter = (IBaseFilter)Activator.CreateInstance(mpegmuxType);
                hr = m_filterGraph.AddFilter(mpegmuxfilter, "MpegMux");

                DsError.ThrowExceptionForHR(hr);
                IPin mpegIn = FindPinByDirection(mpegmuxfilter, PinDirection.Input);

                hr = m_filterGraph.Connect(pinffdout, mpegIn);
                IPin mpegOut = FindPinByDirection(mpegmuxfilter, PinDirection.Output);

                DsError.ThrowExceptionForHR(hr);


                m_filterGraph.Connect(pinffdout, mpegIn);

                IBaseFilter filewriter = null;
                filewriter = new FileWriter() as IBaseFilter;

               filesinkFilter= (IFileSinkFilter)filewriter;

                hr = m_filterGraph.AddFilter(filewriter, "FileWriter");
                DsError.ThrowExceptionForHR(hr);
                IPin fileIn = FindPinByDirection(filewriter, PinDirection.Input);
                m_filterGraph.Connect(mpegOut, fileIn); //Here an access violation exception is triggered
                foreach (IPin pin in audioOutputs)
                {
                    IPin muxInPin = FindPinByDirection(mpegmuxfilter, PinDirection.Input);
                    m_filterGraph.Connect(pin, muxInPin);
                }

             }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
        }

Here is again the line where the exception is triggered:

 m_filterGraph.Connect(mpegOut, fileIn); //Here an access violation exception is triggered

I would greatly appreciate any help, suggestion or information, thanks.

The callstack doesnt show much useful information. There is a native transation and i can't see in visual studio which functions are called there nor can i step into the method using the debugger.

[Managed to Native Transition]

YourControlService.dll!YourControlService.YourControlRecorder.init() Line 207 C#

YourControlService.dll!YourControlService.YourControlRecorder.startRecording(string filename = "D:\TEMP\test_2014_5_31.avi") Line 229 C#

YourControlService.dll!YourControlService.Service.StartRecording(string name = "test", string text = "text") Line 79 C# [Lightweight Function]

System.ServiceModel.dll!System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(object instance, object[] inputs, out object[] outputs) Unknown System.ServiceModel.dll!System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(ref System.ServiceModel.Dispatcher.MessageRpc rpc = {System.ServiceModel.Dispatcher.MessageRpc}) Unknown

System.ServiceModel.dll!System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(ref System.ServiceModel.Dispatcher.MessageRpc rpc = {System.ServiceModel.Dispatcher.MessageRpc}) Unknown

System.ServiceModel.dll!System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(ref System.ServiceModel.Dispatcher.MessageRpc rpc) Unknown

System.ServiceModel.dll!System.ServiceModel.Dispatcher.MessageRpc.Process(bool isOperationContextSet = false) Unknown

System.ServiceModel.dll!System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(System.ServiceModel.Channels.RequestContext request = {System.ServiceModel.Channels.HttpRequestContext.ListenerHttpContext}, bool cleanThread, System.ServiceModel.OperationContext currentOperationContext) Unknown

System.ServiceModel.dll!System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(System.ServiceModel.Channels.RequestContext request, System.ServiceModel.OperationContext currentOperationContext) Unknown

System.ServiceModel.dll!System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(System.IAsyncResult result) Unknown

System.ServiceModel.Internals.dll!System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult result) Unknown

System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.Complete(bool completedSynchronously) Unknown

System.ServiceModel.Internals.dll!System.Runtime.InputQueue.AsyncQueueReader.Set(System.Runtime.InputQueue.Item item) Unknown

System.ServiceModel.Internals.dll!System.Runtime.InputQueue.EnqueueAndDispatch(System.Runtime.InputQueue.Item item = {System.Runtime.InputQueue.Item}, bool canDispatchOnThisThread) Unknown

System.ServiceModel.Internals.dll!System.Runtime.InputQueue.EnqueueAndDispatch(System.ServiceModel.Channels.RequestContext item, System.Action dequeuedCallback, bool canDispatchOnThisThread) Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.SingletonChannelAcceptor.Enqueue(System.ServiceModel.Channels.RequestContext item, System.Action dequeuedCallback, bool canDispatchOnThisThread) Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.CompleteParseAndEnqueue(System.IAsyncResult result) Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.HandleParseIncomingMessage(System.IAsyncResult result) Unknown

System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.SyncContinue(System.IAsyncResult result) Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(System.ServiceModel.Channels.ReplyChannelAcceptor replyChannelAcceptor, System.Action dequeuedCallback, System.AsyncCallback callback, object state) Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.HttpChannelListener.HttpContextReceivedAsyncResult.ProcessHttpContextAsync() Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.HttpChannelListener.BeginHttpContextReceived(System.ServiceModel.Channels.HttpRequestContext context, System.Action acceptorCallback, System.AsyncCallback callback, object state) Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.SharedHttpTransportManager.EnqueueContext(System.IAsyncResult listenerContextResult) Unknown

System.ServiceModel.dll!System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(System.IAsyncResult listenerContextResult = {System.Net.ListenerAsyncResult}) Unknown

System.ServiceModel.Internals.dll!System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult result) Unknown

System.dll!System.Net.LazyAsyncResult.Complete(System.IntPtr userToken) Unknown

System.dll!System.Net.ListenerAsyncResult.IOCompleted(System.Net.ListenerAsyncResult asyncResult, uint errorCode, uint numBytes) Unknown

mscorlib.dll!System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint errorCode = 0x00000000, uint numBytes = 0x000004ed, System.Threading.NativeOverlapped* pOVERLAP = 0x000000000330faf8) Unknown

c#
directshow
directshow.net
asked on Stack Overflow May 8, 2014 by Luke • edited May 8, 2014 by Luke

1 Answer

0

A few suggestions to debug this. Much of this applies to debugging any problems with native code called from managed code and some is specific to DirectShow. Specific advice is difficult without knowing more about the crash itself. Any of the filters or even DirectShow itself could be crashing.

  • Use ConnectDirect rather than Connect (intelligent connect) wherever possible. Intelligent connect can potentially create any of the other DirectShow filters registered on your system. A buggy filter could potentially cause a crash. In GraphStudioNext the graph construction report will show some of what intelligent connect is doing behind the scenes. GraphStudioNext also allows you to choose between DirectConnect, DirectConnect with media type, and Intelligent Connect modes and blacklist filters to prevent them being used by Intelligent Connect.
  • Don't have any extra unconnected filters hanging around in the graph when you are connecting or streaming unless you want them to be used by intelligent connect. Well written filters will do nothing but others can cause graph failures.
  • Debug in mixed mode to debug both native code and managed (assuming you're not using a free version of visual studio that does't support this). In Visual Studio 2010, go to Solution explorer, right click on project name, properties, debug, enable 'Enable unmanaged code debugging'.
  • If using just in time debugging outside Visual Studio, debug the crash, ask to manually select debugging engines and enable native and managed code debugging.
  • Download symbols for system DLLs to get a better call stack. Module window, select all, right click, Load Symbols from, Microsoft Symbol servers. This may take a while and can't be interrupted. Visual Studio can cache these symbols so you don't have to download them every time (Tools, Options, Debugging, Symbols, Cache symbols in this directory). It's particularly important to have up to date symbols for Quartz, Kernel32, User32, Gdi.
  • Save out a crash dump for later analysis, Debug, Save Dump As, Minidump (you don't need minidump with heap, these are enormous files).
  • Save out a GRF file for analysis in GraphEdit or GraphStudioNext and see if it still crashes when you load the GRF file and try the connection in a graph editing tool. C++ native GRF file saving code is here Saving a Filter Graph to a GraphEdit File
  • Create a log file for the graph
  • Export your graph to the running object table and connect from a graph editing tool
answered on Stack Overflow Jan 21, 2015 by persiflage

User contributions licensed under CC BY-SA 3.0