Directshow source code analysis push mode, directshow source code
In windowsSDK, there is a push mode Source Filter example, which is located in the SDK installation directory samples \ C ++ \ Directshow \ Ball.
The following is a brief analysis:
Function: Live Source continuously generates video frames to demonstrate the trajectory of the ball that collides within the closed wall. Use the filter to construct the Filter Graph and its output results are as follows:
The inheritance structure of the class is as follows:
CBouncingBall inherited from CSource
CBallStream inherited from CSourceStream
As you can know, the output Pin of the Filter derived from CSource uses a data thread to push out the Sample continuously. The specific implementation is as follows:
//// DoBufferProcessingLoop /// Grabs a buffer and cballs the users processing function. // Overridable, so that different delivery styles can be catered. HRESULT CSourceStream: DoBufferProcessingLoop (void) {Command com; OnThreadStartPlay (); // called before data transmission starts. Subclass can be implemented to initialize do {while (! CheckRequest (& com) {IMediaSample * pSample; <span style = "white-space: pre "> </span> // get an empty Pin HRESULT hr = GetDeliveryBuffer (& pSample, NULL, NULL, 0) on the output Pin; if (FAILED (hr )) {Sleep (1); continue; // go round again. perhaps the error will go away // or the allocator is decommited & we will be asked to // exit soon .} // a function that must be implemented by the subclass. Fill in the actual Sample content hr = FillBuffer (pSample); if (hr = S_ OK) {hr = Deliver (pSamp Le); // send data pSample-> Release () to the next filter (); // downstream filter returns S_FALSE if it wants us to // stop or an error if it's reporting an error. if (hr! = S_ OK) {DbgLog (LOG_TRACE, 2, TEXT ("Deliver () returned % 08x; stopping"), hr); return S_ OK ;}} else if (hr = S_FALSE) {// derived class wants us to stop pushing datapSample-> Release (); DeliverEndOfStream (); return S_ OK ;} else {// derived class encountered an error pSample-> Release (); DbgLog (LOG_ERROR, 1, TEXT ("Error % 08lX from FillBuffer !!! "), Hr); DeliverEndOfStream (); m_pFilter-> policyevent (EC_ERRORABORT, hr, 0); return hr ;} // all paths release the sample} // For all commands sent to us there must be a Reply call! If (com = pai_run | com = pai_pause) {Reply (NOERROR);} else if (com! = Pai_stop) {Reply (DWORD) E_UNEXPECTED); DbgLog (LOG_ERROR, 1, TEXT ("Unexpected command !!! ") ;}} While (com! = Pai_stop); return S_FALSE ;}
CBaseFilter FillBuffer implementation:
<Pre name = "code" class = "cpp"> HRESULT RtpStream: FillBuffer (IMediaSample * pms) {CheckPointer (pms, E_POINTER); ASSERT (m_Ball); BYTE * pData; long lDataLen; pms-> GetPointer (& pData); lDataLen = pms-> GetSize (); ZeroMemory (pData, lDataLen); // screen display, set the image frame to black {CAutoLock cAutoLockShared (& m_cSharedState ); // If we haven't just cleared the buffer delete the old // ball and move the ball onm_Ball-> MoveBall (m_rtSampleTime-(LONG) m_iRepeatTime ); // draw The ball's current position m_Ball-> PlotBall (pData, m_BallPixel, m_iPixelSize) on the image frame; // The current time is the sample's startCRefTime rtStart = m_rtSampleTime; // Increment to find the finish timem_rtSampleTime + = (LONG) m_iRepeatTime; // timestamp pms-> SetTime (REFERENCE_TIME *) & rtStart, (REFERENCE_TIME *) & m_rtSampleTime);} pms-> SetSyncPoint (TRUE); return NOERROR ;}
It can be seen that m_Ball is a CBall class, mainly used to calculate and draw the position of the ball. To draw the ball at a new position, MoveBall is called first.
Calculate the new position, and call PlotBall to draw a ball at the calculated position.
The following are the key points of this example:
1. How to create an output Pin. Because FIlter-Pin adopts the CSource-CSourceStream class structure, the actual output Pin is generally created in the Filter constructor.
<Pre name = "code" class = "cpp"> RtpStreamFilter: RtpStreamFilter (LPUNKNOWN lpunk, HRESULT * phr): CSource (NAME ("Rtp Source Filter"), lpunk, CLSID_BouncingBall) {ASSERT (phr); CAutoLock cAutoLock (& m_cStateLock); // first allocates memory. m_paStreams is a pointer array because there is only one Pin, so assign a unit m_paStreams = (CSourceStream **) new RtpStream * [1]; if (m_paStreams = NULL) {if (phr) * phr = E_OUTOFMEMORY; return ;} // generate a new CSourceStream instance m_paStreams [0] = New RtpStream (phr, this, L "A Rtp Source Filter! "); If (m_paStreams [0] = NULL) {if (phr) * phr = E_OUTOFMEMORY; return ;}}
2. How to provide a list of preferred media types on the output Pin, including RGB32, RGB24, RGB565, RGB555, and RGB8? Code Description
//// GetMediaType // I _ prefer _ 5 formats-8, 16 (* 2 ), 24 or 32 bits per pixel and // I will suggest these with an image size of 320x240. however // I can accept any image size which gives me some space to bounce. /// A bit of fun: // 8 bit displays get red bils // 16 bit displays get blue // 24 bit see green // And 32 bit see yellow /// Prefered types shoshould be ordered by quality, zero as highest qua Lity // Therefore iPosition = // 0 return a 32bit mediatype // 1 return a 24bit mediatype // 2 return 16bit RGB565/3 return a 16bit mediatype (rgb555) // 4 return 8 bit palettised format // (iPosition> 4 is invalid) // HRESULT RtpStream: GetMediaType (int iPosition, CMediaType * pmt) {CheckPointer (pmt, E_POINTER ); // if pmt is NULL, returnCAutoLock cAutoLock (m_pFilter-> pStateLock (); if (iPosition <0) {return E _ INVALIDARG;} // Have we run off the end of types? If (iPosition> 4) {return VFW_S_NO_MORE_ITEMS;} VIDEOINFO * pvi = (VIDEOINFO *) pmt-> AllocFormatBuffer (sizeof (VIDEOINFO); if (NULL = pvi) return (E_OUTOFMEMORY); ZeroMemory (pvi, sizeof (VIDEOINFO); switch (iPosition) {case 0: {// Return our highest quality 32bit format // since we use RGB888 (the default for 32 bit), there is // no reason to use BI_BITFIELDS to specify the RGB // masks. also, not everything supports BI_BITFIELDS SetPaletteEntries (Yellow); pvi-> bmiHeader. biCompression = BI_RGB; pvi-> bmiHeader. biBitCount = 32; break;} case 1: {// Return our 24bit format SetPaletteEntries (Green); pvi-> bmiHeader. biCompression = BI_RGB; pvi-> bmiHeader. biBitCount = 24; break;} case 2: {// 16 bit per pixel RGB565 // Place the RGB masks as the first 3 doublewords in the palette area for (int I = 0; I <3; I ++) pvi-> TrueColorInfo. dwBitMasks [I] = bits565 [I]; SetPaletteEntries (Blue); pvi-> bmiHeader. biCompression = BI_BITFIELDS; pvi-> bmiHeader. biBitCount = 16; break;} case 3: {// 16 bits per pixel RGB555/Place the RGB masks as the first 3 doublewords in the palette area for (int I = 0; I <3; I ++) pvi-> TrueColorInfo. dwBitMasks [I] = bits555 [I]; SetPaletteEntries (Blue); pvi-> bmiHeader. biCompression = BI_BITFIELDS; pvi-> bmiHeader. biBitCount = 16; break;} case 4: {// 8 bit palettised SetPaletteEntries (Red); pvi-> bmiHeader. biCompression = BI_RGB; pvi-> bmiHeader. biBitCount = 8; pvi-> bmiHeader. biClrUsed = iPALETTE_COLORS; break; }}// (Adjust the parameters common to all formats ...) // put the optimal palette in placefor (int I = 0; I <iPALETTE_COLORS; I ++) {pvi-> TrueColorInfo. bmiColors [I]. rgbRed = m_Palette [I]. peRed; pvi-> TrueColorInfo. bmiColors [I]. rgbBlue = m_Palette [I]. peBlue; pvi-> TrueColorInfo. bmiColors [I]. rgbGreen = m_Palette [I]. peGreen; pvi-> TrueColorInfo. bmiColors [I]. rgbReserved = 0;} pvi-> bmiHeader. biSize = sizeof (BITMAPINFOHEADER); pvi-> bmiHeader. biWidth = m_iImageWidth; pvi-> bmiHeader. biHeight = m_iImageHeight; pvi-> bmiHeader. biPlanes = 1; pvi-> bmiHeader. biSizeImage = GetBitmapSize (& pvi-> bmiHeader); pvi-> bmiHeader. biClrImportant = 0; SetRectEmpty (& (pvi-> rcSource); // we want the whole image area rendered. setRectEmpty (& (pvi-> rcTarget); // no maid destination rectanglepmt-> SetType (& MEDIATYPE_Video); pmt-> SetFormatType (& FORMAT_VideoInfo ); pmt-> SetTemporalCompression (FALSE); // Work out the GUID for the subtype from the header info. const GUID SubTypeGUID = GetBitmapSubtype (& pvi-> bmiHeader); pmt-> SetSubtype (& SubTypeGUID); pmt-> SetSampleSize (pvi-> bmiHeader. biSizeImage); return NOERROR ;}
3. How do I check the media type when outputting the Pin connection? The following code
//// CheckMediaType//// We will accept 8, 16, 24 or 32 bit video formats, in any// image size that gives room to bounce.// Returns E_INVALIDARG if the mediatype is not acceptable//HRESULT RtpStream::CheckMediaType(const CMediaType *pMediaType){CheckPointer(pMediaType, E_POINTER);if ((*(pMediaType->Type()) != MEDIATYPE_Video) || // we only output video!(pMediaType->IsFixedSize())) // in fixed size samples{return E_INVALIDARG;}// Check for the subtypes we supportconst GUID *SubType = pMediaType->Subtype();if (SubType == NULL)return E_INVALIDARG;if ((*SubType != MEDIASUBTYPE_RGB8)&& (*SubType != MEDIASUBTYPE_RGB565)&& (*SubType != MEDIASUBTYPE_RGB555)&& (*SubType != MEDIASUBTYPE_RGB24)&& (*SubType != MEDIASUBTYPE_RGB32)){return E_INVALIDARG;}// Get the format area of the media typeVIDEOINFO *pvi = (VIDEOINFO *)pMediaType->Format();if (pvi == NULL)return E_INVALIDARG;// Check the image size. As my default ball is 10 pixels big// look for at least a 20x20 image. This is an arbitary size constraint,// but it avoids balls that are bigger than the picture...if ((pvi->bmiHeader.biWidth < 20) || (abs(pvi->bmiHeader.biHeight) < 20)){return E_INVALIDARG;}// Check if the image width & height have changedif (pvi->bmiHeader.biWidth != m_Ball->GetImageWidth() ||abs(pvi->bmiHeader.biHeight) != m_Ball->GetImageHeight()){// If the image width/height is changed, fail CheckMediaType() to force// the renderer to resize the image.return E_INVALIDARG;}return S_OK; // This format is acceptable.}4. After the output Pin connection is successful, you need to negotiate the attributes of the Sample used for data transmission after the Pin, such as the memory size used by the Sample.
//// DecideBufferSize//// This will always be called after the format has been sucessfully// negotiated. So we have a look at m_mt to see what size image we agreed.// Then we can ask for buffers of the correct size to contain them.//HRESULT RtpStream::DecideBufferSize(IMemAllocator *pAlloc,ALLOCATOR_PROPERTIES *pProperties){CheckPointer(pAlloc, E_POINTER);CheckPointer(pProperties, E_POINTER);CAutoLock cAutoLock(m_pFilter->pStateLock());HRESULT hr = NOERROR;VIDEOINFO *pvi = (VIDEOINFO *)m_mt.Format();pProperties->cBuffers = 1;pProperties->cbBuffer = pvi->bmiHeader.biSizeImage;ASSERT(pProperties->cbBuffer);// Ask the allocator to reserve us some sample memory, NOTE the function// can succeed (that is return NOERROR) but still not have allocated the// memory that we requested, so we must check we got whatever we wantedALLOCATOR_PROPERTIES Actual;hr = pAlloc->SetProperties(pProperties, &Actual);if (FAILED(hr)){return hr;}// Is this allocator unsuitableif (Actual.cbBuffer < pProperties->cbBuffer){return E_FAIL;}// Make sure that we have only 1 buffer (we erase the ball in the// old buffer to save having to zero a 200k+ buffer every time// we draw a frame)ASSERT(Actual.cBuffers == 1);return NOERROR;} 5. Respond to quality control events. Implement the Notify function on the output Pin.
STDMETHODIMP RtpStream::Notify(IBaseFilter * pSender, Quality q){// Adjust the repeat rate.if (q.Proportion <= 0){m_iRepeatTime = 1000; // We don't go slower than 1 per second}else{m_iRepeatTime = m_iRepeatTime * 1000 / q.Proportion;if (m_iRepeatTime > 1000){m_iRepeatTime = 1000; // We don't go slower than 1 per second}else if (m_iRepeatTime<10){m_iRepeatTime = 10; // We don't go faster than 100/sec}}// skip forwardsif (q.Late > 0)m_rtSampleTime += q.Late;return NOERROR;} // Notify
Come here and try again.