none
Im getting error: DisconnectedContext was detected when extracting frames from a viddeo file. Whats that ? RRS feed

  • Question

  • The program is extracting frames from a video file. In this case im doing that it will extract 1/20(20 frames per second).

    And im using a 99.5MB video file wich is .3gp(Htc desire phone file video i recorded).

     

    Its extracting all the frames about 5519 files ! When its getting to the end im getting the error and i cant close the program regular it dosent close like when its finished. I see the icon of the running program when standing on it with the mouse i see:  Form1 but thats it.

    I need to make OK on the error message window and then the program quit.

     

    This is the error im message:

     

    Context 0x5abe30' is disconnected.  Releasing the interfaces from the current context (context 0x5abcc0). This may cause corruption or data loss. To avoid this problem, please ensure that all contexts/apartments stay alive until the application is completely done with the RuntimeCallableWrappers that represent COM components that live inside them.

     

    Im clicking OK on this message error and then im doing Debug>Stop Debugging

     

    Cant figure out why this error is popup and if all frames realy extracted before the error popup.

    I can see the frames and edit each one. Each frame is saved on my hard disk as .bmp files the first one name is: 000000,000001...last one is: 005519

     

    This is the full code of my program in Form1.cs:

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using ExtractFrames.Properties;
    using ExtractFrames;
    using JockerSoft.Media;
    using JockerSoft;
    using Interop.qedit;
    using Interop;
    using System.Runtime.InteropServices;
    using System.IO;
    
    namespace ExtractFrames
    {
        public partial class Form1 : Form
        {
            FolderBrowserDialog fb;
            OpenFileDialog openFileDialog1;
            private bool _connect = false;
            private bool _rightButton;
            List<LinePoint> _points = null;
            private float _circleWidth = 10;
            DirectoryInfo dir1;
            FileInfo[] fi;
            double streamlength;
            MediaDet mdd;
            double x;
            string sf;
            double[] streamDouble ;
            string strVideoFile;
            public Form1()
            {
                InitializeComponent();
                fb = new FolderBrowserDialog();
                openFileDialog1 = new OpenFileDialog();
                mdd = new MediaDet();
                streamDouble = new double[1];
                sf = @"d:\Frames\";
                dir1 = new DirectoryInfo(sf);
                fi = dir1.GetFiles("*.bmp");
                if (fi.Length == 0)
                {
                    trackBar1.Enabled = false;
                }
                else
                {
                    trackBar1.Minimum = 0;
                    trackBar1.Maximum = fi.Length - 1;
                    trackBar1.Value = 0;//fi.Length - 1;
                    Bitmap newImage;
                    newImage = new Bitmap(fi[0].FullName);
                    pictureBox1.Image = newImage;
                }
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                
            }
    
            private  void getFrameRate()
            {
                // Get framerate
                MediaDet md = new MediaDet();
                md.Filename = strVideoFile;
                //md.CurrentStream = 0;                     // choose the video stream
                x = md.FrameRate;
                double i = md.StreamLength;
                
            }
    
            public static void SaveFramesFromVideo(string videoFile, double[] positions, string outputBitmapFiles)
            {
                if (videoFile == null)
                    throw new ArgumentNullException("videoFile");
    
                double streamLength;
    
                IMediaDet mediaDet = null;
                try
                {
                    _AMMediaType mediaType;
                    if (openVideoStream(videoFile, out mediaDet, out mediaType))
                    {
                        streamLength = mediaDet.StreamLength;
                        Size target = getVideoSize(mediaType);
                        int iteration = 0;
                        foreach (double position in positions)
                        {
                            iteration++;
                            string outputBitmapFile = string.Format(outputBitmapFiles, iteration);
                            mediaDet.WriteBitmapBits(position, target.Width, target.Height, outputBitmapFile);
                        }
                        return;
                    }
                }
                catch (COMException)
                {
                    throw new InvalidVideoFileException();
                }
                finally
                {
                    if (mediaDet != null)
                        Marshal.ReleaseComObject(mediaDet);
                }
    
                throw new InvalidVideoFileException("No video stream was found");
            }
    
    
            private static Size getVideoSize(_AMMediaType mediaType)
            {
                WinStructs.VIDEOINFOHEADER videoInfo = (WinStructs.VIDEOINFOHEADER)Marshal.PtrToStructure(mediaType.pbFormat, typeof(WinStructs.VIDEOINFOHEADER));
    
                return new Size(videoInfo.bmiHeader.biWidth, videoInfo.bmiHeader.biHeight);
            }
    
            private static Size scaleToFit(Size target, Size original)
            {
                if (target.Height * original.Width > target.Width * original.Height)
                    target.Height = target.Width * original.Height / original.Width;
                else
                    target.Width = target.Height * original.Width / original.Height;
    
                return target;
            }
            private static Size scaleToFitSmart(Size target, Size original)
            {
                target = scaleToFit(target, original);
    
                if (target.Width > original.Width || target.Height > original.Height)
                    return original;
    
                return target;
            }
    
    
            private static bool openVideoStream(string videoFile, out IMediaDet mediaDet, out _AMMediaType aMMediaType)
            {
                mediaDet = new MediaDet();
    
                //loads file
                mediaDet.Filename = videoFile;
    
                //gets # of streams
                int streamsNumber = mediaDet.OutputStreams;
    
                //finds a video stream
                for (int i = 0; i < streamsNumber; i++)
                {
                    mediaDet.CurrentStream = i;
                    _AMMediaType mediaType = mediaDet.StreamMediaType;
    
                    if (mediaType.majortype == JockerSoft.Media.MayorTypes.MEDIATYPE_Video)
                    {
                        //video stream found
                        aMMediaType = mediaType;
                        return true;
                    }
                }
    
                //no video stream found
                Marshal.ReleaseComObject(mediaDet);
                mediaDet = null;
                aMMediaType = new _AMMediaType();
                return false;
            }
    
    
            private bool LoadPictureAt(int nIndex, object c)
            {
    
                bool bRet = false;
    
                if (nIndex >= 0 && nIndex < fi.Length)
                {
                    if (c.Equals(trackBar1))
    
                        pictureBox1.Load(fi[nIndex].FullName);
                    bRet = true;
    
                }
    
                return bRet;
            }
    
            private void trackBar1_Scroll(object sender, EventArgs e)
            {
                LoadPictureAt(trackBar1.Value, sender);
            }
    
            private void pictureBox1_Paint(object sender, PaintEventArgs e)
            {
                /*if (_points != null)
                {
                    Pen p = new Pen(Color.Red);
                    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    using (SolidBrush myBrush = new SolidBrush(Color.Red))
                    {
                        for (int i = 0; i < _points.Count; i++)
                        {
                            Point pt = _points[i];
                            e.Graphics.FillEllipse(myBrush, new RectangleF(pt.X - _circleWidth / 2F, pt.Y - _circleWidth / 2F, _circleWidth, _circleWidth));
    
                            if (_connect && i > 0)
                                e.Graphics.DrawLine(Pens.Blue, _points[i - 1], _points[i]);
                        }
                    }
                }*/
    
                if (_points != null)
                {
                    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    using (SolidBrush myBrush = new SolidBrush(Color.Red))
                    {
                        for (int i = 0; i < _points.Count; i++)
                        {
                            try
                            {
                                Point pt = _points[i].Point;
                                e.Graphics.FillEllipse(myBrush, new RectangleF(pt.X - _circleWidth / 2F, pt.Y - _circleWidth / 2F, _circleWidth, _circleWidth));
    
                                if (i > 0)
                                {
                                    if (_points[i].Connected)
                                        e.Graphics.DrawLine(Pens.Blue, _points[i - 1].Point, _points[i].Point);
                                }
                            }
                            catch ( Exception err)
                            {
                                textBox1.Text = err.ToString();
                            }
                        }
                    }
                }
    
    
            }
    
            private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
            {
                /*if (e.Button == MouseButtons.Left)
                {
                    if (_points == null)
                        _points = new List<Point>();
                    _points.Add(new Point(e.X, e.Y));
                    pictureBox1.Invalidate();
                }*/
                if (e.Button == MouseButtons.Left)
                {
                    if (_points == null)
                        _points = new List<LinePoint>();
                    _points.Add(new LinePoint() { Point = new Point(e.X, e.Y), Connected = _connect });
                    pictureBox1.Invalidate();
                }
    
                if (e.Button == MouseButtons.Right)
                {
                    _connect = !_connect;
                    _rightButton = true;
                }
            }
    
            private void pictureBox1_DoubleClick(object sender, EventArgs e)
            {
               /* _connect = !_connect;
                pictureBox1.Invalidate();*/
                _points.Clear();
                if (_rightButton && _points != null)
                    _points.Clear();
    
                pictureBox1.Invalidate();
            }
    
            private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
            {
                _rightButton = false;
            }
    
            public class LinePoint
            {
                public Point Point { get; set; }
                public bool Connected { get; set; }
            }
    
            private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Left)
                {
    
                    
                }
            }
    
            private void loadVideoToolStripMenuItem_Click(object sender, EventArgs e)
            {
                openFileDialog1.Title = "Select a video file";
                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.FileName = null;
                openFileDialog1.Filter = "Video Files|*.wmv;*.3gp;*.avi";
                openFileDialog1.FilterIndex = 1;
                openFileDialog1.RestoreDirectory = true;
                DialogResult result1 = openFileDialog1.ShowDialog();
                string file1 = openFileDialog1.FileName;
                if (result1 == DialogResult.OK)
                {
                    strVideoFile = file1;
                    mdd.Filename = strVideoFile;
                    streamlength = mdd.StreamLength;
                    double dt = (double)1 / (double)20; //mdd.FrameRate;
                    int i = 0;
                    for (double x = 0; x < streamlength; x += dt)
                    {
                        streamDouble[0] = x;
                        SaveFramesFromVideo(strVideoFile, streamDouble, sf + i.ToString("D6") + ".bmp");
                        i++;
                    }
                    fi = dir1.GetFiles("*.bmp");
                    if (fi.Length == 0)
                    {
                        trackBar1.Enabled = false;
                    }
                    else
                    {
                        trackBar1.Enabled = true;
                        trackBar1.Minimum = 0;
                        trackBar1.Maximum = fi.Length - 1;
                        trackBar1.Value = 0;//fi.Length - 1;
                        Bitmap newImage;
                        newImage = new Bitmap(fi[0].FullName);
                        pictureBox1.Image = newImage;
                    }
                }
                if (result1 == DialogResult.Cancel)
                {
                    if (file1 == "")
                    {
                    }
                }
            }
    
            private void changeExtractedFramesDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
            {
                fb.Description = "Directory To Extract Frames";
                DialogResult result = fb.ShowDialog();
                string file1 = fb.SelectedPath;
            }
        }
    }
    
    

     

    In the refereces i have added: Interop.qedit.dll and JockerSoft.Media.dll

     

    Thanks for the help.

     


    danieli
    Saturday, November 5, 2011 5:33 PM

All replies

  • Hi Danieli,

    I dont know, if this causes the error, but you should release the Com-object before retuning from the method:

    //...
                IMediaDet mediaDet = null;
                try
                {
                    _AMMediaType mediaType;
                    if (openVideoStream(videoFile, out mediaDet, out mediaType))
                    {
                        streamLength = mediaDet.StreamLength;
                        Size target = getVideoSize(mediaType);
                        int iteration = 0;
                        foreach (double position in positions)
                        {
                            iteration++;
                            string outputBitmapFile = string.Format(outputBitmapFiles, iteration);
                            mediaDet.WriteBitmapBits(position, target.Width, target.Height, outputBitmapFile);
                        }
                        //dont return here, or release the comObject first
                        if (mediaDet != null)
                            Marshal.ReleaseComObject(mediaDet);
                        return;
                    }
                }
                catch (COMException)
                {
                    throw new InvalidVideoFileException();
                }
                finally
                {
                    if (mediaDet != null)
                        Marshal.ReleaseComObject(mediaDet);
                }
    /...

    Regards,

      Thorsten

    Saturday, November 5, 2011 6:51 PM
  • It didnt solve the problem the exception error but i changed as you said anyway.
    danieli
    Saturday, November 5, 2011 8:33 PM
  • yes,

    so do not return from inside the try...catch block. Return after the finally block instead...

    And what kind of object is the _AMMediaType? Has something to be freed here?

    //...
                IMediaDet mediaDet = null;
                try
                {
                    _AMMediaType mediaType;
                    if (openVideoStream(videoFile, out mediaDet, out mediaType))
                    {
                        streamLength = mediaDet.StreamLength;
                        Size target = getVideoSize(mediaType);
                        int iteration = 0;
                        foreach (double position in positions)
                        {
                            iteration++;
                            string outputBitmapFile = string.Format(outputBitmapFiles, iteration);
                            mediaDet.WriteBitmapBits(position, target.Width, target.Height, outputBitmapFile);
                        }
    
                    }
                }
                catch (COMException)
                {
                    throw new InvalidVideoFileException();
                }
                finally
                {
                    if (mediaDet != null)
                        Marshal.ReleaseComObject(mediaDet);
                }
    
                return;
    /...

    Regards,

     

      Thorsten



    Saturday, November 5, 2011 9:33 PM
  • Thank you Thorsten for your time and efforts in the forum!

     

    Hi chocolade,

    Welcome to the MSDN forum!

    I’m moving the thread from Visual C# General forum Common Language Runtime (CLR) forum for better support.

    In the meantime, there is a similar thread in the MSDN forum for you to check out. Please take a look at the following link:
    Error in MS VS.NET 2005 TEAM Message: Context 0x1b1670' is disconnected.
    http://social.msdn.microsoft.com/forums/en-US/clr/thread/f9d04ae1-d69e-4cdd-b357-1f648184034a

    “You can find more information on the error here:
    disconnectedContext MDA
    http://msdn2.microsoft.com/en-us/library/2c1czate.aspx

    I spent a little while tracking this down in one of our solutions recently.  In our instance, one of our coders was making calls to AD with System.DirectoryServices objects in a BackgroundWorker component and not cleaning up (calling Dispose()).  What's worse is that we were only seeing it 1 in 10 times or so, and the MDA doesn't give you a good sense of *where* the problem is or from which component the error is originating from. 

    I would suspect with some tweaking of the debugger that they could identify the component that was out in it's own apartment trying to do something?  That's for doods much more qualified than I to determine, though.

    If you're using threading, either through a bgw or manually, I would check that code first to make sure the thread's not closing on you prior to cleanup taking place.”

    Thank you for your understanding and have a nice day!
    Yoyo. 


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, November 8, 2011 5:16 AM
    Moderator