home *** CD-ROM | disk | FTP | other *** search
/ The Net: Ultimate Internet Guide / WWLCD1.ISO / mac / SiteBldr / AMOVIE / SDK / _SETUP / COMMON.Z / renbase.h < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-20  |  19.2 KB  |  450 lines

  1. //==========================================================================;
  2. //
  3. //  THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  4. //  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  5. //  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
  6. //  PURPOSE.
  7. //
  8. //  Copyright (c) 1992 - 1996  Microsoft Corporation.  All Rights Reserved.
  9. //
  10. //--------------------------------------------------------------------------;
  11.  
  12. // Generic AciveX base renderer class, December 1995
  13.  
  14. #ifndef __RENBASE__
  15. #define __RENBASE__
  16.  
  17. // Simple rendered input pin
  18. //
  19. // NOTE if your filter queues stuff before rendering then it may not be
  20. // appropriate to use this class
  21. //
  22. // In that case queue the end of stream condition until the last sample
  23. // is actually rendered and flush the condition appropriately
  24. //
  25. class CRenderedInputPin : public CBaseInputPin
  26. {
  27. public:
  28.     CRenderedInputPin(
  29.         TCHAR *pObjectName,
  30.         CBaseFilter *pFilter,
  31.         CCritSec *pLock,
  32.         HRESULT *phr,
  33.         LPCWSTR pName);
  34.  
  35.     //  Override methods to track end of stream state
  36.     STDMETHODIMP EndOfStream();
  37.     STDMETHODIMP EndFlush();
  38.  
  39.     HRESULT Active();
  40.     HRESULT Run(REFERENCE_TIME tStart);
  41.  
  42. protected:
  43.  
  44.     // Member variables to track state
  45.     BOOL m_bAtEndOfStream;      // Set by EndOfStream
  46.     BOOL m_bCompleteNotified;   // Set when we notify for EC_COMPLETE
  47.  
  48. private:
  49.     void DoCompleteHandling();
  50. };
  51.  
  52. // Forward class declarations
  53.  
  54. class CBaseRenderer;
  55. class CRendererInputPin;
  56.  
  57. // This is our input pin class that channels calls to the renderer
  58.  
  59. class CRendererInputPin : public CBaseInputPin
  60. {
  61. protected:
  62.  
  63.     CBaseRenderer *m_pRenderer;
  64.  
  65. public:
  66.  
  67.     CRendererInputPin(CBaseRenderer *pRenderer,
  68.                       HRESULT *phr,
  69.                       LPCWSTR Name);
  70.  
  71.     // Overriden from the base pin classes
  72.  
  73.     HRESULT BreakConnect();
  74.     HRESULT CompleteConnect(IPin *pReceivePin);
  75.     HRESULT SetMediaType(const CMediaType *pmt);
  76.     HRESULT CheckMediaType(const CMediaType *pmt);
  77.     HRESULT Active();
  78.     HRESULT Inactive();
  79.  
  80.     // Add rendering behaviour to interface functions
  81.  
  82.     STDMETHODIMP QueryId(LPWSTR *Id);
  83.     STDMETHODIMP EndOfStream();
  84.     STDMETHODIMP BeginFlush();
  85.     STDMETHODIMP EndFlush();
  86.     STDMETHODIMP Receive(IMediaSample *pMediaSample);
  87. };
  88.  
  89. // Main renderer class that handles synchronisation and state changes
  90.  
  91. class CBaseRenderer : public CBaseFilter
  92. {
  93. protected:
  94.  
  95.     friend class CRendererInputPin;
  96.  
  97.     CRendererPosPassThru *m_pPosition;  // Media seeking pass by object
  98.     CAMEvent m_RenderEvent;             // Used to signal timer events
  99.     CAMEvent m_ThreadSignal;            // Signalled to release worker thread
  100.     CTimeoutEvent m_evComplete;         // Signalled when state complete
  101.     BOOL m_bAbort;                      // Stop us from rendering more data
  102.     BOOL m_bStreaming;                  // Are we currently streaming
  103.     DWORD m_dwAdvise;                   // Timer advise cookie
  104.     IMediaSample *m_pMediaSample;       // Current image media sample
  105.     BOOL m_bEOS;                        // Any more samples in the stream
  106.     BOOL m_bEOSDelivered;               // Have we delivered an EC_COMPLETE
  107.     CRendererInputPin *m_pInputPin;     // Our renderer input pin object
  108.     CCritSec m_InterfaceLock;           // Critical section for interfaces
  109.     CCritSec m_RendererLock;            // Controls access to internals
  110.     IQualityControl * m_pQSink;         // QualityControl sink
  111.     BOOL m_bRepaintStatus;              // Can we signal an EC_REPAINT
  112.  
  113. public:
  114.  
  115.     CBaseRenderer(CLSID RenderClass,    // CLSID for this renderer
  116.                   TCHAR *pName,         // Debug ONLY description
  117.                   LPUNKNOWN pUnk,       // Aggregated owner object
  118.                   HRESULT *phr);        // General OLE return code
  119.  
  120.     ~CBaseRenderer();
  121.  
  122.     // Overriden to say what interfaces we support and where
  123.  
  124.     virtual HRESULT GetMediaPositionInterface(REFIID riid,void **ppv);
  125.     STDMETHODIMP NonDelegatingQueryInterface(REFIID, void **);
  126.  
  127.     virtual HRESULT SourceThreadCanWait(BOOL bCanWait);
  128.     virtual HRESULT WaitForRenderTime();
  129.     virtual HRESULT CompleteStateChange(FILTER_STATE OldState);
  130.  
  131.     // Return internal information about this filter
  132.  
  133.     BOOL IsEndOfStream() { return m_bEOS; };
  134.     BOOL IsEndOfStreamDelivered() { return m_bEOSDelivered; };
  135.     BOOL IsStreaming() { return m_bStreaming; };
  136.     void SetAbortSignal(BOOL bAbort) { m_bAbort = bAbort; };
  137.     virtual void OnReceiveFirstSample(IMediaSample *pMediaSample) { };
  138.     CAMEvent *GetRenderEvent() { return &m_RenderEvent; };
  139.  
  140.     // Permit access to the transition state
  141.  
  142.     void Ready() { m_evComplete.Set(); };
  143.     void NotReady() { m_evComplete.Reset(); };
  144.     BOOL CheckReady() { return m_evComplete.Check(); };
  145.  
  146.     virtual int GetPinCount();
  147.     virtual CBasePin *GetPin(int n);
  148.     FILTER_STATE GetRealState();
  149.     void SendRepaint();
  150.     BOOL OnDisplayChange();
  151.     void SetRepaintStatus(BOOL bRepaint);
  152.  
  153.     // Override the filter and pin interface functions
  154.  
  155.     STDMETHODIMP Stop();
  156.     STDMETHODIMP Pause();
  157.     STDMETHODIMP Run(REFERENCE_TIME StartTime);
  158.     STDMETHODIMP GetState(DWORD dwMSecs,FILTER_STATE *State);
  159.     STDMETHODIMP FindPin(LPCWSTR Id, IPin **ppPin);
  160.  
  161.     // These are available for a quality management implementation
  162.  
  163.     virtual void OnRenderStart(IMediaSample *pMediaSample);
  164.     virtual void OnRenderEnd(IMediaSample *pMediaSample);
  165.     virtual HRESULT OnStartStreaming() { return NOERROR; };
  166.     virtual HRESULT OnStopStreaming() { return NOERROR; };
  167.     virtual void OnWaitStart() { };
  168.     virtual void OnWaitEnd() { };
  169.     virtual void PrepareRender() { };
  170.  
  171. #ifdef PERF
  172.     REFERENCE_TIME m_trRenderStart; // Just before we started drawing
  173.                                     // Set in OnRenderStart, Used in OnRenderEnd
  174.     int m_idBaseStamp;              // MSR_id for frame time stamp
  175.     int m_idBaseRenderTime;         // MSR_id for true wait time
  176.     int m_idBaseAccuracy;           // MSR_id for time frame is late (int)
  177. #endif
  178.  
  179.     virtual BOOL ScheduleSample(IMediaSample *pMediaSample);
  180.     virtual HRESULT GetSampleTimes(IMediaSample *pMediaSample,
  181.                                    REFERENCE_TIME *pStartTime,
  182.                                    REFERENCE_TIME *pEndTime);
  183.  
  184.     virtual HRESULT ShouldDrawSampleNow(IMediaSample *pMediaSample,
  185.                                         REFERENCE_TIME *ptrStart,
  186.                                         REFERENCE_TIME *ptrEnd);
  187.     virtual void SignalTimerFired();
  188.     virtual HRESULT CancelNotification();
  189.     virtual HRESULT PrepareReceive(IMediaSample *pMediaSample);
  190.     virtual HRESULT Render(IMediaSample *pMediaSample);
  191.     virtual HRESULT DisplayTimingInfo();
  192.     virtual HRESULT ClearPendingSample();
  193.     virtual HRESULT SendEndOfStream();
  194.     virtual HRESULT ResetEndOfStream();
  195.     virtual HRESULT StartStreaming();
  196.     virtual HRESULT StopStreaming();
  197.     virtual HRESULT EndOfStream();
  198.     virtual HRESULT BeginFlush();
  199.     virtual HRESULT EndFlush();
  200.     virtual HRESULT BreakConnect();
  201.     virtual HRESULT SetMediaType(const CMediaType *pmt);
  202.     virtual HRESULT CompleteConnect(IPin *pReceivePin);
  203.     virtual HRESULT Active();
  204.     virtual HRESULT Inactive();
  205.     virtual HRESULT Receive(IMediaSample *pMediaSample);
  206.     virtual BOOL HaveCurrentSample();
  207.     virtual IMediaSample *GetCurrentSample();
  208.  
  209.     // Derived classes MUST override these
  210.  
  211.     virtual HRESULT DoRenderSample(IMediaSample *pMediaSample) PURE;
  212.     virtual HRESULT CheckMediaType(const CMediaType *) PURE;
  213. };
  214.  
  215.  
  216. // CBaseVideoRenderer is a renderer class (see its ancestor class) and
  217. // it handles scheduling of media samples so that they are drawn at the
  218. // correct time by the reference clock.  It implements a degradation
  219. // strategy.  Possible degradation modes are:
  220. //    Drop frames here (only useful if the drawing takes significant time)
  221. //    Signal supplier (upstream) to drop some frame(s) - i.e. one-off skip.
  222. //    Signal supplier to change the frame rate - i.e. ongoing skipping.
  223. //    Or any combination of the above.
  224. // In order to determine what's useful to try we need to know what's going
  225. // on.  This is done by timing various operations (including the supplier).
  226. // This timing is done by using timeGetTime as it is accurate enough and
  227. // usually cheaper than calling the reference clock.  It also tells the
  228. // truth if there is an audio break and the reference clock stops.
  229. // We provide a number of public entry points (named OnXxxStart, OnXxxEnd)
  230. // which the rest of the renderer calls at significant moments.  These do
  231. // the timing.
  232.  
  233. // the number of frames that the sliding averages are averaged over.
  234. // the rule is (1024*NewObservation + (AVGPERIOD-1) * PreviousAverage)/AVGPERIOD
  235. #define AVGPERIOD 4
  236. #define DO_MOVING_AVG(avg,obs) (avg = (1024*obs + (AVGPERIOD-1)*avg)/AVGPERIOD)
  237. // Spot the bug in this macro - I can't. but it doesn't work!
  238.  
  239. class CBaseVideoRenderer : public CBaseRenderer,    // Base renderer class
  240.                            public IQualProp,        // Property page guff
  241.                            public IQualityControl   // Allow throttling
  242. {
  243. protected:
  244.  
  245.     // Hungarian:
  246.     //     tFoo is the time Foo in mSec (beware m_tStart from filter.h)
  247.     //     trBar is the time Bar by the reference clock
  248.  
  249.     //******************************************************************
  250.     // State variables to control synchronisation
  251.     //******************************************************************
  252.  
  253.     // Control of sending Quality messages.  We need to know whether
  254.     // we are in trouble (e.g. frames being dropped) and where the time
  255.     // is being spent.
  256.  
  257.     // When we drop a frame we play the next one early.
  258.     // The frame after that is likely to wait before drawing and counting this
  259.     // wait as spare time is unfair, so we count it as a zero wait.
  260.     // We therefore need to know whether we are playing frames early or not.
  261.  
  262.     int m_nNormal;                  // The number of consecutive frames
  263.                                     // drawn at their normal time (not early)
  264.                                     // -1 means we just dropped a frame.
  265.  
  266.     BOOL m_bDrawLateFrames;         // Don't drop any frames (debug and I'm
  267.                                     // not keen on people using it!)
  268.  
  269.     BOOL m_bSupplierHandlingQuality;// The response to Quality messages says
  270.                                     // our supplier is handling things.
  271.                                     // We will allow things to go extra late
  272.                                     // before dropping frames.  We will play
  273.                                     // very early after he has dropped one.
  274.  
  275.     // Control of scheduling, frame dropping etc.
  276.     // We need to know where the time is being spent so as to tell whether
  277.     // we should be taking action here, signalling supplier or what.
  278.     // The variables are initialised to a mode of NOT dropping frames.
  279.     // They will tell the truth after a few frames.
  280.     // We typically record a start time for an event, later we get the time
  281.     // again and subtract to get the elapsed time, and we average this over
  282.     // a few frames.  The average is used to tell what mode we are in.
  283.  
  284.     // Although these are reference times (64 bit) they are all DIFFERENCES
  285.     // between times which are small.  An int will go up to 214 secs before
  286.     // overflow.  Avoiding 64 bit multiplications and divisions seems
  287.     // worth while.
  288.  
  289.  
  290.  
  291.     // Audio-video throttling.  If the user has turned up audio quality
  292.     // very high (in principle it could be any other stream, not just audio)
  293.     // then we can receive cries for help via the graph manager.  In this case
  294.     // we put in a wait for some time after rendering each frame.
  295.     int m_trThrottle;
  296.  
  297.     // The time taken to render (i.e. BitBlt) frames controls which component
  298.     // needs to degrade.  If the blt is expensive, the renderer degrades.
  299.     // If the blt is cheap it's done anyway and the supplier degrades.
  300.     int m_trRenderAvg;              // Time frames are taking to blt
  301.     int m_trRenderLast;             // Time for last frame blt
  302.     int m_tRenderStart;             // Just before we started drawing (mSec)
  303.                                     // derived from timeGetTime.
  304.  
  305.     // When frames are dropped we will play the next frame as early as we can.
  306.     // If it was a false alarm and the machine is fast we slide gently back to
  307.     // normal timing.  To do this, we record the offset showing just how early
  308.     // we really are.  This will normally be negative meaning early or zero.
  309.     int m_trEarliness;
  310.  
  311.     // Target provides slow long-term feedback to try to reduce the
  312.     // average sync offset to zero.  Whenever a frame is actually rendered
  313.     // early we add a msec or two, whenever late we take off a few.
  314.     // We add or take off 1/32 of the error time.
  315.     // Eventually we should be hovering around zero.  For a really bad case
  316.     // where we were (say) 300mSec off, it might take 100 odd frames to
  317.     // settle down.  The rate of change of this is intended to be slower
  318.     // than any other mechanism in Quartz, thereby avoiding hunting.
  319.     int m_trTarget;
  320.  
  321.     // The proportion of time spent waiting for the right moment to blt
  322.     // controls whether we bother to drop a frame or whether we reckon that
  323.     // we're doing well enough that we can stand a one-frame glitch.
  324.     int m_trWaitAvg;                // Average of last few wait times
  325.                                     // (actually we just average how early
  326.                                     // we were).  Negative here means LATE.
  327.  
  328.     // The average inter-frame time.
  329.     // This is used to calculate the proportion of the time used by the
  330.     // three operations (supplying us, waiting, rendering)
  331.     int m_trFrameAvg;               // Average inter-frame time
  332.     int m_trDuration;               // duration of last frame.
  333.  
  334.     // Performance logging identifiers
  335.     int m_idTimeStamp;              // MSR_id for frame time stamp
  336.     int m_idEarliness;              // MSR_id for earliness fudge
  337.     int m_idTarget;                 // MSR_id for Target fudge
  338.     int m_idWaitReal;               // MSR_id for true wait time
  339.     int m_idWait;                   // MSR_id for wait time recorded
  340.     int m_idFrameAccuracy;          // MSR_id for time frame is late (int)
  341.     int m_idRenderAvg;              // MSR_id for Render time recorded (int)
  342.     int m_idSchLateTime;            // MSR_id for lateness at scheduler
  343.     int m_idQualityRate;            // MSR_id for Quality rate requested
  344.     int m_idQualityTime;            // MSR_id for Quality time requested
  345.     int m_idDecision;               // MSR_id for decision code
  346.     int m_idDuration;               // MSR_id for duration of a frame
  347.     int m_idThrottle;               // MSR_id for audio-video throttling
  348.     //int m_idDebug;                  // MSR_id for trace style debugging
  349.     //int m_idSendQuality;          // MSR_id for timing the notifications per se
  350.     REFERENCE_TIME m_trRememberStampForPerf;  // original time stamp of frame
  351.                                               // with no earliness fudges etc.
  352. #ifdef PERF
  353.     REFERENCE_TIME m_trRememberFrameForPerf;  // time when previous frame rendered
  354. #endif
  355.  
  356.     // debug...
  357.     int m_idFrameAvg;
  358.     int m_idWaitAvg;
  359.  
  360.     // PROPERTY PAGE
  361.     // This has edit fields that show the user what's happening
  362.     // These member variables hold these counts.
  363.  
  364.     int m_cFramesDropped;           // cumulative frames dropped IN THE RENDERER
  365.     int m_cFramesDrawn;             // Frames since streaming started seen BY THE
  366.                                     // RENDERER (some may be dropped upstream)
  367.  
  368.     // Next two support average sync offset and standard deviation of sync offset.
  369.     int m_iTotAcc;                  // Sum of accuracies in mSec
  370.     int m_iSumSqAcc;                // Sum of squares of (accuracies in mSec)
  371.  
  372.     // Next two allow jitter calculation.  Jitter is std deviation of frame time.
  373.     REFERENCE_TIME m_trLastDraw;    // Time of prev frame (for inter-frame times)
  374.     int m_iSumSqFrameTime;          // Sum of squares of (inter-frame time in mSec)
  375.     int m_iSumFrameTime;            // Sum of inter-frame times in mSec
  376.  
  377.     // To get performance statistics on frame rate, jitter etc, we need
  378.     // to record the lateness and inter-frame time.  What we actually need are the
  379.     // data above (sum, sum of squares and number of entries for each) but the data
  380.     // is generated just ahead of time and only later do we discover whether the
  381.     // frame was actually drawn or not.  So we have to hang on to the data
  382.     int m_trLate;                   // hold onto frame lateness
  383.     int m_trFrame;                  // hold onto inter-frame time
  384.  
  385.     int m_tStreamingStart;          // if streaming then time streaming started
  386.                                     // else time of last streaming session
  387.                                     // used for property page statistics
  388. #ifdef PERF
  389.     LONGLONG m_llTimeOffset;        // timeGetTime()*10000+m_llTimeOffset==ref time
  390. #endif
  391.  
  392. public:
  393.  
  394.  
  395.     CBaseVideoRenderer(CLSID RenderClass,    // CLSID for this renderer
  396.                        TCHAR *pName,         // Debug ONLY description
  397.                        LPUNKNOWN pUnk,       // Aggregated owner object
  398.                        HRESULT *phr);        // General OLE return code
  399.  
  400.     ~CBaseVideoRenderer();
  401.  
  402.     // IQualityControl methods - Notify allows audio-video throttling
  403.  
  404.     STDMETHODIMP SetSink( IQualityControl * piqc);
  405.     STDMETHODIMP Notify( IFilter * pSelf, Quality q);
  406.  
  407.     // These provide a full video quality management implementation
  408.  
  409.     void OnRenderStart(IMediaSample *pMediaSample);
  410.     void OnRenderEnd(IMediaSample *pMediaSample);
  411.     void OnWaitStart();
  412.     void OnWaitEnd();
  413.     HRESULT OnStartStreaming();
  414.     HRESULT OnStopStreaming();
  415.     void ThrottleWait();
  416.  
  417.     // Handle the statistics gathering for our quality management
  418.  
  419.     void PreparePerformanceData(int trLate, int trFrame);
  420.     virtual void RecordFrameLateness(int trLate, int trFrame);
  421.     virtual void OnDirectRender(IMediaSample *pMediaSample);
  422.     virtual HRESULT ResetStreamingTimes();
  423.     BOOL ScheduleSample(IMediaSample *pMediaSample);
  424.     HRESULT ShouldDrawSampleNow(IMediaSample *pMediaSample,
  425.                                 REFERENCE_TIME *ptrStart,
  426.                                 REFERENCE_TIME *ptrEnd);
  427.  
  428.     virtual HRESULT SendQuality(REFERENCE_TIME trLate, REFERENCE_TIME trRealStream);
  429.     STDMETHODIMP JoinFilterGraph(IFilterGraph * pGraph, LPCWSTR pName);
  430.  
  431. public:
  432.  
  433.     // IQualProp property page support
  434.  
  435.     STDMETHODIMP get_FramesDroppedInRenderer(int *cFramesDropped);
  436.     STDMETHODIMP get_FramesDrawn(int *pcFramesDrawn);
  437.     STDMETHODIMP get_AvgFrameRate(int *piAvgFrameRate);
  438.     STDMETHODIMP get_Jitter(int *piJitter);
  439.     STDMETHODIMP get_AvgSyncOffset(int *piAvg);
  440.     STDMETHODIMP get_DevSyncOffset(int *piDev);
  441.  
  442.     // Implement an IUnknown interface and expose IQualProp
  443.  
  444.     DECLARE_IUNKNOWN
  445.     STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,VOID **ppv);
  446. };
  447.  
  448. #endif // __RENBASE__
  449.  
  450.