home *** CD-ROM | disk | FTP | other *** search
/ Windows Game Programming for Dummies (2nd Edition) / WinGamProgFD.iso / pc / DirectX SDK / DXSDK / samples / Multimedia / DirectShow / BaseClasses / renbase.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2001-10-08  |  96.6 KB  |  2,834 lines

  1. //------------------------------------------------------------------------------
  2. // File: RenBase.cpp
  3. //
  4. // Desc: DirectShow base classes.
  5. //
  6. // Copyright (c) 1992-2001 Microsoft Corporation.  All rights reserved.
  7. //------------------------------------------------------------------------------
  8.  
  9.  
  10. #include <streams.h>        // DirectShow base class definitions
  11. #include <mmsystem.h>       // Needed for definition of timeGetTime
  12. #include <limits.h>         // Standard data type limit definitions
  13. #include <measure.h>        // Used for time critical log functions
  14.  
  15. #pragma warning(disable:4355)
  16.  
  17. //  Helper function for clamping time differences
  18. int inline TimeDiff(REFERENCE_TIME rt)
  19. {
  20.     if (rt < - (50 * UNITS)) {
  21.         return -(50 * UNITS);
  22.     } else
  23.     if (rt > 50 * UNITS) {
  24.         return 50 * UNITS;
  25.     } else return (int)rt;
  26. }
  27.  
  28. // Implements the CBaseRenderer class
  29.  
  30. CBaseRenderer::CBaseRenderer(REFCLSID RenderClass, // CLSID for this renderer
  31.                              TCHAR *pName,         // Debug ONLY description
  32.                              LPUNKNOWN pUnk,       // Aggregated owner object
  33.                              HRESULT *phr) :       // General OLE return code
  34.  
  35.     CBaseFilter(pName,pUnk,&m_InterfaceLock,RenderClass),
  36.     m_evComplete(TRUE),
  37.     m_bAbort(FALSE),
  38.     m_pPosition(NULL),
  39.     m_ThreadSignal(TRUE),
  40.     m_bStreaming(FALSE),
  41.     m_bEOS(FALSE),
  42.     m_bEOSDelivered(FALSE),
  43.     m_pMediaSample(NULL),
  44.     m_dwAdvise(0),
  45.     m_pQSink(NULL),
  46.     m_pInputPin(NULL),
  47.     m_bRepaintStatus(TRUE),
  48.     m_SignalTime(0),
  49.     m_bInReceive(FALSE),
  50.     m_EndOfStreamTimer(0)
  51. {
  52.     Ready();
  53. #ifdef PERF
  54.     m_idBaseStamp = MSR_REGISTER(TEXT("BaseRenderer: sample time stamp"));
  55.     m_idBaseRenderTime = MSR_REGISTER(TEXT("BaseRenderer: draw time (msec)"));
  56.     m_idBaseAccuracy = MSR_REGISTER(TEXT("BaseRenderer: Accuracy (msec)"));
  57. #endif
  58. }
  59.  
  60.  
  61. // Delete the dynamically allocated IMediaPosition and IMediaSeeking helper
  62. // object. The object is created when somebody queries us. These are standard
  63. // control interfaces for seeking and setting start/stop positions and rates.
  64. // We will probably also have made an input pin based on CRendererInputPin
  65. // that has to be deleted, it's created when an enumerator calls our GetPin
  66.  
  67. CBaseRenderer::~CBaseRenderer()
  68. {
  69.     ASSERT(m_bStreaming == FALSE);
  70.     ASSERT(m_EndOfStreamTimer == 0);
  71.     StopStreaming();
  72.     ClearPendingSample();
  73.  
  74.     // Delete any IMediaPosition implementation
  75.  
  76.     if (m_pPosition) {
  77.         delete m_pPosition;
  78.         m_pPosition = NULL;
  79.     }
  80.  
  81.     // Delete any input pin created
  82.  
  83.     if (m_pInputPin) {
  84.         delete m_pInputPin;
  85.         m_pInputPin = NULL;
  86.     }
  87.  
  88.     // Release any Quality sink
  89.  
  90.     ASSERT(m_pQSink == NULL);
  91. }
  92.  
  93.  
  94. // This returns the IMediaPosition and IMediaSeeking interfaces
  95.  
  96. HRESULT CBaseRenderer::GetMediaPositionInterface(REFIID riid,void **ppv)
  97. {
  98.     CAutoLock cObjectCreationLock(&m_ObjectCreationLock);
  99.     if (m_pPosition) {
  100.         return m_pPosition->NonDelegatingQueryInterface(riid,ppv);
  101.     }
  102.  
  103.     HRESULT hr = NOERROR;
  104.  
  105.     // Create implementation of this dynamically since sometimes we may
  106.     // never try and do a seek. The helper object implements a position
  107.     // control interface (IMediaPosition) which in fact simply takes the
  108.     // calls normally from the filter graph and passes them upstream
  109.  
  110.     m_pPosition = new CRendererPosPassThru(NAME("Renderer CPosPassThru"),
  111.                                            CBaseFilter::GetOwner(),
  112.                                            (HRESULT *) &hr,
  113.                                            GetPin(0));
  114.     if (m_pPosition == NULL) {
  115.         return E_OUTOFMEMORY;
  116.     }
  117.  
  118.     if (FAILED(hr)) {
  119.         delete m_pPosition;
  120.         m_pPosition = NULL;
  121.         return E_NOINTERFACE;
  122.     }
  123.     return GetMediaPositionInterface(riid,ppv);
  124. }
  125.  
  126.  
  127. // Overriden to say what interfaces we support and where
  128.  
  129. STDMETHODIMP CBaseRenderer::NonDelegatingQueryInterface(REFIID riid,void **ppv)
  130. {
  131.     // Do we have this interface
  132.  
  133.     if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking) {
  134.         return GetMediaPositionInterface(riid,ppv);
  135.     } else {
  136.         return CBaseFilter::NonDelegatingQueryInterface(riid,ppv);
  137.     }
  138. }
  139.  
  140.  
  141. // This is called whenever we change states, we have a manual reset event that
  142. // is signalled whenever we don't won't the source filter thread to wait in us
  143. // (such as in a stopped state) and likewise is not signalled whenever it can
  144. // wait (during paused and running) this function sets or resets the thread
  145. // event. The event is used to stop source filter threads waiting in Receive
  146.  
  147. HRESULT CBaseRenderer::SourceThreadCanWait(BOOL bCanWait)
  148. {
  149.     if (bCanWait == TRUE) {
  150.         m_ThreadSignal.Reset();
  151.     } else {
  152.         m_ThreadSignal.Set();
  153.     }
  154.     return NOERROR;
  155. }
  156.  
  157.  
  158. #ifdef DEBUG
  159. // Dump the current renderer state to the debug terminal. The hardest part of
  160. // the renderer is the window where we unlock everything to wait for a clock
  161. // to signal it is time to draw or for the application to cancel everything
  162. // by stopping the filter. If we get things wrong we can leave the thread in
  163. // WaitForRenderTime with no way for it to ever get out and we will deadlock
  164.  
  165. void CBaseRenderer::DisplayRendererState()
  166. {
  167.     DbgLog((LOG_TIMING, 1, TEXT("\nTimed out in WaitForRenderTime")));
  168.  
  169.     // No way should this be signalled at this point
  170.  
  171.     BOOL bSignalled = m_ThreadSignal.Check();
  172.     DbgLog((LOG_TIMING, 1, TEXT("Signal sanity check %d"),bSignalled));
  173.  
  174.     // Now output the current renderer state variables
  175.  
  176.     DbgLog((LOG_TIMING, 1, TEXT("Filter state %d"),m_State));
  177.     DbgLog((LOG_TIMING, 1, TEXT("Abort flag %d"),m_bAbort));
  178.     DbgLog((LOG_TIMING, 1, TEXT("Streaming flag %d"),m_bStreaming));
  179.     DbgLog((LOG_TIMING, 1, TEXT("Clock advise link %d"),m_dwAdvise));
  180.     DbgLog((LOG_TIMING, 1, TEXT("Current media sample %x"),m_pMediaSample));
  181.     DbgLog((LOG_TIMING, 1, TEXT("EOS signalled %d"),m_bEOS));
  182.     DbgLog((LOG_TIMING, 1, TEXT("EOS delivered %d"),m_bEOSDelivered));
  183.     DbgLog((LOG_TIMING, 1, TEXT("Repaint status %d"),m_bRepaintStatus));
  184.  
  185.  
  186.     // Output the delayed end of stream timer information
  187.  
  188.     DbgLog((LOG_TIMING, 1, TEXT("End of stream timer %x"),m_EndOfStreamTimer));
  189.     DbgLog((LOG_TIMING, 1, TEXT("Deliver time %s"),CDisp((LONGLONG)m_SignalTime)));
  190.  
  191.  
  192.     // Should never timeout during a flushing state
  193.  
  194.     BOOL bFlushing = m_pInputPin->IsFlushing();
  195.     DbgLog((LOG_TIMING, 1, TEXT("Flushing sanity check %d"),bFlushing));
  196.  
  197.     // Display the time we were told to start at
  198.     DbgLog((LOG_TIMING, 1, TEXT("Last run time %s"),CDisp((LONGLONG)m_tStart.m_time)));
  199.  
  200.     // Do we have a reference clock?
  201.     if (m_pClock == NULL) return;
  202.  
  203.     // Get the current time from the wall clock
  204.  
  205.     CRefTime CurrentTime,StartTime,EndTime;
  206.     m_pClock->GetTime((REFERENCE_TIME*) &CurrentTime);
  207.     CRefTime Offset = CurrentTime - m_tStart;
  208.  
  209.     // Display the current time from the clock
  210.  
  211.     DbgLog((LOG_TIMING, 1, TEXT("Clock time %s"),CDisp((LONGLONG)CurrentTime.m_time)));
  212.     DbgLog((LOG_TIMING, 1, TEXT("Time difference %dms"),Offset.Millisecs()));
  213.  
  214.     // Do we have a sample ready to render
  215.     if (m_pMediaSample == NULL) return;
  216.  
  217.     m_pMediaSample->GetTime((REFERENCE_TIME*)&StartTime, (REFERENCE_TIME*)&EndTime);
  218.     DbgLog((LOG_TIMING, 1, TEXT("Next sample stream times (Start %d End %d ms)"),
  219.            StartTime.Millisecs(),EndTime.Millisecs()));
  220.  
  221.     // Calculate how long it is until it is due for rendering
  222.     CRefTime Wait = (m_tStart + StartTime) - CurrentTime;
  223.     DbgLog((LOG_TIMING, 1, TEXT("Wait required %d ms"),Wait.Millisecs()));
  224. }
  225. #endif
  226.  
  227.  
  228. // Wait until the clock sets the timer event or we're otherwise signalled. We
  229. // set an arbitrary timeout for this wait and if it fires then we display the
  230. // current renderer state on the debugger. It will often fire if the filter's
  231. // left paused in an application however it may also fire during stress tests
  232. // if the synchronisation with application seeks and state changes is faulty
  233.  
  234. #define RENDER_TIMEOUT 10000
  235.  
  236. HRESULT CBaseRenderer::WaitForRenderTime()
  237. {
  238.     HANDLE WaitObjects[] = { m_ThreadSignal, m_RenderEvent };
  239.     DWORD Result = WAIT_TIMEOUT;
  240.  
  241.     // Wait for either the time to arrive or for us to be stopped
  242.  
  243.     OnWaitStart();
  244.     while (Result == WAIT_TIMEOUT) {
  245.         Result = WaitForMultipleObjects(2,WaitObjects,FALSE,RENDER_TIMEOUT);
  246.  
  247. #ifdef DEBUG
  248.         if (Result == WAIT_TIMEOUT) DisplayRendererState();
  249. #endif
  250.  
  251.     }
  252.     OnWaitEnd();
  253.  
  254.     // We may have been awoken without the timer firing
  255.  
  256.     if (Result == WAIT_OBJECT_0) {
  257.         return VFW_E_STATE_CHANGED;
  258.     }
  259.  
  260.     SignalTimerFired();
  261.     return NOERROR;
  262. }
  263.  
  264.  
  265. // Poll waiting for Receive to complete.  This really matters when
  266. // Receive may set the palette and cause window messages
  267. // The problem is that if we don't really wait for a renderer to
  268. // stop processing we can deadlock waiting for a transform which
  269. // is calling the renderer's Receive() method because the transform's
  270. // Stop method doesn't know to process window messages to unblock
  271. // the renderer's Receive processing
  272. void CBaseRenderer::WaitForReceiveToComplete()
  273. {
  274.     for (;;) {
  275.         if (!m_bInReceive) {
  276.             break;
  277.         }
  278.  
  279.         MSG msg;
  280.         //  Receive all interthread sendmessages
  281.         PeekMessage(&msg, NULL, WM_NULL, WM_NULL, PM_NOREMOVE);
  282.  
  283.         Sleep(1);
  284.     }
  285.  
  286.     // If the wakebit for QS_POSTMESSAGE is set, the PeekMessage call
  287.     // above just cleared the changebit which will cause some messaging
  288.     // calls to block (waitMessage, MsgWaitFor...) now.
  289.     // Post a dummy message to set the QS_POSTMESSAGE bit again
  290.     if (HIWORD(GetQueueStatus(QS_POSTMESSAGE)) & QS_POSTMESSAGE) {
  291.         //  Send dummy message
  292.         PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
  293.     }
  294. }
  295.  
  296. // A filter can have four discrete states, namely Stopped, Running, Paused,
  297. // Intermediate. We are in an intermediate state if we are currently trying
  298. // to pause but haven't yet got the first sample (or if we have been flushed
  299. // in paused state and therefore still have to wait for a sample to arrive)
  300.  
  301. // This class contains an event called m_evComplete which is signalled when
  302. // the current state is completed and is not signalled when we are waiting to
  303. // complete the last state transition. As mentioned above the only time we
  304. // use this at the moment is when we wait for a media sample in paused state
  305. // If while we are waiting we receive an end of stream notification from the
  306. // source filter then we know no data is imminent so we can reset the event
  307. // This means that when we transition to paused the source filter must call
  308. // end of stream on us or send us an image otherwise we'll hang indefinately
  309.  
  310.  
  311. // Simple internal way of getting the real state
  312.  
  313. FILTER_STATE CBaseRenderer::GetRealState() {
  314.     return m_State;
  315. }
  316.  
  317.  
  318. // The renderer doesn't complete the full transition to paused states until
  319. // it has got one media sample to render. If you ask it for its state while
  320. // it's waiting it will return the state along with VFW_S_STATE_INTERMEDIATE
  321.  
  322. STDMETHODIMP CBaseRenderer::GetState(DWORD dwMSecs,FILTER_STATE *State)
  323. {
  324.     CheckPointer(State,E_POINTER);
  325.  
  326.     if (WaitDispatchingMessages(m_evComplete, dwMSecs) == WAIT_TIMEOUT) {
  327.         *State = m_State;
  328.         return VFW_S_STATE_INTERMEDIATE;
  329.     }
  330.     *State = m_State;
  331.     return NOERROR;
  332. }
  333.  
  334.  
  335. // If we're pausing and we have no samples we don't complete the transition
  336. // to State_Paused and we return S_FALSE. However if the m_bAbort flag has
  337. // been set then all samples are rejected so there is no point waiting for
  338. // one. If we do have a sample then return NOERROR. We will only ever return
  339. // VFW_S_STATE_INTERMEDIATE from GetState after being paused with no sample
  340. // (calling GetState after either being stopped or Run will NOT return this)
  341.  
  342. HRESULT CBaseRenderer::CompleteStateChange(FILTER_STATE OldState)
  343. {
  344.     // Allow us to be paused when disconnected
  345.  
  346.     if (m_pInputPin->IsConnected() == FALSE) {
  347.         Ready();
  348.         return S_OK;
  349.     }
  350.  
  351.     // Have we run off the end of stream
  352.  
  353.     if (IsEndOfStream() == TRUE) {
  354.         Ready();
  355.         return S_OK;
  356.     }
  357.  
  358.     // Make sure we get fresh data after being stopped
  359.  
  360.     if (HaveCurrentSample() == TRUE) {
  361.         if (OldState != State_Stopped) {
  362.             Ready();
  363.             return S_OK;
  364.         }
  365.     }
  366.     NotReady();
  367.     return S_FALSE;
  368. }
  369.  
  370.  
  371. // When we stop the filter the things we do are:-
  372.  
  373. //      Decommit the allocator being used in the connection
  374. //      Release the source filter if it's waiting in Receive
  375. //      Cancel any advise link we set up with the clock
  376. //      Any end of stream signalled is now obsolete so reset
  377. //      Allow us to be stopped when we are not connected
  378.  
  379. STDMETHODIMP CBaseRenderer::Stop()
  380. {
  381.     CAutoLock cRendererLock(&m_InterfaceLock);
  382.  
  383.     // Make sure there really is a state change
  384.  
  385.     if (m_State == State_Stopped) {
  386.         return NOERROR;
  387.     }
  388.  
  389.     // Is our input pin connected
  390.  
  391.     if (m_pInputPin->IsConnected() == FALSE) {
  392.         NOTE("Input pin is not connected");
  393.         m_State = State_Stopped;
  394.         return NOERROR;
  395.     }
  396.  
  397.     CBaseFilter::Stop();
  398.  
  399.     // If we are going into a stopped state then we must decommit whatever
  400.     // allocator we are using it so that any source filter waiting in the
  401.     // GetBuffer can be released and unlock themselves for a state change
  402.  
  403.     if (m_pInputPin->Allocator()) {
  404.         m_pInputPin->Allocator()->Decommit();
  405.     }
  406.  
  407.     // Cancel any scheduled rendering
  408.  
  409.     SetRepaintStatus(TRUE);
  410.     StopStreaming();
  411.     SourceThreadCanWait(FALSE);
  412.     ResetEndOfStream();
  413.     CancelNotification();
  414.  
  415.     // There should be no outstanding clock advise
  416.     ASSERT(CancelNotification() == S_FALSE);
  417.     ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent,0));
  418.     ASSERT(m_EndOfStreamTimer == 0);
  419.  
  420.     Ready();
  421.     WaitForReceiveToComplete();
  422.     m_bAbort = FALSE;
  423.  
  424.     return NOERROR;
  425. }
  426.  
  427.  
  428. // When we pause the filter the things we do are:-
  429.  
  430. //      Commit the allocator being used in the connection
  431. //      Allow a source filter thread to wait in Receive
  432. //      Cancel any clock advise link (we may be running)
  433. //      Possibly complete the state change if we have data
  434. //      Allow us to be paused when we are not connected
  435.  
  436. STDMETHODIMP CBaseRenderer::Pause()
  437. {
  438.     CAutoLock cRendererLock(&m_InterfaceLock);
  439.     FILTER_STATE OldState = m_State;
  440.     ASSERT(m_pInputPin->IsFlushing() == FALSE);
  441.  
  442.     // Make sure there really is a state change
  443.  
  444.     if (m_State == State_Paused) {
  445.         return CompleteStateChange(State_Paused);
  446.     }
  447.  
  448.     // Has our input pin been connected
  449.  
  450.     if (m_pInputPin->IsConnected() == FALSE) {
  451.         NOTE("Input pin is not connected");
  452.         m_State = State_Paused;
  453.         return CompleteStateChange(State_Paused);
  454.     }
  455.  
  456.     // Pause the base filter class
  457.  
  458.     HRESULT hr = CBaseFilter::Pause();
  459.     if (FAILED(hr)) {
  460.         NOTE("Pause failed");
  461.         return hr;
  462.     }
  463.  
  464.     // Enable EC_REPAINT events again
  465.  
  466.     SetRepaintStatus(TRUE);
  467.     StopStreaming();
  468.     SourceThreadCanWait(TRUE);
  469.     CancelNotification();
  470.     ResetEndOfStreamTimer();
  471.  
  472.     // If we are going into a paused state then we must commit whatever
  473.     // allocator we are using it so that any source filter can call the
  474.     // GetBuffer and expect to get a buffer without returning an error
  475.  
  476.     if (m_pInputPin->Allocator()) {
  477.         m_pInputPin->Allocator()->Commit();
  478.     }
  479.  
  480.     // There should be no outstanding advise
  481.     ASSERT(CancelNotification() == S_FALSE);
  482.     ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent,0));
  483.     ASSERT(m_EndOfStreamTimer == 0);
  484.     ASSERT(m_pInputPin->IsFlushing() == FALSE);
  485.  
  486.     // When we come out of a stopped state we must clear any image we were
  487.     // holding onto for frame refreshing. Since renderers see state changes
  488.     // first we can reset ourselves ready to accept the source thread data
  489.     // Paused or running after being stopped causes the current position to
  490.     // be reset so we're not interested in passing end of stream signals
  491.  
  492.     if (OldState == State_Stopped) {
  493.         m_bAbort = FALSE;
  494.         ClearPendingSample();
  495.     }
  496.     return CompleteStateChange(OldState);
  497. }
  498.  
  499.  
  500. // When we run the filter the things we do are:-
  501.  
  502. //      Commit the allocator being used in the connection
  503. //      Allow a source filter thread to wait in Receive
  504. //      Signal the render event just to get us going
  505. //      Start the base class by calling StartStreaming
  506. //      Allow us to be run when we are not connected
  507. //      Signal EC_COMPLETE if we are not connected
  508.  
  509. STDMETHODIMP CBaseRenderer::Run(REFERENCE_TIME StartTime)
  510. {
  511.     CAutoLock cRendererLock(&m_InterfaceLock);
  512.     FILTER_STATE OldState = m_State;
  513.  
  514.     // Make sure there really is a state change
  515.  
  516.     if (m_State == State_Running) {
  517.         return NOERROR;
  518.     }
  519.  
  520.     // Send EC_COMPLETE if we're not connected
  521.  
  522.     if (m_pInputPin->IsConnected() == FALSE) {
  523.         NotifyEvent(EC_COMPLETE,S_OK,(LONG_PTR)(IBaseFilter *)this);
  524.         m_State = State_Running;
  525.         return NOERROR;
  526.     }
  527.  
  528.     Ready();
  529.  
  530.     // Pause the base filter class
  531.  
  532.     HRESULT hr = CBaseFilter::Run(StartTime);
  533.     if (FAILED(hr)) {
  534.         NOTE("Run failed");
  535.         return hr;
  536.     }
  537.  
  538.     // Allow the source thread to wait
  539.     ASSERT(m_pInputPin->IsFlushing() == FALSE);
  540.     SourceThreadCanWait(TRUE);
  541.     SetRepaintStatus(FALSE);
  542.  
  543.     // There should be no outstanding advise
  544.     ASSERT(CancelNotification() == S_FALSE);
  545.     ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent,0));
  546.     ASSERT(m_EndOfStreamTimer == 0);
  547.     ASSERT(m_pInputPin->IsFlushing() == FALSE);
  548.  
  549.     // If we are going into a running state then we must commit whatever
  550.     // allocator we are using it so that any source filter can call the
  551.     // GetBuffer and expect to get a buffer without returning an error
  552.  
  553.     if (m_pInputPin->Allocator()) {
  554.         m_pInputPin->Allocator()->Commit();
  555.     }
  556.  
  557.     // When we come out of a stopped state we must clear any image we were
  558.     // holding onto for frame refreshing. Since renderers see state changes
  559.     // first we can reset ourselves ready to accept the source thread data
  560.     // Paused or running after being stopped causes the current position to
  561.     // be reset so we're not interested in passing end of stream signals
  562.  
  563.     if (OldState == State_Stopped) {
  564.         m_bAbort = FALSE;
  565.         ClearPendingSample();
  566.     }
  567.     return StartStreaming();
  568. }
  569.  
  570.  
  571. // Return the number of input pins we support
  572.  
  573. int CBaseRenderer::GetPinCount()
  574. {
  575.     return 1;
  576. }
  577.  
  578.  
  579. // We only support one input pin and it is numbered zero
  580.  
  581. CBasePin *CBaseRenderer::GetPin(int n)
  582. {
  583.     CAutoLock cObjectCreationLock(&m_ObjectCreationLock);
  584.  
  585.     // Should only ever be called with zero
  586.     ASSERT(n == 0);
  587.  
  588.     if (n != 0) {
  589.         return NULL;
  590.     }
  591.  
  592.     // Create the input pin if not already done so
  593.  
  594.     if (m_pInputPin == NULL) {
  595.  
  596.         // hr must be initialized to NOERROR because
  597.         // CRendererInputPin's constructor only changes
  598.         // hr's value if an error occurs.
  599.         HRESULT hr = NOERROR;
  600.  
  601.         m_pInputPin = new CRendererInputPin(this,&hr,L"In");
  602.         if (NULL == m_pInputPin) {
  603.             return NULL;
  604.         }
  605.  
  606.         if (FAILED(hr)) {
  607.             delete m_pInputPin;
  608.             m_pInputPin = NULL;
  609.             return NULL;
  610.         }
  611.     }
  612.     return m_pInputPin;
  613. }
  614.  
  615.  
  616. // If "In" then return the IPin for our input pin, otherwise NULL and error
  617.  
  618. STDMETHODIMP CBaseRenderer::FindPin(LPCWSTR Id, IPin **ppPin)
  619. {
  620.     CheckPointer(ppPin,E_POINTER);
  621.  
  622.     if (0==lstrcmpW(Id,L"In")) {
  623.         *ppPin = GetPin(0);
  624.         ASSERT(*ppPin);
  625.         (*ppPin)->AddRef();
  626.     } else {
  627.         *ppPin = NULL;
  628.         return VFW_E_NOT_FOUND;
  629.     }
  630.     return NOERROR;
  631. }
  632.  
  633.  
  634. // Called when the input pin receives an EndOfStream notification. If we have
  635. // not got a sample, then notify EC_COMPLETE now. If we have samples, then set
  636. // m_bEOS and check for this on completing samples. If we're waiting to pause
  637. // then complete the transition to paused state by setting the state event
  638.  
  639. HRESULT CBaseRenderer::EndOfStream()
  640. {
  641.     // Ignore these calls if we are stopped
  642.  
  643.     if (m_State == State_Stopped) {
  644.         return NOERROR;
  645.     }
  646.  
  647.     // If we have a sample then wait for it to be rendered
  648.  
  649.     m_bEOS = TRUE;
  650.     if (m_pMediaSample) {
  651.         return NOERROR;
  652.     }
  653.  
  654.     // If we are waiting for pause then we are now ready since we cannot now
  655.     // carry on waiting for a sample to arrive since we are being told there
  656.     // won't be any. This sets an event that the GetState function picks up
  657.  
  658.     Ready();
  659.  
  660.     // Only signal completion now if we are running otherwise queue it until
  661.     // we do run in StartStreaming. This is used when we seek because a seek
  662.     // causes a pause where early notification of completion is misleading
  663.  
  664.     if (m_bStreaming) {
  665.         SendEndOfStream();
  666.     }
  667.     return NOERROR;
  668. }
  669.  
  670.  
  671. // When we are told to flush we should release the source thread
  672.  
  673. HRESULT CBaseRenderer::BeginFlush()
  674. {
  675.     // If paused then report state intermediate until we get some data
  676.  
  677.     if (m_State == State_Paused) {
  678.         NotReady();
  679.     }
  680.  
  681.     SourceThreadCanWait(FALSE);
  682.     CancelNotification();
  683.     ClearPendingSample();
  684.     //  Wait for Receive to complete
  685.     WaitForReceiveToComplete();
  686.  
  687.     return NOERROR;
  688. }
  689.  
  690.  
  691. // After flushing the source thread can wait in Receive again
  692.  
  693. HRESULT CBaseRenderer::EndFlush()
  694. {
  695.     // Reset the current sample media time
  696.     if (m_pPosition) m_pPosition->ResetMediaTime();
  697.  
  698.     // There should be no outstanding advise
  699.  
  700.     ASSERT(CancelNotification() == S_FALSE);
  701.     SourceThreadCanWait(TRUE);
  702.     return NOERROR;
  703. }
  704.  
  705.  
  706. // We can now send EC_REPAINTs if so required
  707.  
  708. HRESULT CBaseRenderer::CompleteConnect(IPin *pReceivePin)
  709. {
  710.     // The caller should always hold the interface lock because
  711.     // the function uses CBaseFilter::m_State.
  712.     ASSERT(CritCheckIn(&m_InterfaceLock));
  713.  
  714.     m_bAbort = FALSE;
  715.  
  716.     if (State_Running == GetRealState()) {
  717.         HRESULT hr = StartStreaming();
  718.         if (FAILED(hr)) {
  719.             return hr;
  720.         }
  721.  
  722.         SetRepaintStatus(FALSE);
  723.     } else {
  724.         SetRepaintStatus(TRUE);
  725.     }
  726.  
  727.     return NOERROR;
  728. }
  729.  
  730.  
  731. // Called when we go paused or running
  732.  
  733. HRESULT CBaseRenderer::Active()
  734. {
  735.     return NOERROR;
  736. }
  737.  
  738.  
  739. // Called when we go into a stopped state
  740.  
  741. HRESULT CBaseRenderer::Inactive()
  742. {
  743.     if (m_pPosition) {
  744.         m_pPosition->ResetMediaTime();
  745.     }
  746.     //  People who derive from this may want to override this behaviour
  747.     //  to keep hold of the sample in some circumstances
  748.     ClearPendingSample();
  749.  
  750.     return NOERROR;
  751. }
  752.  
  753.  
  754. // Tell derived classes about the media type agreed
  755.  
  756. HRESULT CBaseRenderer::SetMediaType(const CMediaType *pmt)
  757. {
  758.     return NOERROR;
  759. }
  760.  
  761.  
  762. // When we break the input pin connection we should reset the EOS flags. When
  763. // we are asked for either IMediaPosition or IMediaSeeking we will create a
  764. // CPosPassThru object to handles media time pass through. When we're handed
  765. // samples we store (by calling CPosPassThru::RegisterMediaTime) their media
  766. // times so we can then return a real current position of data being rendered
  767.  
  768. HRESULT CBaseRenderer::BreakConnect()
  769. {
  770.     // Do we have a quality management sink
  771.  
  772.     if (m_pQSink) {
  773.         m_pQSink->Release();
  774.         m_pQSink = NULL;
  775.     }
  776.  
  777.     // Check we have a valid connection
  778.  
  779.     if (m_pInputPin->IsConnected() == FALSE) {
  780.         return S_FALSE;
  781.     }
  782.  
  783.     // Check we are stopped before disconnecting
  784.     if (m_State != State_Stopped && !m_pInputPin->CanReconnectWhenActive()) {
  785.         return VFW_E_NOT_STOPPED;
  786.     }
  787.  
  788.     SetRepaintStatus(FALSE);
  789.     ResetEndOfStream();
  790.     ClearPendingSample();
  791.     m_bAbort = FALSE;
  792.  
  793.     if (State_Running == m_State) {
  794.         StopStreaming();
  795.     }
  796.  
  797.     return NOERROR;
  798. }
  799.  
  800.  
  801. // Retrieves the sample times for this samples (note the sample times are
  802. // passed in by reference not value). We return S_FALSE to say schedule this
  803. // sample according to the times on the sample. We also return S_OK in
  804. // which case the object should simply render the sample data immediately
  805.  
  806. HRESULT CBaseRenderer::GetSampleTimes(IMediaSample *pMediaSample,
  807.                                       REFERENCE_TIME *pStartTime,
  808.                                       REFERENCE_TIME *pEndTime)
  809. {
  810.     ASSERT(m_dwAdvise == 0);
  811.     ASSERT(pMediaSample);
  812.  
  813.     // If the stop time for this sample is before or the same as start time,
  814.     // then just ignore it (release it) and schedule the next one in line
  815.     // Source filters should always fill in the start and end times properly!
  816.  
  817.     if (SUCCEEDED(pMediaSample->GetTime(pStartTime, pEndTime))) {
  818.         if (*pEndTime < *pStartTime) {
  819.             return VFW_E_START_TIME_AFTER_END;
  820.         }
  821.     } else {
  822.         // no time set in the sample... draw it now?
  823.         return S_OK;
  824.     }
  825.  
  826.     // Can't synchronise without a clock so we return S_OK which tells the
  827.     // caller that the sample should be rendered immediately without going
  828.     // through the overhead of setting a timer advise link with the clock
  829.  
  830.     if (m_pClock == NULL) {
  831.         return S_OK;
  832.     }
  833.     return ShouldDrawSampleNow(pMediaSample,pStartTime,pEndTime);
  834. }
  835.  
  836.  
  837. // By default all samples are drawn according to their time stamps so we
  838. // return S_FALSE. Returning S_OK means draw immediately, this is used
  839. // by the derived video renderer class in its quality management.
  840.  
  841. HRESULT CBaseRenderer::ShouldDrawSampleNow(IMediaSample *pMediaSample,
  842.                                            REFERENCE_TIME *ptrStart,
  843.                                            REFERENCE_TIME *ptrEnd)
  844. {
  845.     return S_FALSE;
  846. }
  847.  
  848.  
  849. // We must always reset the current advise time to zero after a timer fires
  850. // because there are several possible ways which lead us not to do any more
  851. // scheduling such as the pending image being cleared after state changes
  852.  
  853. void CBaseRenderer::SignalTimerFired()
  854. {
  855.     m_dwAdvise = 0;
  856. }
  857.  
  858.  
  859. // Cancel any notification currently scheduled. This is called by the owning
  860. // window object when it is told to stop streaming. If there is no timer link
  861. // outstanding then calling this is benign otherwise we go ahead and cancel
  862. // We must always reset the render event as the quality management code can
  863. // signal immediate rendering by setting the event without setting an advise
  864. // link. If we're subsequently stopped and run the first attempt to setup an
  865. // advise link with the reference clock will find the event still signalled
  866.  
  867. HRESULT CBaseRenderer::CancelNotification()
  868. {
  869.     ASSERT(m_dwAdvise == 0 || m_pClock);
  870.     DWORD_PTR dwAdvise = m_dwAdvise;
  871.  
  872.     // Have we a live advise link
  873.  
  874.     if (m_dwAdvise) {
  875.         m_pClock->Unadvise(m_dwAdvise);
  876.         SignalTimerFired();
  877.         ASSERT(m_dwAdvise == 0);
  878.     }
  879.  
  880.     // Clear the event and return our status
  881.  
  882.     m_RenderEvent.Reset();
  883.     return (dwAdvise ? S_OK : S_FALSE);
  884. }
  885.  
  886.  
  887. // Responsible for setting up one shot advise links with the clock
  888. // Return FALSE if the sample is to be dropped (not drawn at all)
  889. // Return TRUE if the sample is to be drawn and in this case also
  890. // arrange for m_RenderEvent to be set at the appropriate time
  891.  
  892. BOOL CBaseRenderer::ScheduleSample(IMediaSample *pMediaSample)
  893. {
  894.     REFERENCE_TIME StartSample, EndSample;
  895.  
  896.     // Is someone pulling our leg
  897.  
  898.     if (pMediaSample == NULL) {
  899.         return FALSE;
  900.     }
  901.  
  902.     // Get the next sample due up for rendering.  If there aren't any ready
  903.     // then GetNextSampleTimes returns an error.  If there is one to be done
  904.     // then it succeeds and yields the sample times. If it is due now then
  905.     // it returns S_OK other if it's to be done when due it returns S_FALSE
  906.  
  907.     HRESULT hr = GetSampleTimes(pMediaSample, &StartSample, &EndSample);
  908.     if (FAILED(hr)) {
  909.         return FALSE;
  910.     }
  911.  
  912.     // If we don't have a reference clock then we cannot set up the advise
  913.     // time so we simply set the event indicating an image to render. This
  914.     // will cause us to run flat out without any timing or synchronisation
  915.  
  916.     if (hr == S_OK) {
  917.         EXECUTE_ASSERT(SetEvent((HANDLE) m_RenderEvent));
  918.         return TRUE;
  919.     }
  920.  
  921.     ASSERT(m_dwAdvise == 0);
  922.     ASSERT(m_pClock);
  923.     ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent,0));
  924.  
  925.     // We do have a valid reference clock interface so we can ask it to
  926.     // set an event when the image comes due for rendering. We pass in
  927.     // the reference time we were told to start at and also the current
  928.     // stream time which is the offset from the start reference time
  929.  
  930.     hr = m_pClock->AdviseTime(
  931.             (REFERENCE_TIME) m_tStart,          // Start run time
  932.             StartSample,                        // Stream time
  933.             (HEVENT)(HANDLE) m_RenderEvent,     // Render notification
  934.             &m_dwAdvise);                       // Advise cookie
  935.  
  936.     if (SUCCEEDED(hr)) {
  937.         return TRUE;
  938.     }
  939.  
  940.     // We could not schedule the next sample for rendering despite the fact
  941.     // we have a valid sample here. This is a fair indication that either
  942.     // the system clock is wrong or the time stamp for the sample is duff
  943.  
  944.     ASSERT(m_dwAdvise == 0);
  945.     return FALSE;
  946. }
  947.  
  948.  
  949. // This is called when a sample comes due for rendering. We pass the sample
  950. // on to the derived class. After rendering we will initialise the timer for
  951. // the next sample, NOTE signal that the last one fired first, if we don't
  952. // do this it thinks there is still one outstanding that hasn't completed
  953.  
  954. HRESULT CBaseRenderer::Render(IMediaSample *pMediaSample)
  955. {
  956.     // If the media sample is NULL then we will have been notified by the
  957.     // clock that another sample is ready but in the mean time someone has
  958.     // stopped us streaming which causes the next sample to be released
  959.  
  960.     if (pMediaSample == NULL) {
  961.         return S_FALSE;
  962.     }
  963.  
  964.     // If we have stopped streaming then don't render any more samples, the
  965.     // thread that got in and locked us and then reset this flag does not
  966.     // clear the pending sample as we can use it to refresh any output device
  967.  
  968.     if (m_bStreaming == FALSE) {
  969.         return S_FALSE;
  970.     }
  971.  
  972.     // Time how long the rendering takes
  973.  
  974.     OnRenderStart(pMediaSample);
  975.     DoRenderSample(pMediaSample);
  976.     OnRenderEnd(pMediaSample);
  977.  
  978.     return NOERROR;
  979. }
  980.  
  981.  
  982. // Checks if there is a sample waiting at the renderer
  983.  
  984. BOOL CBaseRenderer::HaveCurrentSample()
  985. {
  986.     CAutoLock cRendererLock(&m_RendererLock);
  987.     return (m_pMediaSample == NULL ? FALSE : TRUE);
  988. }
  989.  
  990.  
  991. // Returns the current sample waiting at the video renderer. We AddRef the
  992. // sample before returning so that should it come due for rendering the
  993. // person who called this method will hold the remaining reference count
  994. // that will stop the sample being added back onto the allocator free list
  995.  
  996. IMediaSample *CBaseRenderer::GetCurrentSample()
  997. {
  998.     CAutoLock cRendererLock(&m_RendererLock);
  999.     if (m_pMediaSample) {
  1000.         m_pMediaSample->AddRef();
  1001.     }
  1002.     return m_pMediaSample;
  1003. }
  1004.  
  1005.  
  1006. // Called when the source delivers us a sample. We go through a few checks to
  1007. // make sure the sample can be rendered. If we are running (streaming) then we
  1008. // have the sample scheduled with the reference clock, if we are not streaming
  1009. // then we have received an sample in paused mode so we can complete any state
  1010. // transition. On leaving this function everything will be unlocked so an app
  1011. // thread may get in and change our state to stopped (for example) in which
  1012. // case it will also signal the thread event so that our wait call is stopped
  1013.  
  1014. HRESULT CBaseRenderer::PrepareReceive(IMediaSample *pMediaSample)
  1015. {
  1016.     CAutoLock cInterfaceLock(&m_InterfaceLock);
  1017.     m_bInReceive = TRUE;
  1018.  
  1019.     // Check our flushing and filter state
  1020.  
  1021.     // This function must hold the interface lock because it calls 
  1022.     // CBaseInputPin::Receive() and CBaseInputPin::Receive() uses
  1023.     // CBasePin::m_bRunTimeError.
  1024.     HRESULT hr = m_pInputPin->CBaseInputPin::Receive(pMediaSample);
  1025.  
  1026.     if (hr != NOERROR) {
  1027.         m_bInReceive = FALSE;
  1028.         return E_FAIL;
  1029.     }
  1030.  
  1031.     // Has the type changed on a media sample. We do all rendering
  1032.     // synchronously on the source thread, which has a side effect
  1033.     // that only one buffer is ever outstanding. Therefore when we
  1034.     // have Receive called we can go ahead and change the format
  1035.     // Since the format change can cause a SendMessage we just don't
  1036.     // lock
  1037.     if (m_pInputPin->SampleProps()->pMediaType) {
  1038.         hr = m_pInputPin->SetMediaType(
  1039.                 (CMediaType *)m_pInputPin->SampleProps()->pMediaType);
  1040.         if (FAILED(hr)) {
  1041.             m_bInReceive = FALSE;
  1042.             return hr;
  1043.         }
  1044.     }
  1045.  
  1046.  
  1047.     CAutoLock cSampleLock(&m_RendererLock);
  1048.  
  1049.     ASSERT(IsActive() == TRUE);
  1050.     ASSERT(m_pInputPin->IsFlushing() == FALSE);
  1051.     ASSERT(m_pInputPin->IsConnected() == TRUE);
  1052.     ASSERT(m_pMediaSample == NULL);
  1053.  
  1054.     // Return an error if we already have a sample waiting for rendering
  1055.     // source pins must serialise the Receive calls - we also check that
  1056.     // no data is being sent after the source signalled an end of stream
  1057.  
  1058.     if (m_pMediaSample || m_bEOS || m_bAbort) {
  1059.         Ready();
  1060.         m_bInReceive = FALSE;
  1061.         return E_UNEXPECTED;
  1062.     }
  1063.  
  1064.     // Store the media times from this sample
  1065.     if (m_pPosition) m_pPosition->RegisterMediaTime(pMediaSample);
  1066.  
  1067.     // Schedule the next sample if we are streaming
  1068.  
  1069.     if ((m_bStreaming == TRUE) && (ScheduleSample(pMediaSample) == FALSE)) {
  1070.         ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent,0));
  1071.         ASSERT(CancelNotification() == S_FALSE);
  1072.         m_bInReceive = FALSE;
  1073.         return VFW_E_SAMPLE_REJECTED;
  1074.     }
  1075.  
  1076.     // Store the sample end time for EC_COMPLETE handling
  1077.     m_SignalTime = m_pInputPin->SampleProps()->tStop;
  1078.  
  1079.     // BEWARE we sometimes keep the sample even after returning the thread to
  1080.     // the source filter such as when we go into a stopped state (we keep it
  1081.     // to refresh the device with) so we must AddRef it to keep it safely. If
  1082.     // we start flushing the source thread is released and any sample waiting
  1083.     // will be released otherwise GetBuffer may never return (see BeginFlush)
  1084.  
  1085.     m_pMediaSample = pMediaSample;
  1086.     m_pMediaSample->AddRef();
  1087.  
  1088.     if (m_bStreaming == FALSE) {
  1089.         SetRepaintStatus(TRUE);
  1090.     }
  1091.     return NOERROR;
  1092. }
  1093.  
  1094.  
  1095. // Called by the source filter when we have a sample to render. Under normal
  1096. // circumstances we set an advise link with the clock, wait for the time to
  1097. // arrive and then render the data using the PURE virtual DoRenderSample that
  1098. // the derived class will have overriden. After rendering the sample we may
  1099. // also signal EOS if it was the last one sent before EndOfStream was called
  1100.  
  1101. HRESULT CBaseRenderer::Receive(IMediaSample *pSample)
  1102. {
  1103.     ASSERT(pSample);
  1104.  
  1105.     // It may return VFW_E_SAMPLE_REJECTED code to say don't bother
  1106.  
  1107.     HRESULT hr = PrepareReceive(pSample);
  1108.     ASSERT(m_bInReceive == SUCCEEDED(hr));
  1109.     if (FAILED(hr)) {
  1110.         if (hr == VFW_E_SAMPLE_REJECTED) {
  1111.             return NOERROR;
  1112.         }
  1113.         return hr;
  1114.     }
  1115.  
  1116.     // We realize the palette in "PrepareRender()" so we have to give away the
  1117.     // filter lock here.
  1118.     if (m_State == State_Paused) {
  1119.         PrepareRender();
  1120.         // no need to use InterlockedExchange
  1121.         m_bInReceive = FALSE;
  1122.         {
  1123.             // We must hold both these locks
  1124.             CAutoLock cRendererLock(&m_InterfaceLock);
  1125.             if (m_State == State_Stopped)
  1126.                 return NOERROR;
  1127.  
  1128.             m_bInReceive = TRUE;
  1129.             CAutoLock cSampleLock(&m_RendererLock);
  1130.             OnReceiveFirstSample(pSample);
  1131.         }
  1132.         Ready();
  1133.     }
  1134.     // Having set an advise link with the clock we sit and wait. We may be
  1135.     // awoken by the clock firing or by a state change. The rendering call
  1136.     // will lock the critical section and check we can still render the data
  1137.  
  1138.     hr = WaitForRenderTime();
  1139.     if (FAILED(hr)) {
  1140.         m_bInReceive = FALSE;
  1141.         return NOERROR;
  1142.     }
  1143.  
  1144.     PrepareRender();
  1145.  
  1146.     //  Set this here and poll it until we work out the locking correctly
  1147.     //  It can't be right that the streaming stuff grabs the interface
  1148.     //  lock - after all we want to be able to wait for this stuff
  1149.     //  to complete
  1150.     m_bInReceive = FALSE;
  1151.  
  1152.     // We must hold both these locks
  1153.     CAutoLock cRendererLock(&m_InterfaceLock);
  1154.  
  1155.     // since we gave away the filter wide lock, the sate of the filter could
  1156.     // have chnaged to Stopped
  1157.     if (m_State == State_Stopped)
  1158.         return NOERROR;
  1159.  
  1160.     CAutoLock cSampleLock(&m_RendererLock);
  1161.  
  1162.     // Deal with this sample
  1163.  
  1164.     Render(m_pMediaSample);
  1165.     ClearPendingSample();
  1166.     SendEndOfStream();
  1167.     CancelNotification();
  1168.     return NOERROR;
  1169. }
  1170.  
  1171.  
  1172. // This is called when we stop or are inactivated to clear the pending sample
  1173. // We release the media sample interface so that they can be allocated to the
  1174. // source filter again, unless of course we are changing state to inactive in
  1175. // which case GetBuffer will return an error. We must also reset the current
  1176. // media sample to NULL so that we know we do not currently have an image
  1177.  
  1178. HRESULT CBaseRenderer::ClearPendingSample()
  1179. {
  1180.     CAutoLock cRendererLock(&m_RendererLock);
  1181.     if (m_pMediaSample) {
  1182.         m_pMediaSample->Release();
  1183.         m_pMediaSample = NULL;
  1184.     }
  1185.     return NOERROR;
  1186. }
  1187.  
  1188.  
  1189. // Used to signal end of stream according to the sample end time
  1190.  
  1191. void CALLBACK EndOfStreamTimer(UINT uID,        // Timer identifier
  1192.                                UINT uMsg,       // Not currently used
  1193.                                DWORD_PTR dwUser,// User information
  1194.                                DWORD_PTR dw1,   // Windows reserved
  1195.                                DWORD_PTR dw2)   // is also reserved
  1196. {
  1197.     CBaseRenderer *pRenderer = (CBaseRenderer *) dwUser;
  1198.     NOTE1("EndOfStreamTimer called (%d)",uID);
  1199.     pRenderer->TimerCallback();
  1200. }
  1201.  
  1202. //  Do the timer callback work
  1203. void CBaseRenderer::TimerCallback()
  1204. {
  1205.     //  Lock for synchronization (but don't hold this lock when calling
  1206.     //  timeKillEvent)
  1207.     CAutoLock cRendererLock(&m_RendererLock);
  1208.  
  1209.     // See if we should signal end of stream now
  1210.  
  1211.     if (m_EndOfStreamTimer) {
  1212.         m_EndOfStreamTimer = 0;
  1213.         SendEndOfStream();
  1214.     }
  1215. }
  1216.  
  1217.  
  1218. // If we are at the end of the stream signal the filter graph but do not set
  1219. // the state flag back to FALSE. Once we drop off the end of the stream we
  1220. // leave the flag set (until a subsequent ResetEndOfStream). Each sample we
  1221. // get delivered will update m_SignalTime to be the last sample's end time.
  1222. // We must wait this long before signalling end of stream to the filtergraph
  1223.  
  1224. #define TIMEOUT_DELIVERYWAIT 50
  1225. #define TIMEOUT_RESOLUTION 10
  1226.  
  1227. HRESULT CBaseRenderer::SendEndOfStream()
  1228. {
  1229.     ASSERT(CritCheckIn(&m_RendererLock));
  1230.     if (m_bEOS == FALSE || m_bEOSDelivered || m_EndOfStreamTimer) {
  1231.         return NOERROR;
  1232.     }
  1233.  
  1234.     // If there is no clock then signal immediately
  1235.     if (m_pClock == NULL) {
  1236.         return NotifyEndOfStream();
  1237.     }
  1238.  
  1239.     // How long into the future is the delivery time
  1240.  
  1241.     REFERENCE_TIME Signal = m_tStart + m_SignalTime;
  1242.     REFERENCE_TIME CurrentTime;
  1243.     m_pClock->GetTime(&CurrentTime);
  1244.     LONG Delay = LONG((Signal - CurrentTime) / 10000);
  1245.  
  1246.     // Dump the timing information to the debugger
  1247.  
  1248.     NOTE1("Delay until end of stream delivery %d",Delay);
  1249.     NOTE1("Current %s",(LPCTSTR)CDisp((LONGLONG)CurrentTime));
  1250.     NOTE1("Signal %s",(LPCTSTR)CDisp((LONGLONG)Signal));
  1251.  
  1252.     // Wait for the delivery time to arrive
  1253.  
  1254.     if (Delay < TIMEOUT_DELIVERYWAIT) {
  1255.         return NotifyEndOfStream();
  1256.     }
  1257.  
  1258.     // Signal a timer callback on another worker thread
  1259.  
  1260.     m_EndOfStreamTimer = CompatibleTimeSetEvent((UINT) Delay, // Period of timer
  1261.                                       TIMEOUT_RESOLUTION,     // Timer resolution
  1262.                                       EndOfStreamTimer,       // Callback function
  1263.                                       DWORD_PTR(this),        // Used information
  1264.                                       TIME_ONESHOT);          // Type of callback
  1265.     if (m_EndOfStreamTimer == 0) {
  1266.         return NotifyEndOfStream();
  1267.     }
  1268.     return NOERROR;
  1269. }
  1270.  
  1271.  
  1272. // Signals EC_COMPLETE to the filtergraph manager
  1273.  
  1274. HRESULT CBaseRenderer::NotifyEndOfStream()
  1275. {
  1276.     CAutoLock cRendererLock(&m_RendererLock);
  1277.     ASSERT(m_bEOSDelivered == FALSE);
  1278.     ASSERT(m_EndOfStreamTimer == 0);
  1279.  
  1280.     // Has the filter changed state
  1281.  
  1282.     if (m_bStreaming == FALSE) {
  1283.         ASSERT(m_EndOfStreamTimer == 0);
  1284.         return NOERROR;
  1285.     }
  1286.  
  1287.     // Reset the end of stream timer
  1288.     m_EndOfStreamTimer = 0;
  1289.  
  1290.     // If we've been using the IMediaPosition interface, set it's start
  1291.     // and end media "times" to the stop position by hand.  This ensures
  1292.     // that we actually get to the end, even if the MPEG guestimate has
  1293.     // been bad or if the quality management dropped the last few frames
  1294.  
  1295.     if (m_pPosition) m_pPosition->EOS();
  1296.     m_bEOSDelivered = TRUE;
  1297.     NOTE("Sending EC_COMPLETE...");
  1298.     return NotifyEvent(EC_COMPLETE,S_OK,(LONG_PTR)(IBaseFilter *)this);
  1299. }
  1300.  
  1301.  
  1302. // Reset the end of stream flag, this is typically called when we transfer to
  1303. // stopped states since that resets the current position back to the start so
  1304. // we will receive more samples or another EndOfStream if there aren't any. We
  1305. // keep two separate flags one to say we have run off the end of the stream
  1306. // (this is the m_bEOS flag) and another to say we have delivered EC_COMPLETE
  1307. // to the filter graph. We need the latter otherwise we can end up sending an
  1308. // EC_COMPLETE every time the source changes state and calls our EndOfStream
  1309.  
  1310. HRESULT CBaseRenderer::ResetEndOfStream()
  1311. {
  1312.     ResetEndOfStreamTimer();
  1313.     CAutoLock cRendererLock(&m_RendererLock);
  1314.  
  1315.     m_bEOS = FALSE;
  1316.     m_bEOSDelivered = FALSE;
  1317.     m_SignalTime = 0;
  1318.  
  1319.     return NOERROR;
  1320. }
  1321.  
  1322.  
  1323. // Kills any outstanding end of stream timer
  1324.  
  1325. void CBaseRenderer::ResetEndOfStreamTimer()
  1326. {
  1327.     ASSERT(CritCheckOut(&m_RendererLock));
  1328.     if (m_EndOfStreamTimer) {
  1329.         timeKillEvent(m_EndOfStreamTimer);
  1330.         m_EndOfStreamTimer = 0;
  1331.     }
  1332. }
  1333.  
  1334.  
  1335. // This is called when we start running so that we can schedule any pending
  1336. // image we have with the clock and display any timing information. If we
  1337. // don't have any sample but we have queued an EOS flag then we send it. If
  1338. // we do have a sample then we wait until that has been rendered before we
  1339. // signal the filter graph otherwise we may change state before it's done
  1340.  
  1341. HRESULT CBaseRenderer::StartStreaming()
  1342. {
  1343.     CAutoLock cRendererLock(&m_RendererLock);
  1344.     if (m_bStreaming == TRUE) {
  1345.         return NOERROR;
  1346.     }
  1347.  
  1348.     // Reset the streaming times ready for running
  1349.  
  1350.     m_bStreaming = TRUE;
  1351.  
  1352.     timeBeginPeriod(1);
  1353.     OnStartStreaming();
  1354.  
  1355.     // There should be no outstanding advise
  1356.     ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent,0));
  1357.     ASSERT(CancelNotification() == S_FALSE);
  1358.  
  1359.     // If we have an EOS and no data then deliver it now
  1360.  
  1361.     if (m_pMediaSample == NULL) {
  1362.         return SendEndOfStream();
  1363.     }
  1364.  
  1365.     // Have the data rendered
  1366.  
  1367.     ASSERT(m_pMediaSample);
  1368.     if (!ScheduleSample(m_pMediaSample))
  1369.         m_RenderEvent.Set();
  1370.  
  1371.     return NOERROR;
  1372. }
  1373.  
  1374.  
  1375. // This is called when we stop streaming so that we can set our internal flag
  1376. // indicating we are not now to schedule any more samples arriving. The state
  1377. // change methods in the filter implementation take care of cancelling any
  1378. // clock advise link we have set up and clearing any pending sample we have
  1379.  
  1380. HRESULT CBaseRenderer::StopStreaming()
  1381. {
  1382.     CAutoLock cRendererLock(&m_RendererLock);
  1383.     m_bEOSDelivered = FALSE;
  1384.  
  1385.     if (m_bStreaming == TRUE) {
  1386.         m_bStreaming = FALSE;
  1387.         OnStopStreaming();
  1388.         timeEndPeriod(1);
  1389.     }
  1390.     return NOERROR;
  1391. }
  1392.  
  1393.  
  1394. // We have a boolean flag that is reset when we have signalled EC_REPAINT to
  1395. // the filter graph. We set this when we receive an image so that should any
  1396. // conditions arise again we can send another one. By having a flag we ensure
  1397. // we don't flood the filter graph with redundant calls. We do not set the
  1398. // event when we receive an EndOfStream call since there is no point in us
  1399. // sending further EC_REPAINTs. In particular the AutoShowWindow method and
  1400. // the DirectDraw object use this method to control the window repainting
  1401.  
  1402. void CBaseRenderer::SetRepaintStatus(BOOL bRepaint)
  1403. {
  1404.     CAutoLock cSampleLock(&m_RendererLock);
  1405.     m_bRepaintStatus = bRepaint;
  1406. }
  1407.  
  1408.  
  1409. // Pass the window handle to the upstream filter
  1410.  
  1411. void CBaseRenderer::SendNotifyWindow(IPin *pPin,HWND hwnd)
  1412. {
  1413.     IMediaEventSink *pSink;
  1414.  
  1415.     // Does the pin support IMediaEventSink
  1416.     HRESULT hr = pPin->QueryInterface(IID_IMediaEventSink,(void **)&pSink);
  1417.     if (SUCCEEDED(hr)) {
  1418.         pSink->Notify(EC_NOTIFY_WINDOW,LONG_PTR(hwnd),0);
  1419.         pSink->Release();
  1420.     }
  1421.     NotifyEvent(EC_NOTIFY_WINDOW,LONG_PTR(hwnd),0);
  1422. }
  1423.  
  1424.  
  1425. // Signal an EC_REPAINT to the filter graph. This can be used to have data
  1426. // sent to us. For example when a video window is first displayed it may
  1427. // not have an image to display, at which point it signals EC_REPAINT. The
  1428. // filtergraph will either pause the graph if stopped or if already paused
  1429. // it will call put_CurrentPosition of the current position. Setting the
  1430. // current position to itself has the stream flushed and the image resent
  1431.  
  1432. #define RLOG(_x_) DbgLog((LOG_TRACE,1,TEXT(_x_)));
  1433.  
  1434. void CBaseRenderer::SendRepaint()
  1435. {
  1436.     CAutoLock cSampleLock(&m_RendererLock);
  1437.     ASSERT(m_pInputPin);
  1438.  
  1439.     // We should not send repaint notifications when...
  1440.     //    - An end of stream has been notified
  1441.     //    - Our input pin is being flushed
  1442.     //    - The input pin is not connected
  1443.     //    - We have aborted a video playback
  1444.     //    - There is a repaint already sent
  1445.  
  1446.     if (m_bAbort == FALSE) {
  1447.         if (m_pInputPin->IsConnected() == TRUE) {
  1448.             if (m_pInputPin->IsFlushing() == FALSE) {
  1449.                 if (IsEndOfStream() == FALSE) {
  1450.                     if (m_bRepaintStatus == TRUE) {
  1451.                         IPin *pPin = (IPin *) m_pInputPin;
  1452.                         NotifyEvent(EC_REPAINT,(LONG_PTR) pPin,0);
  1453.                         SetRepaintStatus(FALSE);
  1454.                         RLOG("Sending repaint");
  1455.                     }
  1456.                 }
  1457.             }
  1458.         }
  1459.     }
  1460. }
  1461.  
  1462.  
  1463. // When a video window detects a display change (WM_DISPLAYCHANGE message) it
  1464. // can send an EC_DISPLAY_CHANGED event code along with the renderer pin. The
  1465. // filtergraph will stop everyone and reconnect our input pin. As we're then
  1466. // reconnected we can accept the media type that matches the new display mode
  1467. // since we may no longer be able to draw the current image type efficiently
  1468.  
  1469. BOOL CBaseRenderer::OnDisplayChange()
  1470. {
  1471.     // Ignore if we are not connected yet
  1472.  
  1473.     CAutoLock cSampleLock(&m_RendererLock);
  1474.     if (m_pInputPin->IsConnected() == FALSE) {
  1475.         return FALSE;
  1476.     }
  1477.  
  1478.     RLOG("Notification of EC_DISPLAY_CHANGE");
  1479.  
  1480.     // Pass our input pin as parameter on the event
  1481.  
  1482.     IPin *pPin = (IPin *) m_pInputPin;
  1483.     m_pInputPin->AddRef();
  1484.     NotifyEvent(EC_DISPLAY_CHANGED,(LONG_PTR) pPin,0);
  1485.     SetAbortSignal(TRUE);
  1486.     ClearPendingSample();
  1487.     m_pInputPin->Release();
  1488.  
  1489.     return TRUE;
  1490. }
  1491.  
  1492.  
  1493. // Called just before we start drawing.
  1494. // Store the current time in m_trRenderStart to allow the rendering time to be
  1495. // logged.  Log the time stamp of the sample and how late it is (neg is early)
  1496.  
  1497. void CBaseRenderer::OnRenderStart(IMediaSample *pMediaSample)
  1498. {
  1499. #ifdef PERF
  1500.     REFERENCE_TIME trStart, trEnd;
  1501.     pMediaSample->GetTime(&trStart, &trEnd);
  1502.  
  1503.     MSR_INTEGER(m_idBaseStamp, (int)trStart);     // dump low order 32 bits
  1504.  
  1505.     m_pClock->GetTime(&m_trRenderStart);
  1506.     MSR_INTEGER(0, (int)m_trRenderStart);
  1507.     REFERENCE_TIME trStream;
  1508.     trStream = m_trRenderStart-m_tStart;     // convert reftime to stream time
  1509.     MSR_INTEGER(0,(int)trStream);
  1510.  
  1511.     const int trLate = (int)(trStream - trStart);
  1512.     MSR_INTEGER(m_idBaseAccuracy, trLate/10000);  // dump in mSec
  1513. #endif
  1514.  
  1515. } // OnRenderStart
  1516.  
  1517.  
  1518. // Called directly after drawing an image.
  1519. // calculate the time spent drawing and log it.
  1520.  
  1521. void CBaseRenderer::OnRenderEnd(IMediaSample *pMediaSample)
  1522. {
  1523. #ifdef PERF
  1524.     REFERENCE_TIME trNow;
  1525.     m_pClock->GetTime(&trNow);
  1526.     MSR_INTEGER(0,(int)trNow);
  1527.     int t = (int)((trNow - m_trRenderStart)/10000);   // convert UNITS->msec
  1528.     MSR_INTEGER(m_idBaseRenderTime, t);
  1529. #endif
  1530. } // OnRenderEnd
  1531.  
  1532.  
  1533.  
  1534.  
  1535. // Constructor must be passed the base renderer object
  1536.  
  1537. CRendererInputPin::CRendererInputPin(CBaseRenderer *pRenderer,
  1538.                                      HRESULT *phr,
  1539.                                      LPCWSTR pPinName) :
  1540.     CBaseInputPin(NAME("Renderer pin"),
  1541.                   pRenderer,
  1542.                   &pRenderer->m_InterfaceLock,
  1543.                   (HRESULT *) phr,
  1544.                   pPinName)
  1545. {
  1546.     m_pRenderer = pRenderer;
  1547.     ASSERT(m_pRenderer);
  1548. }
  1549.  
  1550.  
  1551. // Signals end of data stream on the input pin
  1552.  
  1553. STDMETHODIMP CRendererInputPin::EndOfStream()
  1554. {
  1555.     CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock);
  1556.     CAutoLock cSampleLock(&m_pRenderer->m_RendererLock);
  1557.  
  1558.     // Make sure we're streaming ok
  1559.  
  1560.     HRESULT hr = CheckStreaming();
  1561.     if (hr != NOERROR) {
  1562.         return hr;
  1563.     }
  1564.  
  1565.     // Pass it onto the renderer
  1566.  
  1567.     hr = m_pRenderer->EndOfStream();
  1568.     if (SUCCEEDED(hr)) {
  1569.         hr = CBaseInputPin::EndOfStream();
  1570.     }
  1571.     return hr;
  1572. }
  1573.  
  1574.  
  1575. // Signals start of flushing on the input pin - we do the final reset end of
  1576. // stream with the renderer lock unlocked but with the interface lock locked
  1577. // We must do this because we call timeKillEvent, our timer callback method
  1578. // has to take the renderer lock to serialise our state. Therefore holding a
  1579. // renderer lock when calling timeKillEvent could cause a deadlock condition
  1580.  
  1581. STDMETHODIMP CRendererInputPin::BeginFlush()
  1582. {
  1583.     CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock);
  1584.     {
  1585.         CAutoLock cSampleLock(&m_pRenderer->m_RendererLock);
  1586.         CBaseInputPin::BeginFlush();
  1587.         m_pRenderer->BeginFlush();
  1588.     }
  1589.     return m_pRenderer->ResetEndOfStream();
  1590. }
  1591.  
  1592.  
  1593. // Signals end of flushing on the input pin
  1594.  
  1595. STDMETHODIMP CRendererInputPin::EndFlush()
  1596. {
  1597.     CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock);
  1598.     CAutoLock cSampleLock(&m_pRenderer->m_RendererLock);
  1599.  
  1600.     HRESULT hr = m_pRenderer->EndFlush();
  1601.     if (SUCCEEDED(hr)) {
  1602.         hr = CBaseInputPin::EndFlush();
  1603.     }
  1604.     return hr;
  1605. }
  1606.  
  1607.  
  1608. // Pass the sample straight through to the renderer object
  1609.  
  1610. STDMETHODIMP CRendererInputPin::Receive(IMediaSample *pSample)
  1611. {
  1612.     HRESULT hr = m_pRenderer->Receive(pSample);
  1613.     if (FAILED(hr)) {
  1614.  
  1615.         // A deadlock could occur if the caller holds the renderer lock and
  1616.         // attempts to acquire the interface lock.
  1617.         ASSERT(CritCheckOut(&m_pRenderer->m_RendererLock));
  1618.  
  1619.         {
  1620.             // The interface lock must be held when the filter is calling
  1621.             // IsStopped() or IsFlushing().  The interface lock must also
  1622.             // be held because the function uses m_bRunTimeError.
  1623.             CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock);
  1624.  
  1625.             // We do not report errors which occur while the filter is stopping,
  1626.             // flushing or if the m_bAbort flag is set .  Errors are expected to 
  1627.             // occur during these operations and the streaming thread correctly 
  1628.             // handles the errors.  
  1629.             if (!IsStopped() && !IsFlushing() && !m_pRenderer->m_bAbort && !m_bRunTimeError) {
  1630.  
  1631.                 // EC_ERRORABORT's first parameter is the error which caused
  1632.                 // the event and its' last parameter is 0.  See the Direct
  1633.                 // Show SDK documentation for more information.
  1634.                 m_pRenderer->NotifyEvent(EC_ERRORABORT,hr,0);
  1635.  
  1636.                 {
  1637.                     CAutoLock alRendererLock(&m_pRenderer->m_RendererLock);
  1638.                     if (m_pRenderer->IsStreaming() && !m_pRenderer->IsEndOfStreamDelivered()) {
  1639.                         m_pRenderer->NotifyEndOfStream();
  1640.                     }
  1641.                 }
  1642.     
  1643.                 m_bRunTimeError = TRUE;
  1644.             }
  1645.         }
  1646.     }
  1647.  
  1648.     return hr;
  1649. }
  1650.  
  1651.  
  1652. // Called when the input pin is disconnected
  1653.  
  1654. HRESULT CRendererInputPin::BreakConnect()
  1655. {
  1656.     HRESULT hr = m_pRenderer->BreakConnect();
  1657.     if (FAILED(hr)) {
  1658.         return hr;
  1659.     }
  1660.     return CBaseInputPin::BreakConnect();
  1661. }
  1662.  
  1663.  
  1664. // Called when the input pin is connected
  1665.  
  1666. HRESULT CRendererInputPin::CompleteConnect(IPin *pReceivePin)
  1667. {
  1668.     HRESULT hr = m_pRenderer->CompleteConnect(pReceivePin);
  1669.     if (FAILED(hr)) {
  1670.         return hr;
  1671.     }
  1672.     return CBaseInputPin::CompleteConnect(pReceivePin);
  1673. }
  1674.  
  1675.  
  1676. // Give the pin id of our one and only pin
  1677.  
  1678. STDMETHODIMP CRendererInputPin::QueryId(LPWSTR *Id)
  1679. {
  1680.     CheckPointer(Id,E_POINTER);
  1681.  
  1682.     *Id = (LPWSTR)CoTaskMemAlloc(8);
  1683.     if (*Id == NULL) {
  1684.         return E_OUTOFMEMORY;
  1685.     }
  1686.     lstrcpyW(*Id, L"In");
  1687.     return NOERROR;
  1688. }
  1689.  
  1690.  
  1691. // Will the filter accept this media type
  1692.  
  1693. HRESULT CRendererInputPin::CheckMediaType(const CMediaType *pmt)
  1694. {
  1695.     return m_pRenderer->CheckMediaType(pmt);
  1696. }
  1697.  
  1698.  
  1699. // Called when we go paused or running
  1700.  
  1701. HRESULT CRendererInputPin::Active()
  1702. {
  1703.     return m_pRenderer->Active();
  1704. }
  1705.  
  1706.  
  1707. // Called when we go into a stopped state
  1708.  
  1709. HRESULT CRendererInputPin::Inactive()
  1710. {
  1711.     // The caller must hold the interface lock because 
  1712.     // this function uses m_bRunTimeError.
  1713.     ASSERT(CritCheckIn(&m_pRenderer->m_InterfaceLock));
  1714.  
  1715.     m_bRunTimeError = FALSE;
  1716.  
  1717.     return m_pRenderer->Inactive();
  1718. }
  1719.  
  1720.  
  1721. // Tell derived classes about the media type agreed
  1722.  
  1723. HRESULT CRendererInputPin::SetMediaType(const CMediaType *pmt)
  1724. {
  1725.     HRESULT hr = CBaseInputPin::SetMediaType(pmt);
  1726.     if (FAILED(hr)) {
  1727.         return hr;
  1728.     }
  1729.     return m_pRenderer->SetMediaType(pmt);
  1730. }
  1731.  
  1732.  
  1733. // We do not keep an event object to use when setting up a timer link with
  1734. // the clock but are given a pointer to one by the owning object through the
  1735. // SetNotificationObject method - this must be initialised before starting
  1736. // We can override the default quality management process to have it always
  1737. // draw late frames, this is currently done by having the following registry
  1738. // key (actually an INI key) called DrawLateFrames set to 1 (default is 0)
  1739.  
  1740. const TCHAR AMQUALITY[] = TEXT("ActiveMovie");
  1741. const TCHAR DRAWLATEFRAMES[] = TEXT("DrawLateFrames");
  1742.  
  1743. CBaseVideoRenderer::CBaseVideoRenderer(
  1744.       REFCLSID RenderClass, // CLSID for this renderer
  1745.       TCHAR *pName,         // Debug ONLY description
  1746.       LPUNKNOWN pUnk,       // Aggregated owner object
  1747.       HRESULT *phr) :       // General OLE return code
  1748.  
  1749.     CBaseRenderer(RenderClass,pName,pUnk,phr),
  1750.     m_cFramesDropped(0),
  1751.     m_cFramesDrawn(0),
  1752.     m_bSupplierHandlingQuality(FALSE)
  1753. {
  1754.     ResetStreamingTimes();
  1755.  
  1756. #ifdef PERF
  1757.     m_idTimeStamp       = MSR_REGISTER(TEXT("Frame time stamp"));
  1758.     m_idEarliness       = MSR_REGISTER(TEXT("Earliness fudge"));
  1759.     m_idTarget          = MSR_REGISTER(TEXT("Target (mSec)"));
  1760.     m_idSchLateTime     = MSR_REGISTER(TEXT("mSec late when scheduled"));
  1761.     m_idDecision        = MSR_REGISTER(TEXT("Scheduler decision code"));
  1762.     m_idQualityRate     = MSR_REGISTER(TEXT("Quality rate sent"));
  1763.     m_idQualityTime     = MSR_REGISTER(TEXT("Quality time sent"));
  1764.     m_idWaitReal        = MSR_REGISTER(TEXT("Render wait"));
  1765.     // m_idWait            = MSR_REGISTER(TEXT("wait time recorded (msec)"));
  1766.     m_idFrameAccuracy   = MSR_REGISTER(TEXT("Frame accuracy (msecs)"));
  1767.     m_bDrawLateFrames = GetProfileInt(AMQUALITY, DRAWLATEFRAMES, FALSE);
  1768.     //m_idSendQuality      = MSR_REGISTER(TEXT("Processing Quality message"));
  1769.  
  1770.     m_idRenderAvg       = MSR_REGISTER(TEXT("Render draw time Avg"));
  1771.     m_idFrameAvg        = MSR_REGISTER(TEXT("FrameAvg"));
  1772.     m_idWaitAvg         = MSR_REGISTER(TEXT("WaitAvg"));
  1773.     m_idDuration        = MSR_REGISTER(TEXT("Duration"));
  1774.     m_idThrottle        = MSR_REGISTER(TEXT("Audio-video throttle wait"));
  1775.     // m_idDebug           = MSR_REGISTER(TEXT("Debug stuff"));
  1776. #endif // PERF
  1777. } // Constructor
  1778.  
  1779.  
  1780. // Destructor is just a placeholder
  1781.  
  1782. CBaseVideoRenderer::~CBaseVideoRenderer()
  1783. {
  1784.     ASSERT(m_dwAdvise == 0);
  1785. }
  1786.  
  1787.  
  1788. // The timing functions in this class are called by the window object and by
  1789. // the renderer's allocator.
  1790. // The windows object calls timing functions as it receives media sample
  1791. // images for drawing using GDI.
  1792. // The allocator calls timing functions when it starts passing DCI/DirectDraw
  1793. // surfaces which are not rendered in the same way; The decompressor writes
  1794. // directly to the surface with no separate rendering, so those code paths
  1795. // call direct into us.  Since we only ever hand out DCI/DirectDraw surfaces
  1796. // when we have allocated one and only one image we know there cannot be any
  1797. // conflict between the two.
  1798. //
  1799. // We use timeGetTime to return the timing counts we use (since it's relative
  1800. // performance we are interested in rather than absolute compared to a clock)
  1801. // The window object sets the accuracy of the system clock (normally 1ms) by
  1802. // calling timeBeginPeriod/timeEndPeriod when it changes streaming states
  1803.  
  1804.  
  1805. // Reset all times controlling streaming.
  1806. // Set them so that
  1807. // 1. Frames will not initially be dropped
  1808. // 2. The first frame will definitely be drawn (achieved by saying that there
  1809. //    has not ben a frame drawn for a long time).
  1810.  
  1811. HRESULT CBaseVideoRenderer::ResetStreamingTimes()
  1812. {
  1813.     m_trLastDraw = -1000;     // set up as first frame since ages (1 sec) ago
  1814.     m_tStreamingStart = timeGetTime();
  1815.     m_trRenderAvg = 0;
  1816.     m_trFrameAvg = -1;        // -1000 fps == "unset"
  1817.     m_trDuration = 0;         // 0 - strange value
  1818.     m_trRenderLast = 0;
  1819.     m_trWaitAvg = 0;
  1820.     m_tRenderStart = 0;
  1821.     m_cFramesDrawn = 0;
  1822.     m_cFramesDropped = 0;
  1823.     m_iTotAcc = 0;
  1824.     m_iSumSqAcc = 0;
  1825.     m_iSumSqFrameTime = 0;
  1826.     m_trFrame = 0;          // hygeine - not really needed
  1827.     m_trLate = 0;           // hygeine - not really needed
  1828.     m_iSumFrameTime = 0;
  1829.     m_nNormal = 0;
  1830.     m_trEarliness = 0;
  1831.     m_trTarget = -300000;  // 30mSec early
  1832.     m_trThrottle = 0;
  1833.     m_trRememberStampForPerf = 0;
  1834.  
  1835. #ifdef PERF
  1836.     m_trRememberFrameForPerf = 0;
  1837. #endif
  1838.  
  1839.     return NOERROR;
  1840. } // ResetStreamingTimes
  1841.  
  1842.  
  1843. // Reset all times controlling streaming. Note that we're now streaming. We
  1844. // don't need to set the rendering event to have the source filter released
  1845. // as it is done during the Run processing. When we are run we immediately
  1846. // release the source filter thread and draw any image waiting (that image
  1847. // may already have been drawn once as a poster frame while we were paused)
  1848.  
  1849. HRESULT CBaseVideoRenderer::OnStartStreaming()
  1850. {
  1851.     ResetStreamingTimes();
  1852.     return NOERROR;
  1853. } // OnStartStreaming
  1854.  
  1855.  
  1856. // Called at end of streaming.  Fixes times for property page report
  1857.  
  1858. HRESULT CBaseVideoRenderer::OnStopStreaming()
  1859. {
  1860.     m_tStreamingStart = timeGetTime()-m_tStreamingStart;
  1861.     return NOERROR;
  1862. } // OnStopStreaming
  1863.  
  1864.  
  1865. // Called when we start waiting for a rendering event.
  1866. // Used to update times spent waiting and not waiting.
  1867.  
  1868. void CBaseVideoRenderer::OnWaitStart()
  1869. {
  1870.     MSR_START(m_idWaitReal);
  1871. } // OnWaitStart
  1872.  
  1873.  
  1874. // Called when we are awoken from the wait in the window OR by our allocator
  1875. // when it is hanging around until the next sample is due for rendering on a
  1876. // DCI/DirectDraw surface. We add the wait time into our rolling average.
  1877. // We grab the interface lock so that we're serialised with the application
  1878. // thread going through the run code - which in due course ends up calling
  1879. // ResetStreaming times - possibly as we run through this section of code
  1880.  
  1881. void CBaseVideoRenderer::OnWaitEnd()
  1882. {
  1883. #ifdef PERF
  1884.     MSR_STOP(m_idWaitReal);
  1885.     // for a perf build we want to know just exactly how late we REALLY are.
  1886.     // even if this means that we have to look at the clock again.
  1887.  
  1888.     REFERENCE_TIME trRealStream;     // the real time now expressed as stream time.
  1889. #if 0
  1890.     m_pClock->GetTime(&trRealStream); // Calling clock here causes W95 deadlock!
  1891. #else
  1892.     // We will be discarding overflows like mad here!
  1893.     // This is wrong really because timeGetTime() can wrap but it's
  1894.     // only for PERF
  1895.     REFERENCE_TIME tr = timeGetTime()*10000;
  1896.     trRealStream = tr + m_llTimeOffset;
  1897. #endif
  1898.     trRealStream -= m_tStart;     // convert to stream time (this is a reftime)
  1899.  
  1900.     if (m_trRememberStampForPerf==0) {
  1901.         // This is probably the poster frame at the start, and it is not scheduled
  1902.         // in the usual way at all.  Just count it.  The rememberstamp gets set
  1903.         // in ShouldDrawSampleNow, so this does invalid frame recording until we
  1904.         // actually start playing.
  1905.         PreparePerformanceData(0, 0);
  1906.     } else {
  1907.         int trLate = (int)(trRealStream - m_trRememberStampForPerf);
  1908.         int trFrame = (int)(tr - m_trRememberFrameForPerf);
  1909.         PreparePerformanceData(trLate, trFrame);
  1910.     }
  1911.     m_trRememberFrameForPerf = tr;
  1912. #endif //PERF
  1913. } // OnWaitEnd
  1914.  
  1915.  
  1916. // Put data on one side that describes the lateness of the current frame.
  1917. // We don't yet know whether it will actually be drawn.  In direct draw mode,
  1918. // this decision is up to the filter upstream, and it could change its mind.
  1919. // The rules say that if it did draw it must call Receive().  One way or
  1920. // another we eventually get into either OnRenderStart or OnDirectRender and
  1921. // these both call RecordFrameLateness to update the statistics.
  1922.  
  1923. void CBaseVideoRenderer::PreparePerformanceData(int trLate, int trFrame)
  1924. {
  1925.     m_trLate = trLate;
  1926.     m_trFrame = trFrame;
  1927. } // PreparePerformanceData
  1928.  
  1929.  
  1930. // update the statistics:
  1931. // m_iTotAcc, m_iSumSqAcc, m_iSumSqFrameTime, m_iSumFrameTime, m_cFramesDrawn
  1932. // Note that because the properties page reports using these variables,
  1933. // 1. We need to be inside a critical section
  1934. // 2. They must all be updated together.  Updating the sums here and the count
  1935. // elsewhere can result in imaginary jitter (i.e. attempts to find square roots
  1936. // of negative numbers) in the property page code.
  1937.  
  1938. void CBaseVideoRenderer::RecordFrameLateness(int trLate, int trFrame)
  1939. {
  1940.     // Record how timely we are.
  1941.     int tLate = trLate/10000;
  1942.  
  1943.     // Best estimate of moment of appearing on the screen is average of
  1944.     // start and end draw times.  Here we have only the end time.  This may
  1945.     // tend to show us as spuriously late by up to 1/2 frame rate achieved.
  1946.     // Decoder probably monitors draw time.  We don't bother.
  1947.     MSR_INTEGER( m_idFrameAccuracy, tLate );
  1948.  
  1949.     // This is a kludge - we can get frames that are very late
  1950.     // especially (at start-up) and they invalidate the statistics.
  1951.     // So ignore things that are more than 1 sec off.
  1952.     if (tLate>1000 || tLate<-1000) {
  1953.         if (m_cFramesDrawn<=1) {
  1954.             tLate = 0;
  1955.         } else if (tLate>0) {
  1956.             tLate = 1000;
  1957.         } else {
  1958.             tLate = -1000;
  1959.         }
  1960.     }
  1961.     // The very first frame often has a invalid time, so don't
  1962.     // count it into the statistics.   (???)
  1963.     if (m_cFramesDrawn>1) {
  1964.         m_iTotAcc += tLate;
  1965.         m_iSumSqAcc += (tLate*tLate);
  1966.     }
  1967.  
  1968.     // calculate inter-frame time.  Doesn't make sense for first frame
  1969.     // second frame suffers from invalid first frame stamp.
  1970.     if (m_cFramesDrawn>2) {
  1971.         int tFrame = trFrame/10000;    // convert to mSec else it overflows
  1972.  
  1973.         // This is a kludge.  It can overflow anyway (a pause can cause
  1974.         // a very long inter-frame time) and it overflows at 2**31/10**7
  1975.         // or about 215 seconds i.e. 3min 35sec
  1976.         if (tFrame>1000||tFrame<0) tFrame = 1000;
  1977.         m_iSumSqFrameTime += tFrame*tFrame;
  1978.         ASSERT(m_iSumSqFrameTime>=0);
  1979.         m_iSumFrameTime += tFrame;
  1980.     }
  1981.     ++m_cFramesDrawn;
  1982.  
  1983. } // RecordFrameLateness
  1984.  
  1985.  
  1986. void CBaseVideoRenderer::ThrottleWait()
  1987. {
  1988.     if (m_trThrottle>0) {
  1989.         int iThrottle = m_trThrottle/10000;    // convert to mSec
  1990.         MSR_INTEGER( m_idThrottle, iThrottle);
  1991.         DbgLog((LOG_TRACE, 0, TEXT("Throttle %d ms"), iThrottle));
  1992.         Sleep(iThrottle);
  1993.     } else {
  1994.         Sleep(0);
  1995.     }
  1996. } // ThrottleWait
  1997.  
  1998.  
  1999. // Whenever a frame is rendered it goes though either OnRenderStart
  2000. // or OnDirectRender.  Data that are generated during ShouldDrawSample
  2001. // are added to the statistics by calling RecordFrameLateness from both
  2002. // these two places.
  2003.  
  2004. // Called in place of OnRenderStart..OnRenderEnd
  2005. // When a DirectDraw image is drawn
  2006. void CBaseVideoRenderer::OnDirectRender(IMediaSample *pMediaSample)
  2007. {
  2008.     m_trRenderAvg = 0;
  2009.     m_trRenderLast = 5000000;  // If we mode switch, we do NOT want this
  2010.                                // to inhibit the new average getting going!
  2011.                                // so we set it to half a second
  2012.     // MSR_INTEGER(m_idRenderAvg, m_trRenderAvg/10000);
  2013.     RecordFrameLateness(m_trLate, m_trFrame);
  2014.     ThrottleWait();
  2015. } // OnDirectRender
  2016.  
  2017.  
  2018. // Called just before we start drawing.  All we do is to get the current clock
  2019. // time (from the system) and return.  We have to store the start render time
  2020. // in a member variable because it isn't used until we complete the drawing
  2021. // The rest is just performance logging.
  2022.  
  2023. void CBaseVideoRenderer::OnRenderStart(IMediaSample *pMediaSample)
  2024. {
  2025.     RecordFrameLateness(m_trLate, m_trFrame);
  2026.     m_tRenderStart = timeGetTime();
  2027. } // OnRenderStart
  2028.  
  2029.  
  2030. // Called directly after drawing an image.  We calculate the time spent in the
  2031. // drawing code and if this doesn't appear to have any odd looking spikes in
  2032. // it then we add it to the current average draw time.  Measurement spikes may
  2033. // occur if the drawing thread is interrupted and switched to somewhere else.
  2034.  
  2035. void CBaseVideoRenderer::OnRenderEnd(IMediaSample *pMediaSample)
  2036. {
  2037.     // The renderer time can vary erratically if we are interrupted so we do
  2038.     // some smoothing to help get more sensible figures out but even that is
  2039.     // not enough as figures can go 9,10,9,9,83,9 and we must disregard 83
  2040.  
  2041.     int tr = (timeGetTime() - m_tRenderStart)*10000;   // convert mSec->UNITS
  2042.     if (tr < m_trRenderAvg*2 || tr < 2 * m_trRenderLast) {
  2043.         // DO_MOVING_AVG(m_trRenderAvg, tr);
  2044.         m_trRenderAvg = (tr + (AVGPERIOD-1)*m_trRenderAvg)/AVGPERIOD;
  2045.     }
  2046.     m_trRenderLast = tr;
  2047.     ThrottleWait();
  2048. } // OnRenderEnd
  2049.  
  2050.  
  2051. STDMETHODIMP CBaseVideoRenderer::SetSink( IQualityControl * piqc)
  2052. {
  2053.  
  2054.     m_pQSink = piqc;
  2055.  
  2056.     return NOERROR;
  2057. } // SetSink
  2058.  
  2059.  
  2060. STDMETHODIMP CBaseVideoRenderer::Notify( IBaseFilter * pSelf, Quality q)
  2061. {
  2062.     // NOTE:  We are NOT getting any locks here.  We could be called
  2063.     // asynchronously and possibly even on a time critical thread of
  2064.     // someone else's - so we do the minumum.  We only set one state
  2065.     // variable (an integer) and if that happens to be in the middle
  2066.     // of another thread reading it they will just get either the new
  2067.     // or the old value.  Locking would achieve no more than this.
  2068.  
  2069.     // It might be nice to check that we are being called from m_pGraph, but
  2070.     // it turns out to be a millisecond or so per throw!
  2071.  
  2072.     // This is heuristics, these numbers are aimed at being "what works"
  2073.     // rather than anything based on some theory.
  2074.     // We use a hyperbola because it's easy to calculate and it includes
  2075.     // a panic button asymptote (which we push off just to the left)
  2076.     // The throttling fits the following table (roughly)
  2077.     // Proportion   Throttle (msec)
  2078.     //     >=1000         0
  2079.     //        900         3
  2080.     //        800         7
  2081.     //        700        11
  2082.     //        600        17
  2083.     //        500        25
  2084.     //        400        35
  2085.     //        300        50
  2086.     //        200        72
  2087.     //        125       100
  2088.     //        100       112
  2089.     //         50       146
  2090.     //          0       200
  2091.  
  2092.     // (some evidence that we could go for a sharper kink - e.g. no throttling
  2093.     // until below the 750 mark - might give fractionally more frames on a
  2094.     // P60-ish machine).  The easy way to get these coefficients is to use
  2095.     // Renbase.xls follow the instructions therein using excel solver.
  2096.  
  2097.     if (q.Proportion>=1000) { m_trThrottle = 0; }
  2098.     else {
  2099.         // The DWORD is to make quite sure I get unsigned arithmetic
  2100.         // as the constant is between 2**31 and 2**32
  2101.         m_trThrottle = -330000 + (388880000/(q.Proportion+167));
  2102.     }
  2103.     return NOERROR;
  2104. } // Notify
  2105.  
  2106.  
  2107. // Send a message to indicate what our supplier should do about quality.
  2108. // Theory:
  2109. // What a supplier wants to know is "is the frame I'm working on NOW
  2110. // going to be late?".
  2111. // F1 is the frame at the supplier (as above)
  2112. // Tf1 is the due time for F1
  2113. // T1 is the time at that point (NOW!)
  2114. // Tr1 is the time that f1 WILL actually be rendered
  2115. // L1 is the latency of the graph for frame F1 = Tr1-T1
  2116. // D1 (for delay) is how late F1 will be beyond its due time i.e.
  2117. // D1 = (Tr1-Tf1) which is what the supplier really wants to know.
  2118. // Unfortunately Tr1 is in the future and is unknown, so is L1
  2119. //
  2120. // We could estimate L1 by its value for a previous frame,
  2121. // L0 = Tr0-T0 and work off
  2122. // D1' = ((T1+L0)-Tf1) = (T1 + (Tr0-T0) -Tf1)
  2123. // Rearranging terms:
  2124. // D1' = (T1-T0) + (Tr0-Tf1)
  2125. //       adding (Tf0-Tf0) and rearranging again:
  2126. //     = (T1-T0) + (Tr0-Tf0) + (Tf0-Tf1)
  2127. //     = (T1-T0) - (Tf1-Tf0) + (Tr0-Tf0)
  2128. // But (Tr0-Tf0) is just D0 - how late frame zero was, and this is the
  2129. // Late field in the quality message that we send.
  2130. // The other two terms just state what correction should be applied before
  2131. // using the lateness of F0 to predict the lateness of F1.
  2132. // (T1-T0) says how much time has actually passed (we have lost this much)
  2133. // (Tf1-Tf0) says how much time should have passed if we were keeping pace
  2134. // (we have gained this much).
  2135. //
  2136. // Suppliers should therefore work off:
  2137. //    Quality.Late + (T1-T0)  - (Tf1-Tf0)
  2138. // and see if this is "acceptably late" or even early (i.e. negative).
  2139. // They get T1 and T0 by polling the clock, they get Tf1 and Tf0 from
  2140. // the time stamps in the frames.  They get Quality.Late from us.
  2141. //
  2142.  
  2143. HRESULT CBaseVideoRenderer::SendQuality(REFERENCE_TIME trLate,
  2144.                                         REFERENCE_TIME trRealStream)
  2145. {
  2146.     Quality q;
  2147.     HRESULT hr;
  2148.  
  2149.     // If we are the main user of time, then report this as Flood/Dry.
  2150.     // If our suppliers are, then report it as Famine/Glut.
  2151.     //
  2152.     // We need to take action, but avoid hunting.  Hunting is caused by
  2153.     // 1. Taking too much action too soon and overshooting
  2154.     // 2. Taking too long to react (so averaging can CAUSE hunting).
  2155.     //
  2156.     // The reason why we use trLate as well as Wait is to reduce hunting;
  2157.     // if the wait time is coming down and about to go into the red, we do
  2158.     // NOT want to rely on some average which is only telling is that it used
  2159.     // to be OK once.
  2160.  
  2161.     q.TimeStamp = (REFERENCE_TIME)trRealStream;
  2162.  
  2163.     if (m_trFrameAvg<0) {
  2164.         q.Type = Famine;      // guess
  2165.     }
  2166.     // Is the greater part of the time taken bltting or something else
  2167.     else if (m_trFrameAvg > 2*m_trRenderAvg) {
  2168.         q.Type = Famine;                        // mainly other
  2169.     } else {
  2170.         q.Type = Flood;                         // mainly bltting
  2171.     }
  2172.  
  2173.     q.Proportion = 1000;               // default
  2174.  
  2175.     if (m_trFrameAvg<0) {
  2176.         // leave it alone - we don't know enough
  2177.     }
  2178.     else if ( trLate> 0 ) {
  2179.         // try to catch up over the next second
  2180.         // We could be Really, REALLY late, but rendering all the frames
  2181.         // anyway, just because it's so cheap.
  2182.  
  2183.         q.Proportion = 1000 - (int)((trLate)/(UNITS/1000));
  2184.         if (q.Proportion<500) {
  2185.            q.Proportion = 500;      // don't go daft. (could've been negative!)
  2186.         } else {
  2187.         }
  2188.  
  2189.     } else if (  m_trWaitAvg>20000
  2190.               && trLate<-20000
  2191.               ){
  2192.         // Go cautiously faster - aim at 2mSec wait.
  2193.         if (m_trWaitAvg>=m_trFrameAvg) {
  2194.             // This can happen because of some fudges.
  2195.             // The waitAvg is how long we originally planned to wait
  2196.             // The frameAvg is more honest.
  2197.             // It means that we are spending a LOT of time waiting
  2198.             q.Proportion = 2000;    // double.
  2199.         } else {
  2200.             if (m_trFrameAvg+20000 > m_trWaitAvg) {
  2201.                 q.Proportion
  2202.                     = 1000 * (m_trFrameAvg / (m_trFrameAvg + 20000 - m_trWaitAvg));
  2203.             } else {
  2204.                 // We're apparently spending more than the whole frame time waiting.
  2205.                 // Assume that the averages are slightly out of kilter, but that we
  2206.                 // are indeed doing a lot of waiting.  (This leg probably never
  2207.                 // happens, but the code avoids any potential divide by zero).
  2208.                 q.Proportion = 2000;
  2209.             }
  2210.         }
  2211.  
  2212.         if (q.Proportion>2000) {
  2213.             q.Proportion = 2000;    // don't go crazy.
  2214.         }
  2215.     }
  2216.  
  2217.     // Tell the supplier how late frames are when they get rendered
  2218.     // That's how late we are now.
  2219.     // If we are in directdraw mode then the guy upstream can see the drawing
  2220.     // times and we'll just report on the start time.  He can figure out any
  2221.     // offset to apply.  If we are in DIB Section mode then we will apply an
  2222.     // extra offset which is half of our drawing time.  This is usually small
  2223.     // but can sometimes be the dominant effect.  For this we will use the
  2224.     // average drawing time rather than the last frame.  If the last frame took
  2225.     // a long time to draw and made us late, that's already in the lateness
  2226.     // figure.  We should not add it in again unless we expect the next frame
  2227.     // to be the same.  We don't, we expect the average to be a better shot.
  2228.     // In direct draw mode the RenderAvg will be zero.
  2229.  
  2230.     q.Late = trLate + m_trRenderAvg/2;
  2231.  
  2232.     // log what we're doing
  2233.     MSR_INTEGER(m_idQualityRate, q.Proportion);
  2234.     MSR_INTEGER( m_idQualityTime, (int)q.Late / 10000 );
  2235.  
  2236.     // A specific sink interface may be set through IPin
  2237.  
  2238.     if (m_pQSink==NULL) {
  2239.         // Get our input pin's peer.  We send quality management messages
  2240.         // to any nominated receiver of these things (set in the IPin
  2241.         // interface), or else to our source filter.
  2242.  
  2243.         IQualityControl *pQC = NULL;
  2244.         IPin *pOutputPin = m_pInputPin->GetConnected();
  2245.         ASSERT(pOutputPin != NULL);
  2246.  
  2247.         // And get an AddRef'd quality control interface
  2248.  
  2249.         hr = pOutputPin->QueryInterface(IID_IQualityControl,(void**) &pQC);
  2250.         if (SUCCEEDED(hr)) {
  2251.             m_pQSink = pQC;
  2252.         }
  2253.     }
  2254.     if (m_pQSink) {
  2255.         return m_pQSink->Notify(this,q);
  2256.     }
  2257.  
  2258.     return S_FALSE;
  2259.  
  2260. } // SendQuality
  2261.  
  2262.  
  2263. // We are called with a valid IMediaSample image to decide whether this is to
  2264. // be drawn or not.  There must be a reference clock in operation.
  2265. // Return S_OK if it is to be drawn Now (as soon as possible)
  2266. // Return S_FALSE if it is to be drawn when it's due
  2267. // Return an error if we want to drop it
  2268. // m_nNormal=-1 indicates that we dropped the previous frame and so this
  2269. // one should be drawn early.  Respect it and update it.
  2270. // Use current stream time plus a number of heuristics (detailed below)
  2271. // to make the decision
  2272.  
  2273. HRESULT CBaseVideoRenderer::ShouldDrawSampleNow(IMediaSample *pMediaSample,
  2274.                                                 REFERENCE_TIME *ptrStart,
  2275.                                                 REFERENCE_TIME *ptrEnd)
  2276. {
  2277.  
  2278.     // Don't call us unless there's a clock interface to synchronise with
  2279.     ASSERT(m_pClock);
  2280.  
  2281.     MSR_INTEGER(m_idTimeStamp, (int)((*ptrStart)>>32));   // high order 32 bits
  2282.     MSR_INTEGER(m_idTimeStamp, (int)(*ptrStart));         // low order 32 bits
  2283.  
  2284.     // We lose a bit of time depending on the monitor type waiting for the next
  2285.     // screen refresh.  On average this might be about 8mSec - so it will be
  2286.     // later than we think when the picture appears.  To compensate a bit
  2287.     // we bias the media samples by -8mSec i.e. 80000 UNITs.
  2288.     // We don't ever make a stream time negative (call it paranoia)
  2289.     if (*ptrStart>=80000) {
  2290.         *ptrStart -= 80000;
  2291.         *ptrEnd -= 80000;       // bias stop to to retain valid frame duration
  2292.     }
  2293.  
  2294.     // Cache the time stamp now.  We will want to compare what we did with what
  2295.     // we started with (after making the monitor allowance).
  2296.     m_trRememberStampForPerf = *ptrStart;
  2297.  
  2298.     // Get reference times (current and late)
  2299.     REFERENCE_TIME trRealStream;     // the real time now expressed as stream time.
  2300.     m_pClock->GetTime(&trRealStream);
  2301. #ifdef PERF
  2302.     // While the reference clock is expensive:
  2303.     // Remember the offset from timeGetTime and use that.
  2304.     // This overflows all over the place, but when we subtract to get
  2305.     // differences the overflows all cancel out.
  2306.     m_llTimeOffset = trRealStream-timeGetTime()*10000;
  2307. #endif
  2308.     trRealStream -= m_tStart;     // convert to stream time (this is a reftime)
  2309.  
  2310.     // We have to wory about two versions of "lateness".  The truth, which we
  2311.     // try to work out here and the one measured against m_trTarget which
  2312.     // includes long term feedback.  We report statistics against the truth
  2313.     // but for operational decisions we work to the target.
  2314.     // We use TimeDiff to make sure we get an integer because we
  2315.     // may actually be late (or more likely early if there is a big time
  2316.     // gap) by a very long time.
  2317.     const int trTrueLate = TimeDiff(trRealStream - *ptrStart);
  2318.     const int trLate = trTrueLate;
  2319.  
  2320.     MSR_INTEGER(m_idSchLateTime, trTrueLate/10000);
  2321.  
  2322.     // Send quality control messages upstream, measured against target
  2323.     HRESULT hr = SendQuality(trLate, trRealStream);
  2324.     // Note: the filter upstream is allowed to this FAIL meaning "you do it".
  2325.     m_bSupplierHandlingQuality = (hr==S_OK);
  2326.  
  2327.     // Decision time!  Do we drop, draw when ready or draw immediately?
  2328.  
  2329.     const int trDuration = (int)(*ptrEnd - *ptrStart);
  2330.     {
  2331.         // We need to see if the frame rate of the file has just changed.
  2332.         // This would make comparing our previous frame rate with the current
  2333.         // frame rate inefficent.  Hang on a moment though.  I've seen files
  2334.         // where the frames vary between 33 and 34 mSec so as to average
  2335.         // 30fps.  A minor variation like that won't hurt us.
  2336.         int t = m_trDuration/32;
  2337.         if (  trDuration > m_trDuration+t
  2338.            || trDuration < m_trDuration-t
  2339.            ) {
  2340.             // There's a major variation.  Reset the average frame rate to
  2341.             // exactly the current rate to disable decision 9002 for this frame,
  2342.             // and remember the new rate.
  2343.             m_trFrameAvg = trDuration;
  2344.             m_trDuration = trDuration;
  2345.         }
  2346.     }
  2347.  
  2348.     MSR_INTEGER(m_idEarliness, m_trEarliness/10000);
  2349.     MSR_INTEGER(m_idRenderAvg, m_trRenderAvg/10000);
  2350.     MSR_INTEGER(m_idFrameAvg, m_trFrameAvg/10000);
  2351.     MSR_INTEGER(m_idWaitAvg, m_trWaitAvg/10000);
  2352.     MSR_INTEGER(m_idDuration, trDuration/10000);
  2353.  
  2354. #ifdef PERF
  2355.     if (S_OK==pMediaSample->IsDiscontinuity()) {
  2356.         MSR_INTEGER(m_idDecision, 9000);
  2357.     }
  2358. #endif
  2359.  
  2360.     // Control the graceful slide back from slow to fast machine mode.
  2361.     // After a frame drop accept an early frame and set the earliness to here
  2362.     // If this frame is already later than the earliness then slide it to here
  2363.     // otherwise do the standard slide (reduce by about 12% per frame).
  2364.     // Note: earliness is normally NEGATIVE
  2365.     BOOL bJustDroppedFrame
  2366.         = (  m_bSupplierHandlingQuality
  2367.           //  Can't use the pin sample properties because we might
  2368.           //  not be in Receive when we call this
  2369.           && (S_OK == pMediaSample->IsDiscontinuity())          // he just dropped one
  2370.           )
  2371.        || (m_nNormal==-1);                          // we just dropped one
  2372.  
  2373.  
  2374.     // Set m_trEarliness (slide back from slow to fast machine mode)
  2375.     if (trLate>0) {
  2376.         m_trEarliness = 0;   // we are no longer in fast machine mode at all!
  2377.     } else if (  (trLate>=m_trEarliness) || bJustDroppedFrame) {
  2378.         m_trEarliness = trLate;  // Things have slipped of their own accord
  2379.     } else {
  2380.         m_trEarliness = m_trEarliness - m_trEarliness/8;  // graceful slide
  2381.     }
  2382.  
  2383.     // prepare the new wait average - but don't pollute the old one until
  2384.     // we have finished with it.
  2385.     int trWaitAvg;
  2386.     {
  2387.         // We never mix in a negative wait.  This causes us to believe in fast machines
  2388.         // slightly more.
  2389.         int trL = trLate<0 ? -trLate : 0;
  2390.         trWaitAvg = (trL + m_trWaitAvg*(AVGPERIOD-1))/AVGPERIOD;
  2391.     }
  2392.  
  2393.  
  2394.     int trFrame;
  2395.     {
  2396.         REFERENCE_TIME tr = trRealStream - m_trLastDraw; // Cd be large - 4 min pause!
  2397.         if (tr>10000000) {
  2398.             tr = 10000000;   // 1 second - arbitrarily.
  2399.         }
  2400.         trFrame = int(tr);
  2401.     }
  2402.  
  2403.     // We will DRAW this frame IF...
  2404.     if (
  2405.           // ...the time we are spending drawing is a small fraction of the total
  2406.           // observed inter-frame time so that dropping it won't help much.
  2407.           (3*m_trRenderAvg <= m_trFrameAvg)
  2408.  
  2409.          // ...or our supplier is NOT handling things and the next frame would
  2410.          // be less timely than this one or our supplier CLAIMS to be handling
  2411.          // things, and is now less than a full FOUR frames late.
  2412.        || ( m_bSupplierHandlingQuality
  2413.           ? (trLate <= trDuration*4)
  2414.           : (trLate+trLate < trDuration)
  2415.           )
  2416.  
  2417.           // ...or we are on average waiting for over eight milliseconds then
  2418.           // this may be just a glitch.  Draw it and we'll hope to catch up.
  2419.        || (m_trWaitAvg > 80000)
  2420.  
  2421.           // ...or we haven't drawn an image for over a second.  We will update
  2422.           // the display, which stops the video looking hung.
  2423.           // Do this regardless of how late this media sample is.
  2424.        || ((trRealStream - m_trLastDraw) > UNITS)
  2425.  
  2426.     ) {
  2427.         HRESULT Result;
  2428.  
  2429.         // We are going to play this frame.  We may want to play it early.
  2430.         // We will play it early if we think we are in slow machine mode.
  2431.         // If we think we are NOT in slow machine mode, we will still play
  2432.         // it early by m_trEarliness as this controls the graceful slide back.
  2433.         // and in addition we aim at being m_trTarget late rather than "on time".
  2434.  
  2435.         BOOL bPlayASAP = FALSE;
  2436.  
  2437.         // we will play it AT ONCE (slow machine mode) if...
  2438.  
  2439.             // ...we are playing catch-up
  2440.         if ( bJustDroppedFrame) {
  2441.             bPlayASAP = TRUE;
  2442.             MSR_INTEGER(m_idDecision, 9001);
  2443.         }
  2444.  
  2445.             // ...or if we are running below the true frame rate
  2446.             // exact comparisons are glitchy, for these measurements,
  2447.             // so add an extra 5% or so
  2448.         else if (  (m_trFrameAvg > trDuration + trDuration/16)
  2449.  
  2450.                    // It's possible to get into a state where we are losing ground, but
  2451.                    // are a very long way ahead.  To avoid this or recover from it
  2452.                    // we refuse to play early by more than 10 frames.
  2453.                 && (trLate > - trDuration*10)
  2454.                 ){
  2455.             bPlayASAP = TRUE;
  2456.             MSR_INTEGER(m_idDecision, 9002);
  2457.         }
  2458. #if 0
  2459.             // ...or if we have been late and are less than one frame early
  2460.         else if (  (trLate + trDuration > 0)
  2461.                 && (m_trWaitAvg<=20000)
  2462.                 ) {
  2463.             bPlayASAP = TRUE;
  2464.             MSR_INTEGER(m_idDecision, 9003);
  2465.         }
  2466. #endif
  2467.         // We will NOT play it at once if we are grossly early.  On very slow frame
  2468.         // rate movies - e.g. clock.avi - it is not a good idea to leap ahead just
  2469.         // because we got starved (for instance by the net) and dropped one frame
  2470.         // some time or other.  If we are more than 900mSec early, then wait.
  2471.         if (trLate<-9000000) {
  2472.             bPlayASAP = FALSE;
  2473.         }
  2474.  
  2475.         if (bPlayASAP) {
  2476.  
  2477.             m_nNormal = 0;
  2478.             MSR_INTEGER(m_idDecision, 0);
  2479.             // When we are here, we are in slow-machine mode.  trLate may well
  2480.             // oscillate between negative and positive when the supplier is
  2481.             // dropping frames to keep sync.  We should not let that mislead
  2482.             // us into thinking that we have as much as zero spare time!
  2483.             // We just update with a zero wait.
  2484.             m_trWaitAvg = (m_trWaitAvg*(AVGPERIOD-1))/AVGPERIOD;
  2485.  
  2486.             // Assume that we draw it immediately.  Update inter-frame stats
  2487.             m_trFrameAvg = (trFrame + m_trFrameAvg*(AVGPERIOD-1))/AVGPERIOD;
  2488. #ifndef PERF
  2489.             // If this is NOT a perf build, then report what we know so far
  2490.             // without looking at the clock any more.  This assumes that we
  2491.             // actually wait for exactly the time we hope to.  It also reports
  2492.             // how close we get to the manipulated time stamps that we now have
  2493.             // rather than the ones we originally started with.  It will
  2494.             // therefore be a little optimistic.  However it's fast.
  2495.             PreparePerformanceData(trTrueLate, trFrame);
  2496. #endif
  2497.             m_trLastDraw = trRealStream;
  2498.             if (m_trEarliness > trLate) {
  2499.                 m_trEarliness = trLate;  // if we are actually early, this is neg
  2500.             }
  2501.             Result = S_OK;                   // Draw it now
  2502.  
  2503.         } else {
  2504.             ++m_nNormal;
  2505.             // Set the average frame rate to EXACTLY the ideal rate.
  2506.             // If we are exiting slow-machine mode then we will have caught up
  2507.             // and be running ahead, so as we slide back to exact timing we will
  2508.             // have a longer than usual gap at this point.  If we record this
  2509.             // real gap then we'll think that we're running slow and go back
  2510.             // into slow-machine mode and vever get it straight.
  2511.             m_trFrameAvg = trDuration;
  2512.             MSR_INTEGER(m_idDecision, 1);
  2513.  
  2514.             // Play it early by m_trEarliness and by m_trTarget
  2515.  
  2516.             {
  2517.                 int trE = m_trEarliness;
  2518.                 if (trE < -m_trFrameAvg) {
  2519.                     trE = -m_trFrameAvg;
  2520.                 }
  2521.                 *ptrStart += trE;           // N.B. earliness is negative
  2522.             }
  2523.  
  2524.             int Delay = -trTrueLate;
  2525.             Result = Delay<=0 ? S_OK : S_FALSE;     // OK = draw now, FALSE = wait
  2526.  
  2527.             m_trWaitAvg = trWaitAvg;
  2528.  
  2529.             // Predict when it will actually be drawn and update frame stats
  2530.  
  2531.             if (Result==S_FALSE) {   // We are going to wait
  2532.                 trFrame = TimeDiff(*ptrStart-m_trLastDraw);
  2533.                 m_trLastDraw = *ptrStart;
  2534.             } else {
  2535.                 // trFrame is already = trRealStream-m_trLastDraw;
  2536.                 m_trLastDraw = trRealStream;
  2537.             }
  2538. #ifndef PERF
  2539.             int iAccuracy;
  2540.             if (Delay>0) {
  2541.                 // Report lateness based on when we intend to play it
  2542.                 iAccuracy = TimeDiff(*ptrStart-m_trRememberStampForPerf);
  2543.             } else {
  2544.                 // Report lateness based on playing it *now*.
  2545.                 iAccuracy = trTrueLate;     // trRealStream-RememberStampForPerf;
  2546.             }
  2547.             PreparePerformanceData(iAccuracy, trFrame);
  2548. #endif
  2549.         }
  2550.         return Result;
  2551.     }
  2552.  
  2553.     // We are going to drop this frame!
  2554.     // Of course in DirectDraw mode the guy upstream may draw it anyway.
  2555.  
  2556.     // This will probably give a large negative wack to the wait avg.
  2557.     m_trWaitAvg = trWaitAvg;
  2558.  
  2559. #ifdef PERF
  2560.     // Respect registry setting - debug only!
  2561.     if (m_bDrawLateFrames) {
  2562.        return S_OK;                        // draw it when it's ready
  2563.     }                                      // even though it's late.
  2564. #endif
  2565.  
  2566.     // We are going to drop this frame so draw the next one early
  2567.     // n.b. if the supplier is doing direct draw then he may draw it anyway
  2568.     // but he's doing something funny to arrive here in that case.
  2569.  
  2570.     MSR_INTEGER(m_idDecision, 2);
  2571.     m_nNormal = -1;
  2572.     return E_FAIL;                         // drop it
  2573.  
  2574. } // ShouldDrawSampleNow
  2575.  
  2576.  
  2577. // NOTE we're called by both the window thread and the source filter thread
  2578. // so we have to be protected by a critical section (locked before called)
  2579. // Also, when the window thread gets signalled to render an image, it always
  2580. // does so regardless of how late it is. All the degradation is done when we
  2581. // are scheduling the next sample to be drawn. Hence when we start an advise
  2582. // link to draw a sample, that sample's time will always become the last one
  2583. // drawn - unless of course we stop streaming in which case we cancel links
  2584.  
  2585. BOOL CBaseVideoRenderer::ScheduleSample(IMediaSample *pMediaSample)
  2586. {
  2587.     // We override ShouldDrawSampleNow to add quality management
  2588.  
  2589.     BOOL bDrawImage = CBaseRenderer::ScheduleSample(pMediaSample);
  2590.     if (bDrawImage == FALSE) {
  2591.     ++m_cFramesDropped;
  2592.     return FALSE;
  2593.     }
  2594.  
  2595.     // m_cFramesDrawn must NOT be updated here.  It has to be updated
  2596.     // in RecordFrameLateness at the same time as the other statistics.
  2597.     return TRUE;
  2598. }
  2599.  
  2600.  
  2601. // Implementation of IQualProp interface needed to support the property page
  2602. // This is how the property page gets the data out of the scheduler. We are
  2603. // passed into the constructor the owning object in the COM sense, this will
  2604. // either be the video renderer or an external IUnknown if we're aggregated.
  2605. // We initialise our CUnknown base class with this interface pointer. Then
  2606. // all we have to do is to override NonDelegatingQueryInterface to expose
  2607. // our IQualProp interface. The AddRef and Release are handled automatically
  2608. // by the base class and will be passed on to the appropriate outer object
  2609.  
  2610. STDMETHODIMP CBaseVideoRenderer::get_FramesDroppedInRenderer(int *pcFramesDropped)
  2611. {
  2612.     CheckPointer(pcFramesDropped,E_POINTER);
  2613.     CAutoLock cVideoLock(&m_InterfaceLock);
  2614.     *pcFramesDropped = m_cFramesDropped;
  2615.     return NOERROR;
  2616. } // get_FramesDroppedInRenderer
  2617.  
  2618.  
  2619. // Set *pcFramesDrawn to the number of frames drawn since
  2620. // streaming started.
  2621.  
  2622. STDMETHODIMP CBaseVideoRenderer::get_FramesDrawn( int *pcFramesDrawn)
  2623. {
  2624.     CheckPointer(pcFramesDrawn,E_POINTER);
  2625.     CAutoLock cVideoLock(&m_InterfaceLock);
  2626.     *pcFramesDrawn = m_cFramesDrawn;
  2627.     return NOERROR;
  2628. } // get_FramesDrawn
  2629.  
  2630.  
  2631. // Set iAvgFrameRate to the frames per hundred secs since
  2632. // streaming started.  0 otherwise.
  2633.  
  2634. STDMETHODIMP CBaseVideoRenderer::get_AvgFrameRate( int *piAvgFrameRate)
  2635. {
  2636.     CheckPointer(piAvgFrameRate,E_POINTER);
  2637.     CAutoLock cVideoLock(&m_InterfaceLock);
  2638.  
  2639.     int t;
  2640.     if (m_bStreaming) {
  2641.         t = timeGetTime()-m_tStreamingStart;
  2642.     } else {
  2643.         t = m_tStreamingStart;
  2644.     }
  2645.  
  2646.     if (t<=0) {
  2647.         *piAvgFrameRate = 0;
  2648.         ASSERT(m_cFramesDrawn == 0);
  2649.     } else {
  2650.         // i is frames per hundred seconds
  2651.         *piAvgFrameRate = MulDiv(100000, m_cFramesDrawn, t);
  2652.     }
  2653.     return NOERROR;
  2654. } // get_AvgFrameRate
  2655.  
  2656.  
  2657. // Set *piAvg to the average sync offset since streaming started
  2658. // in mSec.  The sync offset is the time in mSec between when the frame
  2659. // should have been drawn and when the frame was actually drawn.
  2660.  
  2661. STDMETHODIMP CBaseVideoRenderer::get_AvgSyncOffset( int *piAvg)
  2662. {
  2663.     CheckPointer(piAvg,E_POINTER);
  2664.     CAutoLock cVideoLock(&m_InterfaceLock);
  2665.  
  2666.     if (NULL==m_pClock) {
  2667.         *piAvg = 0;
  2668.         return NOERROR;
  2669.     }
  2670.  
  2671.     // Note that we didn't gather the stats on the first frame
  2672.     // so we use m_cFramesDrawn-1 here
  2673.     if (m_cFramesDrawn<=1) {
  2674.         *piAvg = 0;
  2675.     } else {
  2676.         *piAvg = (int)(m_iTotAcc / (m_cFramesDrawn-1));
  2677.     }
  2678.     return NOERROR;
  2679. } // get_AvgSyncOffset
  2680.  
  2681.  
  2682. // To avoid dragging in the maths library - a cheap
  2683. // approximate integer square root.
  2684. // We do this by getting a starting guess which is between 1
  2685. // and 2 times too large, followed by THREE iterations of
  2686. // Newton Raphson.  (That will give accuracy to the nearest mSec
  2687. // for the range in question - roughly 0..1000)
  2688. //
  2689. // It would be faster to use a linear interpolation and ONE NR, but
  2690. // who cares.  If anyone does - the best linear interpolation is
  2691. // to approximates sqrt(x) by
  2692. // y = x * (sqrt(2)-1) + 1 - 1/sqrt(2) + 1/(8*(sqrt(2)-1))
  2693. // 0r y = x*0.41421 + 0.59467
  2694. // This minimises the maximal error in the range in question.
  2695. // (error is about +0.008883 and then one NR will give error .0000something
  2696. // (Of course these are integers, so you can't just multiply by 0.41421
  2697. // you'd have to do some sort of MulDiv).
  2698. // Anyone wanna check my maths?  (This is only for a property display!)
  2699.  
  2700. int isqrt(int x)
  2701. {
  2702.     int s = 1;
  2703.     // Make s an initial guess for sqrt(x)
  2704.     if (x > 0x40000000) {
  2705.        s = 0x8000;     // prevent any conceivable closed loop
  2706.     } else {
  2707.         while (s*s<x) {    // loop cannot possible go more than 31 times
  2708.             s = 2*s;       // normally it goes about 6 times
  2709.         }
  2710.         // Three NR iterations.
  2711.         if (x==0) {
  2712.            s= 0; // Wouldn't it be tragic to divide by zero whenever our
  2713.                  // accuracy was perfect!
  2714.         } else {
  2715.             s = (s*s+x)/(2*s);
  2716.             if (s>=0) s = (s*s+x)/(2*s);
  2717.             if (s>=0) s = (s*s+x)/(2*s);
  2718.         }
  2719.     }
  2720.     return s;
  2721. }
  2722.  
  2723. //
  2724. //  Do estimates for standard deviations for per-frame
  2725. //  statistics
  2726. //
  2727. HRESULT CBaseVideoRenderer::GetStdDev(
  2728.     int nSamples,
  2729.     int *piResult,
  2730.     LONGLONG llSumSq,
  2731.     LONGLONG iTot
  2732. )
  2733. {
  2734.     CheckPointer(piResult,E_POINTER);
  2735.     CAutoLock cVideoLock(&m_InterfaceLock);
  2736.  
  2737.     if (NULL==m_pClock) {
  2738.         *piResult = 0;
  2739.         return NOERROR;
  2740.     }
  2741.  
  2742.     // If S is the Sum of the Squares of observations and
  2743.     //    T the Total (i.e. sum) of the observations and there were
  2744.     //    N observations, then an estimate of the standard deviation is
  2745.     //      sqrt( (S - T**2/N) / (N-1) )
  2746.  
  2747.     if (nSamples<=1) {
  2748.         *piResult = 0;
  2749.     } else {
  2750.         LONGLONG x;
  2751.         // First frames have invalid stamps, so we get no stats for them
  2752.         // So we need 2 frames to get 1 datum, so N is cFramesDrawn-1
  2753.  
  2754.         // so we use m_cFramesDrawn-1 here
  2755.         x = llSumSq - llMulDiv(iTot, iTot, nSamples, 0);
  2756.         x = x / (nSamples-1);
  2757.         ASSERT(x>=0);
  2758.         *piResult = isqrt((LONG)x);
  2759.     }
  2760.     return NOERROR;
  2761. }
  2762.  
  2763. // Set *piDev to the standard deviation in mSec of the sync offset
  2764. // of each frame since streaming started.
  2765.  
  2766. STDMETHODIMP CBaseVideoRenderer::get_DevSyncOffset( int *piDev)
  2767. {
  2768.     // First frames have invalid stamps, so we get no stats for them
  2769.     // So we need 2 frames to get 1 datum, so N is cFramesDrawn-1
  2770.     return GetStdDev(m_cFramesDrawn - 1,
  2771.                      piDev,
  2772.                      m_iSumSqAcc,
  2773.                      m_iTotAcc);
  2774. } // get_DevSyncOffset
  2775.  
  2776.  
  2777. // Set *piJitter to the standard deviation in mSec of the inter-frame time
  2778. // of frames since streaming started.
  2779.  
  2780. STDMETHODIMP CBaseVideoRenderer::get_Jitter( int *piJitter)
  2781. {
  2782.     // First frames have invalid stamps, so we get no stats for them
  2783.     // So second frame gives invalid inter-frame time
  2784.     // So we need 3 frames to get 1 datum, so N is cFramesDrawn-2
  2785.     return GetStdDev(m_cFramesDrawn - 2,
  2786.                      piJitter,
  2787.                      m_iSumSqFrameTime,
  2788.                      m_iSumFrameTime);
  2789. } // get_Jitter
  2790.  
  2791.  
  2792. // Overidden to return our IQualProp interface
  2793.  
  2794. STDMETHODIMP
  2795. CBaseVideoRenderer::NonDelegatingQueryInterface(REFIID riid,VOID **ppv)
  2796. {
  2797.     // We return IQualProp and delegate everything else
  2798.  
  2799.     if (riid == IID_IQualProp) {
  2800.         return GetInterface( (IQualProp *)this, ppv);
  2801.     } else if (riid == IID_IQualityControl) {
  2802.         return GetInterface( (IQualityControl *)this, ppv);
  2803.     }
  2804.     return CBaseRenderer::NonDelegatingQueryInterface(riid,ppv);
  2805. }
  2806.  
  2807.  
  2808. // Override JoinFilterGraph so that, just before leaving
  2809. // the graph we can send an EC_WINDOW_DESTROYED event
  2810.  
  2811. STDMETHODIMP
  2812. CBaseVideoRenderer::JoinFilterGraph(IFilterGraph *pGraph,LPCWSTR pName)
  2813. {
  2814.     // Since we send EC_ACTIVATE, we also need to ensure
  2815.     // we send EC_WINDOW_DESTROYED or the resource manager may be
  2816.     // holding us as a focus object
  2817.     if (!pGraph && m_pGraph) {
  2818.  
  2819.         // We were in a graph and now we're not
  2820.         // Do this properly in case we are aggregated
  2821.         IBaseFilter* pFilter;
  2822.         QueryInterface(IID_IBaseFilter,(void **) &pFilter);
  2823.         NotifyEvent(EC_WINDOW_DESTROYED, (LPARAM) pFilter, 0);
  2824.         pFilter->Release();
  2825.     }
  2826.     return CBaseFilter::JoinFilterGraph(pGraph, pName);
  2827. }
  2828.  
  2829.  
  2830. // This removes a large number of level 4 warnings from the
  2831. // Microsoft compiler which in this case are not very useful
  2832. #pragma warning(disable: 4514)
  2833.  
  2834.