title: DirectShow loop video infinitely with C++
body: <p>I have this small C++ code playing a video clip with <strong>DirectShow</strong>. What I want is the video to never stop so once it reaches the end I set the position to 0 again. The problem is that between the end and the start of the new loop there's a small <strong>delay</strong> that I would like to remove. My code looks like this:</p>
  
  <pre><code>#define WM_GRAPHNOTIFY  WM_USER
  
  // Global vars
  IGraphBuilder*      g_pGraphBuilder;
  IMediaControl*      g_pMediaCtrl;
  IMediaPosition*     g_pMediaPos;
  IMediaEventEx*      g_pMediaEvent;
  
  HWND                h_MainWindow;
  
  // PlayVideo() - I removed the errors checking lines (irrelevant right now)
  RECT grc;
  IVideoWindow *pVidWin = NULL;
  HRESULT hr = CoInitialize(NULL);
  
  hr = CoCreateInstance(
      CLSID_FilterGraph, 
      NULL, 
      CLSCTX_INPROC_SERVER,
      IID_IGraphBuilder,
      (void**)&amp;g_pGraphBuilder
  );
  
  hr = g_pGraphBuilder-&gt;RenderFile(L"Clip.mpeg", NULL);
  hr = g_pGraphBuilder-&gt;QueryInterface(IID_IVideoWindow, (void **)&amp;pVidWin);
  hr = pVidWin-&gt;put_Owner((OAHWND)h_MainWindow);
  hr = pVidWin-&gt;put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS);
  
  GetClientRect(h_MainWindow, &amp;grc);
  pVidWin-&gt;SetWindowPosition(0, 0, grc.right, grc.bottom);
  
  hr = g_pGraphBuilder-&gt;QueryInterface(IID_IMediaEventEx, (void **)&amp;g_pMediaEvent);
  hr = g_pGraphBuilder-&gt;QueryInterface(IID_IMediaPosition, (void**)&amp;g_pMediaPos);
  hr = g_pMediaEvent-&gt;SetNotifyWindow((OAHWND)h_MainWindow, WM_GRAPHNOTIFY, 0);
  g_pMediaEvent-&gt;SetNotifyFlags(0);
  
  hr = g_pGraphBuilder-&gt;QueryInterface(IID_IMediaControl, (void **)&amp;g_pMediaCtrl);
  g_pMediaCtrl-&gt;Run();
  
  // WndPrc of the main window, the WM_GRAPHNOTIFY message
  long EventCode, Param1, Param2;
  // ...
  case WM_GRAPHNOTIFY:
      while (g_pMediaEvent-&gt;GetEvent(&amp;EventCode, &amp;Param1, &amp;Param2, 0)!=E_ABORT) {
          switch (EventCode) {
              case EC_COMPLETE:
                  // Going back to the start of the clip
                  g_pMediaPos-&gt;put_CurrentPosition(0);
              break;
              default:
              break;
          }   
          g_pMediaEvent-&gt;FreeEventParams(EventCode, Param1, Param2);
      }
  break;
  // ...
  </code></pre>
  
  <p>The problem here, as I said, is that there's a noticeable lag when the video stops and starts again. It looks like EC_COMPLETE is not sent exactly when the video stops or maybe it is but <code>put_CurrentPosition()</code> takes some time to set the position back to 0. Anyway, the problem is that and I wonder if there's a solution to it.</p>