renbase.cpp 94 KB

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