Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4140 lines
111 KiB

  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 - 1997 Microsoft Corporation. All Rights Reserved.
  9. //
  10. //--------------------------------------------------------------------------;
  11. // Base class hierachy for streams architecture, December 1994
  12. //=====================================================================
  13. //=====================================================================
  14. // The following classes are declared in this header:
  15. //
  16. //
  17. // CBaseMediaFilter Basic IMediaFilter support (abstract class)
  18. // CBaseFilter Support for IBaseFilter (incl. IMediaFilter)
  19. // CEnumPins Enumerate input and output pins
  20. // CEnumMediaTypes Enumerate the preferred pin formats
  21. // CBasePin Abstract base class for IPin interface
  22. // CBaseOutputPin Adds data provider member functions
  23. // CBaseInputPin Implements IMemInputPin interface
  24. // CMediaSample Basic transport unit for IMemInputPin
  25. // CBaseAllocator<_F> General list guff for most allocators
  26. // CMemAllocator Implements memory buffer allocation
  27. //
  28. //=====================================================================
  29. //=====================================================================
  30. void WINAPI CopyMediaType(AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource)
  31. {
  32. *pmtTarget = *pmtSource;
  33. if (pmtSource->cbFormat != 0) {
  34. _ASSERTE(pmtSource->pbFormat != NULL);
  35. pmtTarget->pbFormat = (PBYTE)CoTaskMemAlloc(pmtSource->cbFormat);
  36. if (pmtTarget->pbFormat == NULL) {
  37. pmtTarget->cbFormat = 0;
  38. } else {
  39. CopyMemory((PVOID)pmtTarget->pbFormat, (PVOID)pmtSource->pbFormat,
  40. pmtTarget->cbFormat);
  41. }
  42. }
  43. if (pmtTarget->pUnk != NULL) {
  44. pmtTarget->pUnk->AddRef();
  45. }
  46. }
  47. AM_MEDIA_TYPE * WINAPI CreateMediaType(AM_MEDIA_TYPE *pSrc)
  48. {
  49. _ASSERTE(pSrc);
  50. // Allocate a block of memory for the media type
  51. AM_MEDIA_TYPE *pMediaType =
  52. (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
  53. if (pMediaType == NULL) {
  54. return NULL;
  55. }
  56. // Copy the variable length format block
  57. CopyMediaType(pMediaType,pSrc);
  58. return pMediaType;
  59. }
  60. void WINAPI FreeMediaType(AM_MEDIA_TYPE& mt)
  61. {
  62. if (mt.cbFormat != 0) {
  63. CoTaskMemFree((PVOID)mt.pbFormat);
  64. // Strictly unnecessary but tidier
  65. mt.cbFormat = 0;
  66. mt.pbFormat = NULL;
  67. }
  68. if (mt.pUnk != NULL) {
  69. mt.pUnk->Release();
  70. mt.pUnk = NULL;
  71. }
  72. }
  73. void WINAPI DeleteMediaType(AM_MEDIA_TYPE *pmt)
  74. {
  75. // allow NULL pointers for coding simplicity
  76. if (pmt == NULL) {
  77. return;
  78. }
  79. FreeMediaType(*pmt);
  80. CoTaskMemFree((PVOID)pmt);
  81. }
  82. // HACK to make sure the right functions get created for our
  83. // concrete objects
  84. void MyCreateHackAllocator()
  85. {
  86. new CComObject<CAMMemAllocator>;
  87. new CComAggObject<CAMMemAllocator>(NULL);
  88. new CAMMediaSample<CAMMemAllocator>;
  89. }
  90. #if 0
  91. #define CONNECT_TRACE_LEVEL 3
  92. //=====================================================================
  93. //=====================================================================
  94. // Implements CBaseMediaFilter
  95. //=====================================================================
  96. //=====================================================================
  97. /* Constructor */
  98. CBaseMediaFilter::CBaseMediaFilter(const TCHAR *pName,
  99. LPUNKNOWN pUnk,
  100. CCritSec *pLock,
  101. REFCLSID clsid) :
  102. CUnknown(pName, pUnk),
  103. m_pLock(pLock),
  104. m_clsid(clsid),
  105. m_State(State_Stopped),
  106. m_pClock(NULL)
  107. {
  108. }
  109. /* Destructor */
  110. CBaseMediaFilter::~CBaseMediaFilter()
  111. {
  112. // must be stopped, but can't call Stop here since
  113. // our critsec has been destroyed.
  114. /* Release any clock we were using */
  115. if (m_pClock) {
  116. m_pClock->Release();
  117. m_pClock = NULL;
  118. }
  119. }
  120. /* Override this to say what interfaces we support and where */
  121. STDMETHODIMP
  122. CBaseMediaFilter::NonDelegatingQueryInterface(
  123. REFIID riid,
  124. void ** ppv)
  125. {
  126. if (riid == IID_IMediaFilter) {
  127. return GetInterface((IMediaFilter *) this, ppv);
  128. } else if (riid == IID_IPersist) {
  129. return GetInterface((IPersist *) this, ppv);
  130. } else {
  131. return CUnknown::NonDelegatingQueryInterface(riid, ppv);
  132. }
  133. }
  134. /* Return the filter's clsid */
  135. STDMETHODIMP
  136. CBaseMediaFilter::GetClassID(CLSID *pClsID)
  137. {
  138. CheckPointer(pClsID,E_POINTER);
  139. ValidateReadWritePtr(pClsID,sizeof(CLSID));
  140. *pClsID = m_clsid;
  141. return NOERROR;
  142. }
  143. /* Override this if your state changes are not done synchronously */
  144. STDMETHODIMP
  145. CBaseMediaFilter::GetState(DWORD dwMSecs, FILTER_STATE *State)
  146. {
  147. UNREFERENCED_PARAMETER(dwMSecs);
  148. CheckPointer(State,E_POINTER);
  149. ValidateReadWritePtr(State,sizeof(FILTER_STATE));
  150. *State = m_State;
  151. return S_OK;
  152. }
  153. /* Set the clock we will use for synchronisation */
  154. STDMETHODIMP
  155. CBaseMediaFilter::SetSyncSource(IReferenceClock *pClock)
  156. {
  157. CAutoLock cObjectLock(m_pLock);
  158. // Ensure the new one does not go away - even if the same as the old
  159. if (pClock) {
  160. pClock->AddRef();
  161. }
  162. // if we have a clock, release it
  163. if (m_pClock) {
  164. m_pClock->Release();
  165. }
  166. // Set the new reference clock (might be NULL)
  167. // Should we query it to ensure it is a clock? Consider for a debug build.
  168. m_pClock = pClock;
  169. return NOERROR;
  170. }
  171. /* Return the clock we are using for synchronisation */
  172. STDMETHODIMP
  173. CBaseMediaFilter::GetSyncSource(IReferenceClock **pClock)
  174. {
  175. CheckPointer(pClock,E_POINTER);
  176. ValidateReadWritePtr(pClock,sizeof(IReferenceClock *));
  177. CAutoLock cObjectLock(m_pLock);
  178. if (m_pClock) {
  179. // returning an interface... addref it...
  180. m_pClock->AddRef();
  181. }
  182. *pClock = (IReferenceClock*)m_pClock;
  183. return NOERROR;
  184. }
  185. /* Put the filter into a stopped state */
  186. STDMETHODIMP
  187. CBaseMediaFilter::Stop()
  188. {
  189. CAutoLock cObjectLock(m_pLock);
  190. m_State = State_Stopped;
  191. return S_OK;
  192. }
  193. /* Put the filter into a paused state */
  194. STDMETHODIMP
  195. CBaseMediaFilter::Pause()
  196. {
  197. CAutoLock cObjectLock(m_pLock);
  198. m_State = State_Paused;
  199. return S_OK;
  200. }
  201. // Put the filter into a running state.
  202. // The time parameter is the offset to be added to the samples'
  203. // stream time to get the reference time at which they should be presented.
  204. //
  205. // you can either add these two and compare it against the reference clock,
  206. // or you can call CBaseMediaFilter::StreamTime and compare that against
  207. // the sample timestamp.
  208. STDMETHODIMP
  209. CBaseMediaFilter::Run(REFERENCE_TIME tStart)
  210. {
  211. CAutoLock cObjectLock(m_pLock);
  212. // remember the stream time offset
  213. m_tStart = tStart;
  214. if (m_State == State_Stopped){
  215. HRESULT hr = Pause();
  216. if (FAILED(hr)) {
  217. return hr;
  218. }
  219. }
  220. m_State = State_Running;
  221. return S_OK;
  222. }
  223. //
  224. // return the current stream time - samples with start timestamps of this
  225. // time or before should be rendered by now
  226. HRESULT
  227. CBaseMediaFilter::StreamTime(CRefTime& rtStream)
  228. {
  229. // Caller must lock for synchronization
  230. // We can't grab the filter lock because we want to be able to call
  231. // this from worker threads without deadlocking
  232. if (m_pClock == NULL) {
  233. return VFW_E_NO_CLOCK;
  234. }
  235. // get the current reference time
  236. HRESULT hr = m_pClock->GetTime((REFERENCE_TIME*)&rtStream);
  237. if (FAILED(hr)) {
  238. return hr;
  239. }
  240. // subtract the stream offset to get stream time
  241. rtStream -= m_tStart;
  242. return S_OK;
  243. }
  244. //=====================================================================
  245. //=====================================================================
  246. // Implements CBaseFilter
  247. //=====================================================================
  248. //=====================================================================
  249. /* Override this to say what interfaces we support and where */
  250. STDMETHODIMP CBaseFilter::NonDelegatingQueryInterface(REFIID riid,
  251. void **ppv)
  252. {
  253. /* Do we have this interface */
  254. if (riid == IID_IBaseFilter) {
  255. return GetInterface((IBaseFilter *) this, ppv);
  256. } else if (riid == IID_IMediaFilter) {
  257. return GetInterface((IMediaFilter *) this, ppv);
  258. } else if (riid == IID_IPersist) {
  259. return GetInterface((IPersist *) this, ppv);
  260. } else if (riid == IID_IAMovieSetup) {
  261. return GetInterface((IAMovieSetup *) this, ppv);
  262. } else {
  263. return CUnknown::NonDelegatingQueryInterface(riid, ppv);
  264. }
  265. }
  266. /* Constructor */
  267. CBaseFilter::CBaseFilter(const TCHAR *pName,
  268. LPUNKNOWN pUnk,
  269. CCritSec *pLock,
  270. REFCLSID clsid) :
  271. CUnknown( pName, pUnk ),
  272. m_pLock(pLock),
  273. m_clsid(clsid),
  274. m_State(State_Stopped),
  275. m_pClock(NULL),
  276. m_pGraph(NULL),
  277. m_pSink(NULL),
  278. m_pName(NULL),
  279. m_PinVersion(1)
  280. {
  281. _ASSERTE(pLock != NULL);
  282. }
  283. /* Passes in a redundant HRESULT argument */
  284. CBaseFilter::CBaseFilter(TCHAR *pName,
  285. LPUNKNOWN pUnk,
  286. CCritSec *pLock,
  287. REFCLSID clsid,
  288. HRESULT *phr) :
  289. CUnknown( pName, pUnk ),
  290. m_pLock(pLock),
  291. m_clsid(clsid),
  292. m_State(State_Stopped),
  293. m_pClock(NULL),
  294. m_pGraph(NULL),
  295. m_pSink(NULL),
  296. m_pName(NULL),
  297. m_PinVersion(1)
  298. {
  299. _ASSERTE(pLock != NULL);
  300. UNREFERENCED_PARAMETER(phr);
  301. }
  302. /* Destructor */
  303. CBaseFilter::~CBaseFilter()
  304. {
  305. // NOTE we do NOT hold references on the filtergraph for m_pGraph or m_pSink
  306. // When we did we had the circular reference problem. Nothing would go away.
  307. if (m_pName)
  308. delete[] m_pName;
  309. // must be stopped, but can't call Stop here since
  310. // our critsec has been destroyed.
  311. /* Release any clock we were using */
  312. if (m_pClock) {
  313. m_pClock->Release();
  314. m_pClock = NULL;
  315. }
  316. }
  317. /* Return the filter's clsid */
  318. STDMETHODIMP
  319. CBaseFilter::GetClassID(CLSID *pClsID)
  320. {
  321. CheckPointer(pClsID,E_POINTER);
  322. ValidateReadWritePtr(pClsID,sizeof(CLSID));
  323. *pClsID = m_clsid;
  324. return NOERROR;
  325. }
  326. /* Override this if your state changes are not done synchronously */
  327. STDMETHODIMP
  328. CBaseFilter::GetState(DWORD dwMSecs, FILTER_STATE *State)
  329. {
  330. UNREFERENCED_PARAMETER(dwMSecs);
  331. CheckPointer(State,E_POINTER);
  332. ValidateReadWritePtr(State,sizeof(FILTER_STATE));
  333. *State = m_State;
  334. return S_OK;
  335. }
  336. /* Set the clock we will use for synchronisation */
  337. STDMETHODIMP
  338. CBaseFilter::SetSyncSource(IReferenceClock *pClock)
  339. {
  340. CAutoLock cObjectLock(m_pLock);
  341. // Ensure the new one does not go away - even if the same as the old
  342. if (pClock) {
  343. pClock->AddRef();
  344. }
  345. // if we have a clock, release it
  346. if (m_pClock) {
  347. m_pClock->Release();
  348. }
  349. // Set the new reference clock (might be NULL)
  350. // Should we query it to ensure it is a clock? Consider for a debug build.
  351. m_pClock = pClock;
  352. return NOERROR;
  353. }
  354. /* Return the clock we are using for synchronisation */
  355. STDMETHODIMP
  356. CBaseFilter::GetSyncSource(IReferenceClock **pClock)
  357. {
  358. CheckPointer(pClock,E_POINTER);
  359. ValidateReadWritePtr(pClock,sizeof(IReferenceClock *));
  360. CAutoLock cObjectLock(m_pLock);
  361. if (m_pClock) {
  362. // returning an interface... addref it...
  363. m_pClock->AddRef();
  364. }
  365. *pClock = (IReferenceClock*)m_pClock;
  366. return NOERROR;
  367. }
  368. // override CBaseMediaFilter Stop method, to deactivate any pins this
  369. // filter has.
  370. STDMETHODIMP
  371. CBaseFilter::Stop()
  372. {
  373. CAutoLock cObjectLock(m_pLock);
  374. HRESULT hr = NOERROR;
  375. // notify all pins of the state change
  376. if (m_State != State_Stopped) {
  377. int cPins = GetPinCount();
  378. for (int c = 0; c < cPins; c++) {
  379. CBasePin *pPin = GetPin(c);
  380. // Disconnected pins are not activated - this saves pins worrying
  381. // about this state themselves. We ignore the return code to make
  382. // sure everyone is inactivated regardless. The base input pin
  383. // class can return an error if it has no allocator but Stop can
  384. // be used to resync the graph state after something has gone bad
  385. if (pPin->IsConnected()) {
  386. HRESULT hrTmp = pPin->Inactive();
  387. if (FAILED(hrTmp) && SUCCEEDED(hr)) {
  388. hr = hrTmp;
  389. }
  390. }
  391. }
  392. }
  393. m_State = State_Stopped;
  394. return hr;
  395. }
  396. // override CBaseMediaFilter Pause method to activate any pins
  397. // this filter has (also called from Run)
  398. STDMETHODIMP
  399. CBaseFilter::Pause()
  400. {
  401. CAutoLock cObjectLock(m_pLock);
  402. // notify all pins of the change to active state
  403. if (m_State == State_Stopped) {
  404. int cPins = GetPinCount();
  405. for (int c = 0; c < cPins; c++) {
  406. CBasePin *pPin = GetPin(c);
  407. // Disconnected pins are not activated - this saves pins
  408. // worrying about this state themselves
  409. if (pPin->IsConnected()) {
  410. HRESULT hr = pPin->Active();
  411. if (FAILED(hr)) {
  412. return hr;
  413. }
  414. }
  415. }
  416. }
  417. m_State = State_Paused;
  418. return S_OK;
  419. }
  420. // Put the filter into a running state.
  421. // The time parameter is the offset to be added to the samples'
  422. // stream time to get the reference time at which they should be presented.
  423. //
  424. // you can either add these two and compare it against the reference clock,
  425. // or you can call CBaseFilter::StreamTime and compare that against
  426. // the sample timestamp.
  427. STDMETHODIMP
  428. CBaseFilter::Run(REFERENCE_TIME tStart)
  429. {
  430. CAutoLock cObjectLock(m_pLock);
  431. // remember the stream time offset
  432. m_tStart = tStart;
  433. if (m_State == State_Stopped){
  434. HRESULT hr = Pause();
  435. if (FAILED(hr)) {
  436. return hr;
  437. }
  438. }
  439. // notify all pins of the change to active state
  440. if (m_State != State_Running) {
  441. int cPins = GetPinCount();
  442. for (int c = 0; c < cPins; c++) {
  443. CBasePin *pPin = GetPin(c);
  444. // Disconnected pins are not activated - this saves pins
  445. // worrying about this state themselves
  446. if (pPin->IsConnected()) {
  447. HRESULT hr = pPin->Run(tStart);
  448. if (FAILED(hr)) {
  449. return hr;
  450. }
  451. }
  452. }
  453. }
  454. m_State = State_Running;
  455. return S_OK;
  456. }
  457. //
  458. // return the current stream time - samples with start timestamps of this
  459. // time or before should be rendered by now
  460. HRESULT
  461. CBaseFilter::StreamTime(CRefTime& rtStream)
  462. {
  463. // Caller must lock for synchronization
  464. // We can't grab the filter lock because we want to be able to call
  465. // this from worker threads without deadlocking
  466. if (m_pClock == NULL) {
  467. return VFW_E_NO_CLOCK;
  468. }
  469. // get the current reference time
  470. HRESULT hr = m_pClock->GetTime((REFERENCE_TIME*)&rtStream);
  471. if (FAILED(hr)) {
  472. return hr;
  473. }
  474. // subtract the stream offset to get stream time
  475. rtStream -= m_tStart;
  476. return S_OK;
  477. }
  478. /* Create an enumerator for the pins attached to this filter */
  479. STDMETHODIMP
  480. CBaseFilter::EnumPins(IEnumPins **ppEnum)
  481. {
  482. CheckPointer(ppEnum,E_POINTER);
  483. ValidateReadWritePtr(ppEnum,sizeof(IEnumPins *));
  484. /* Create a new ref counted enumerator */
  485. *ppEnum = new CEnumPins(this,
  486. NULL);
  487. return *ppEnum == NULL ? E_OUTOFMEMORY : NOERROR;
  488. }
  489. // default behaviour of FindPin is to assume pins are named
  490. // by their pin names
  491. STDMETHODIMP
  492. CBaseFilter::FindPin(
  493. LPCWSTR Id,
  494. IPin ** ppPin
  495. )
  496. {
  497. CheckPointer(ppPin,E_POINTER);
  498. ValidateReadWritePtr(ppPin,sizeof(IPin *));
  499. // We're going to search the pin list so maintain integrity
  500. CAutoLock lck(m_pLock);
  501. int iCount = GetPinCount();
  502. for (int i = 0; i < iCount; i++) {
  503. CBasePin *pPin = GetPin(i);
  504. _ASSERTE(pPin != NULL);
  505. if (0 == lstrcmpW(pPin->Name(), Id)) {
  506. // Found one that matches
  507. //
  508. // AddRef() and return it
  509. *ppPin = pPin;
  510. pPin->AddRef();
  511. return S_OK;
  512. }
  513. }
  514. *ppPin = NULL;
  515. return VFW_E_NOT_FOUND;
  516. }
  517. /* Return information about this filter */
  518. STDMETHODIMP
  519. CBaseFilter::QueryFilterInfo(FILTER_INFO * pInfo)
  520. {
  521. CheckPointer(pInfo,E_POINTER);
  522. ValidateReadWritePtr(pInfo,sizeof(FILTER_INFO));
  523. if (m_pName) {
  524. lstrcpynW(pInfo->achName, m_pName, sizeof(pInfo->achName)/sizeof(WCHAR));
  525. } else {
  526. pInfo->achName[0] = L'\0';
  527. }
  528. pInfo->pGraph = m_pGraph;
  529. if (m_pGraph)
  530. m_pGraph->AddRef();
  531. return NOERROR;
  532. }
  533. /* Provide the filter with a filter graph */
  534. STDMETHODIMP
  535. CBaseFilter::JoinFilterGraph(
  536. IFilterGraph * pGraph,
  537. LPCWSTR pName)
  538. {
  539. CAutoLock cObjectLock(m_pLock);
  540. // NOTE: we no longer hold references on the graph (m_pGraph, m_pSink)
  541. m_pGraph = pGraph;
  542. if (m_pGraph) {
  543. HRESULT hr = m_pGraph->QueryInterface(IID_IMediaEventSink,
  544. (void**) &m_pSink);
  545. if (FAILED(hr)) {
  546. _ASSERTE(m_pSink == NULL);
  547. }
  548. else m_pSink->Release(); // we do NOT keep a reference on it.
  549. } else {
  550. // if graph pointer is null, then we should
  551. // also release the IMediaEventSink on the same object - we don't
  552. // refcount it, so just set it to null
  553. m_pSink = NULL;
  554. }
  555. if (m_pName) {
  556. delete[] m_pName;
  557. m_pName = NULL;
  558. }
  559. if (pName) {
  560. DWORD nameLen = lstrlenW(pName)+1;
  561. m_pName = new WCHAR[nameLen];
  562. if (m_pName) {
  563. CopyMemory(m_pName, pName, nameLen*sizeof(WCHAR));
  564. } else {
  565. // !!! error here?
  566. }
  567. }
  568. return NOERROR;
  569. }
  570. // return a Vendor information string. Optional - may return E_NOTIMPL.
  571. // memory returned should be freed using CoTaskMemFree
  572. // default implementation returns E_NOTIMPL
  573. STDMETHODIMP
  574. CBaseFilter::QueryVendorInfo(
  575. LPWSTR* pVendorInfo)
  576. {
  577. UNREFERENCED_PARAMETER(pVendorInfo);
  578. return E_NOTIMPL;
  579. }
  580. // send an event notification to the filter graph if we know about it.
  581. // returns S_OK if delivered, S_FALSE if the filter graph does not sink
  582. // events, or an error otherwise.
  583. HRESULT
  584. CBaseFilter::NotifyEvent(
  585. long EventCode,
  586. long EventParam1,
  587. long EventParam2)
  588. {
  589. // Snapshot so we don't have to lock up
  590. IMediaEventSink *pSink = m_pSink;
  591. if (pSink) {
  592. return pSink->Notify(EventCode, EventParam1, EventParam2);
  593. } else {
  594. return E_NOTIMPL;
  595. }
  596. }
  597. /* This is the same idea as the media type version does for type enumeration
  598. on pins but for the list of pins available. So if the list of pins you
  599. provide changes dynamically then either override this virtual function
  600. to provide the version number, or more simply call IncrementPinVersion */
  601. LONG CBaseFilter::GetPinVersion()
  602. {
  603. return m_PinVersion;
  604. }
  605. /* Increment the current pin version cookie */
  606. void CBaseFilter::IncrementPinVersion()
  607. {
  608. InterlockedIncrement(&m_PinVersion);
  609. }
  610. /* register filter */
  611. HRESULT CBaseFilter::Register()
  612. {
  613. // get setup data, if it exists
  614. //
  615. LPAMOVIESETUP_FILTER psetupdata = GetSetupData();
  616. // check we've got data
  617. //
  618. if( NULL == psetupdata ) return S_FALSE;
  619. // init is ref counted so call just in case
  620. // we're being called cold.
  621. //
  622. HRESULT hr = CoInitialize( (LPVOID)NULL );
  623. _ASSERTE( SUCCEEDED(hr) );
  624. // get hold of IFilterMapper
  625. //
  626. IFilterMapper *pIFM;
  627. hr = CoCreateInstance( CLSID_FilterMapper
  628. , NULL
  629. , CLSCTX_INPROC_SERVER
  630. , IID_IFilterMapper
  631. , (void **)&pIFM );
  632. if( SUCCEEDED(hr) )
  633. {
  634. // register filter
  635. //
  636. hr = pIFM->RegisterFilter( *(psetupdata->clsID)
  637. , psetupdata->strName
  638. , psetupdata->dwMerit );
  639. if( SUCCEEDED(hr) )
  640. {
  641. // all its pins
  642. //
  643. for( UINT m1=0; m1 < psetupdata->nPins; m1++ )
  644. {
  645. hr = pIFM->RegisterPin( *(psetupdata->clsID)
  646. , psetupdata->lpPin[m1].strName
  647. , psetupdata->lpPin[m1].bRendered
  648. , psetupdata->lpPin[m1].bOutput
  649. , psetupdata->lpPin[m1].bZero
  650. , psetupdata->lpPin[m1].bMany
  651. , *(psetupdata->lpPin[m1].clsConnectsToFilter)
  652. , psetupdata->lpPin[m1].strConnectsToPin );
  653. if( SUCCEEDED(hr) )
  654. {
  655. // and each pin's media types
  656. //
  657. for( UINT m2=0; m2 < psetupdata->lpPin[m1].nMediaTypes; m2++ )
  658. {
  659. hr = pIFM->RegisterPinType( *(psetupdata->clsID)
  660. , psetupdata->lpPin[m1].strName
  661. , *(psetupdata->lpPin[m1].lpMediaType[m2].clsMajorType)
  662. , *(psetupdata->lpPin[m1].lpMediaType[m2].clsMinorType) );
  663. if( FAILED(hr) ) break;
  664. }
  665. if( FAILED(hr) ) break;
  666. }
  667. if( FAILED(hr) ) break;
  668. }
  669. }
  670. // free server
  671. //
  672. pIFM->Release();
  673. }
  674. // and clear up
  675. //
  676. CoFreeUnusedLibraries();
  677. CoUninitialize();
  678. return NOERROR;
  679. }
  680. /* unregister filter */
  681. HRESULT CBaseFilter::Unregister()
  682. {
  683. // get setup data, if it exists
  684. //
  685. LPAMOVIESETUP_FILTER psetupdata = GetSetupData();
  686. // check we've got data
  687. //
  688. if( NULL == psetupdata ) return S_FALSE;
  689. // OLE init is ref counted so call
  690. // just in case we're being called cold.
  691. //
  692. HRESULT hr = CoInitialize( (LPVOID)NULL );
  693. _ASSERTE( SUCCEEDED(hr) );
  694. // get hold of IFilterMapper
  695. //
  696. IFilterMapper *pIFM;
  697. hr = CoCreateInstance( CLSID_FilterMapper
  698. , NULL
  699. , CLSCTX_INPROC_SERVER
  700. , IID_IFilterMapper
  701. , (void **)&pIFM );
  702. if( SUCCEEDED(hr) )
  703. {
  704. // unregister filter
  705. // (as pins are subkeys of filter's CLSID key
  706. // they do not need to be removed separately).
  707. //
  708. hr = pIFM->UnregisterFilter( *(psetupdata->clsID) );
  709. // release interface
  710. //
  711. pIFM->Release();
  712. }
  713. // clear up
  714. //
  715. CoFreeUnusedLibraries();
  716. CoUninitialize();
  717. // handle one acceptable "error" - that
  718. // of filter not being registered!
  719. // (couldn't find a suitable #define'd
  720. // name for the error!)
  721. //
  722. if( 0x80070002 == hr)
  723. return NOERROR;
  724. else
  725. return hr;
  726. }
  727. //=====================================================================
  728. //=====================================================================
  729. // Implements CEnumPins
  730. //=====================================================================
  731. //=====================================================================
  732. /* NOTE The implementation of this class calls the CUnknown constructor
  733. with a NULL unknown pointer. This has the effect of making us a self
  734. contained class, ie any QueryInterface, AddRef or Release calls will be
  735. routed to the class's NonDelegatingUnknown methods. You will typically
  736. find that the classes that do this then override one or more of these
  737. virtual functions to provide more specialised behaviour. A good example
  738. of this is where a class wants to keep the QueryInterface internal but
  739. still wants it's lifetime controlled by the external object */
  740. CEnumPins::CEnumPins(CBaseFilter *pFilter,
  741. CEnumPins *pEnumPins) :
  742. m_Position(0),
  743. m_PinCount(0),
  744. m_pFilter(pFilter),
  745. m_cRef(1) // Already ref counted
  746. {
  747. #ifdef DEBUG
  748. m_dwCookie = DbgRegisterObjectCreation(TEXT("CEnumPins"));
  749. #endif
  750. /* We must be owned by a filter derived from CBaseFilter */
  751. _ASSERTE(pFilter != NULL);
  752. /* Hold a reference count on our filter */
  753. m_pFilter->AddRef();
  754. /* Are we creating a new enumerator */
  755. if (pEnumPins == NULL) {
  756. m_Version = m_pFilter->GetPinVersion();
  757. m_PinCount = m_pFilter->GetPinCount();
  758. } else {
  759. _ASSERTE(m_Position <= m_PinCount);
  760. m_Position = pEnumPins->m_Position;
  761. m_PinCount = pEnumPins->m_PinCount;
  762. m_Version = pEnumPins->m_Version;
  763. }
  764. }
  765. /* Destructor releases the reference count on our filter NOTE since we hold
  766. a reference count on the filter who created us we know it is safe to
  767. release it, no access can be made to it afterwards though as we have just
  768. caused the last reference count to go and the object to be deleted */
  769. CEnumPins::~CEnumPins()
  770. {
  771. m_pFilter->Release();
  772. #ifdef DEBUG
  773. DbgRegisterObjectDestruction(m_dwCookie);
  774. #endif
  775. }
  776. /* Override this to say what interfaces we support where */
  777. STDMETHODIMP
  778. CEnumPins::QueryInterface(REFIID riid,void **ppv)
  779. {
  780. CheckPointer(ppv, E_POINTER);
  781. /* Do we have this interface */
  782. if (riid == IID_IEnumPins || riid == IID_IUnknown) {
  783. return GetInterface((IEnumPins *) this, ppv);
  784. } else {
  785. return E_NOINTERFACE;
  786. }
  787. }
  788. STDMETHODIMP_(ULONG)
  789. CEnumPins::AddRef()
  790. {
  791. return InterlockedIncrement(&m_cRef);
  792. }
  793. STDMETHODIMP_(ULONG)
  794. CEnumPins::Release()
  795. {
  796. ULONG cRef = InterlockedDecrement(&m_cRef);
  797. if (cRef == 0) {
  798. delete this;
  799. }
  800. return cRef;
  801. }
  802. /* One of an enumerator's basic member functions allows us to create a cloned
  803. interface that initially has the same state. Since we are taking a snapshot
  804. of an object (current position and all) we must lock access at the start */
  805. STDMETHODIMP
  806. CEnumPins::Clone(IEnumPins **ppEnum)
  807. {
  808. CheckPointer(ppEnum,E_POINTER);
  809. ValidateReadWritePtr(ppEnum,sizeof(IEnumPins *));
  810. HRESULT hr = NOERROR;
  811. /* Check we are still in sync with the filter */
  812. if (AreWeOutOfSync() == TRUE) {
  813. *ppEnum = NULL;
  814. hr = VFW_E_ENUM_OUT_OF_SYNC;
  815. } else {
  816. *ppEnum = new CEnumPins(m_pFilter,
  817. this);
  818. if (*ppEnum == NULL) {
  819. hr = E_OUTOFMEMORY;
  820. }
  821. }
  822. return hr;
  823. }
  824. /* Return the next pin after the current position */
  825. STDMETHODIMP
  826. CEnumPins::Next(ULONG cPins, // place this many pins...
  827. IPin **ppPins, // ...in this array
  828. ULONG *pcFetched) // actual count passed returned here
  829. {
  830. CheckPointer(ppPins,E_POINTER);
  831. ValidateReadWritePtr(ppPins,cPins * sizeof(IPin *));
  832. _ASSERTE(ppPins);
  833. if (pcFetched!=NULL) {
  834. ValidateWritePtr(pcFetched, sizeof(ULONG));
  835. *pcFetched = 0; // default unless we succeed
  836. }
  837. // now check that the parameter is valid
  838. else if (cPins>1) { // pcFetched == NULL
  839. return E_INVALIDARG;
  840. }
  841. ULONG cFetched = 0; // increment as we get each one.
  842. /* Check we are still in sync with the filter */
  843. if (AreWeOutOfSync() == TRUE) {
  844. return VFW_E_ENUM_OUT_OF_SYNC;
  845. }
  846. /* Calculate the number of available pins */
  847. int cRealPins = min(m_PinCount - m_Position, (int) cPins);
  848. if (cRealPins == 0) {
  849. return S_FALSE;
  850. }
  851. /* Return each pin interface NOTE GetPin returns CBasePin * not addrefed
  852. so we must QI for the IPin (which increments its reference count)
  853. If while we are retrieving a pin from the filter an error occurs we
  854. assume that our internal state is stale with respect to the filter
  855. (for example someone has deleted a pin) so we
  856. return VFW_E_ENUM_OUT_OF_SYNC */
  857. while (cRealPins--) {
  858. /* Get the next pin object from the filter */
  859. CBasePin *pPin = m_pFilter->GetPin(m_Position++);
  860. if (pPin == NULL) {
  861. // If this happend, and it's not the first time through, then we've got a problem,
  862. // since we should really go back and release the iPins, which we have previously
  863. // AddRef'ed.
  864. _ASSERTE( cFetched==0 );
  865. return VFW_E_ENUM_OUT_OF_SYNC;
  866. }
  867. /* From the object get an IPin interface */
  868. *ppPins = pPin;
  869. pPin->AddRef();
  870. cFetched++;
  871. ppPins++;
  872. }
  873. if (pcFetched!=NULL) {
  874. *pcFetched = cFetched;
  875. }
  876. return (cPins==cFetched ? NOERROR : S_FALSE);
  877. }
  878. /* Skip over one or more entries in the enumerator */
  879. STDMETHODIMP
  880. CEnumPins::Skip(ULONG cPins)
  881. {
  882. /* Check we are still in sync with the filter */
  883. if (AreWeOutOfSync() == TRUE) {
  884. return VFW_E_ENUM_OUT_OF_SYNC;
  885. }
  886. /* Work out how many pins are left to skip over */
  887. /* We could position at the end if we are asked to skip too many... */
  888. /* ..which would match the base implementation for CEnumMediaTypes::Skip */
  889. ULONG PinsLeft = m_PinCount - m_Position;
  890. if (cPins > PinsLeft) {
  891. return S_FALSE;
  892. }
  893. m_Position += cPins;
  894. return NOERROR;
  895. }
  896. /* Set the current position back to the start */
  897. /* Reset has 3 simple steps:
  898. *
  899. * Set position to head of list
  900. * Sync enumerator with object being enumerated
  901. * return S_OK
  902. */
  903. STDMETHODIMP
  904. CEnumPins::Reset()
  905. {
  906. m_Version = m_pFilter->GetPinVersion();
  907. m_Position = 0;
  908. return S_OK;
  909. }
  910. //=====================================================================
  911. //=====================================================================
  912. // Implements CEnumMediaTypes
  913. //=====================================================================
  914. //=====================================================================
  915. /* NOTE The implementation of this class calls the CUnknown constructor
  916. with a NULL unknown pointer. This has the effect of making us a self
  917. contained class, ie any QueryInterface, AddRef or Release calls will be
  918. routed to the class's NonDelegatingUnknown methods. You will typically
  919. find that the classes that do this then override one or more of these
  920. virtual functions to provide more specialised behaviour. A good example
  921. of this is where a class wants to keep the QueryInterface internal but
  922. still wants it's lifetime controlled by the external object */
  923. CEnumMediaTypes::CEnumMediaTypes(CBasePin *pPin,
  924. CEnumMediaTypes *pEnumMediaTypes) :
  925. m_Position(0),
  926. m_pPin(pPin),
  927. m_cRef(1)
  928. {
  929. #ifdef DEBUG
  930. m_dwCookie = DbgRegisterObjectCreation(TEXT("CEnumMediaTypes"));
  931. #endif
  932. /* We must be owned by a pin derived from CBasePin */
  933. _ASSERTE(pPin != NULL);
  934. /* Hold a reference count on our pin */
  935. m_pPin->AddRef();
  936. /* Are we creating a new enumerator */
  937. if (pEnumMediaTypes == NULL) {
  938. m_Version = m_pPin->GetMediaTypeVersion();
  939. return;
  940. }
  941. m_Position = pEnumMediaTypes->m_Position;
  942. m_Version = pEnumMediaTypes->m_Version;
  943. }
  944. /* Destructor releases the reference count on our base pin. NOTE since we hold
  945. a reference count on the pin who created us we know it is safe to release
  946. it, no access can be made to it afterwards though as we might have just
  947. caused the last reference count to go and the object to be deleted */
  948. CEnumMediaTypes::~CEnumMediaTypes()
  949. {
  950. #ifdef DEBUG
  951. DbgRegisterObjectDestruction(m_dwCookie);
  952. #endif
  953. m_pPin->Release();
  954. }
  955. /* Override this to say what interfaces we support where */
  956. STDMETHODIMP
  957. CEnumMediaTypes::QueryInterface(REFIID riid,void **ppv)
  958. {
  959. CheckPointer(ppv, E_POINTER);
  960. /* Do we have this interface */
  961. if (riid == IID_IEnumMediaTypes || riid == IID_IUnknown) {
  962. return GetInterface((IEnumMediaTypes *) this, ppv);
  963. } else {
  964. return E_NOINTERFACE;
  965. }
  966. }
  967. STDMETHODIMP_(ULONG)
  968. CEnumMediaTypes::AddRef()
  969. {
  970. return InterlockedIncrement(&m_cRef);
  971. }
  972. STDMETHODIMP_(ULONG)
  973. CEnumMediaTypes::Release()
  974. {
  975. ULONG cRef = InterlockedDecrement(&m_cRef);
  976. if (cRef == 0) {
  977. delete this;
  978. }
  979. return cRef;
  980. }
  981. /* One of an enumerator's basic member functions allows us to create a cloned
  982. interface that initially has the same state. Since we are taking a snapshot
  983. of an object (current position and all) we must lock access at the start */
  984. STDMETHODIMP
  985. CEnumMediaTypes::Clone(IEnumMediaTypes **ppEnum)
  986. {
  987. CheckPointer(ppEnum,E_POINTER);
  988. ValidateReadWritePtr(ppEnum,sizeof(IEnumMediaTypes *));
  989. HRESULT hr = NOERROR;
  990. /* Check we are still in sync with the pin */
  991. if (AreWeOutOfSync() == TRUE) {
  992. *ppEnum = NULL;
  993. hr = VFW_E_ENUM_OUT_OF_SYNC;
  994. } else {
  995. *ppEnum = new CEnumMediaTypes(m_pPin,
  996. this);
  997. if (*ppEnum == NULL) {
  998. hr = E_OUTOFMEMORY;
  999. }
  1000. }
  1001. return hr;
  1002. }
  1003. /* Enumerate the next pin(s) after the current position. The client using this
  1004. interface passes in a pointer to an array of pointers each of which will
  1005. be filled in with a pointer to a fully initialised media type format
  1006. Return NOERROR if it all works,
  1007. S_FALSE if fewer than cMediaTypes were enumerated.
  1008. VFW_E_ENUM_OUT_OF_SYNC if the enumerator has been broken by
  1009. state changes in the filter
  1010. The actual count always correctly reflects the number of types in the array.
  1011. */
  1012. STDMETHODIMP
  1013. CEnumMediaTypes::Next(ULONG cMediaTypes, // place this many types...
  1014. AM_MEDIA_TYPE **ppMediaTypes, // ...in this array
  1015. ULONG *pcFetched) // actual count passed
  1016. {
  1017. CheckPointer(ppMediaTypes,E_POINTER);
  1018. ValidateReadWritePtr(ppMediaTypes,cMediaTypes * sizeof(AM_MEDIA_TYPE *));
  1019. /* Check we are still in sync with the pin */
  1020. if (AreWeOutOfSync() == TRUE) {
  1021. return VFW_E_ENUM_OUT_OF_SYNC;
  1022. }
  1023. if (pcFetched!=NULL) {
  1024. ValidateWritePtr(pcFetched, sizeof(ULONG));
  1025. *pcFetched = 0; // default unless we succeed
  1026. }
  1027. // now check that the parameter is valid
  1028. else if (cMediaTypes>1) { // pcFetched == NULL
  1029. return E_INVALIDARG;
  1030. }
  1031. ULONG cFetched = 0; // increment as we get each one.
  1032. /* Return each media type by asking the filter for them in turn - If we
  1033. have an error code retured to us while we are retrieving a media type
  1034. we assume that our internal state is stale with respect to the filter
  1035. (for example the window size changing) so we return
  1036. VFW_E_ENUM_OUT_OF_SYNC */
  1037. while (cMediaTypes) {
  1038. CMediaType cmt;
  1039. HRESULT hr = m_pPin->GetMediaType(m_Position++, &cmt);
  1040. if (S_OK != hr) {
  1041. break;
  1042. }
  1043. /* We now have a CMediaType object that contains the next media type
  1044. but when we assign it to the array position we CANNOT just assign
  1045. the AM_MEDIA_TYPE structure because as soon as the object goes out of
  1046. scope it will delete the memory we have just copied. The function
  1047. we use is CreateMediaType which allocates a task memory block */
  1048. /* Transfer across the format block manually to save an allocate
  1049. and free on the format block and generally go faster */
  1050. *ppMediaTypes = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
  1051. if (*ppMediaTypes == NULL) {
  1052. break;
  1053. }
  1054. /* Do a regular copy */
  1055. **ppMediaTypes = (AM_MEDIA_TYPE)cmt;
  1056. /* Make sure the destructor doesn't free these */
  1057. cmt.pbFormat = NULL;
  1058. cmt.cbFormat = NULL;
  1059. cmt.pUnk = NULL;
  1060. ppMediaTypes++;
  1061. cFetched++;
  1062. cMediaTypes--;
  1063. }
  1064. if (pcFetched!=NULL) {
  1065. *pcFetched = cFetched;
  1066. }
  1067. return ( cMediaTypes==0 ? NOERROR : S_FALSE );
  1068. }
  1069. /* Skip over one or more entries in the enumerator */
  1070. STDMETHODIMP
  1071. CEnumMediaTypes::Skip(ULONG cMediaTypes)
  1072. {
  1073. /* Check we are still in sync with the pin */
  1074. if (AreWeOutOfSync() == TRUE) {
  1075. return VFW_E_ENUM_OUT_OF_SYNC;
  1076. }
  1077. m_Position += cMediaTypes;
  1078. /* See if we're over the end */
  1079. CMediaType cmt;
  1080. return S_OK == m_pPin->GetMediaType(m_Position - 1, &cmt) ? S_OK : S_FALSE;
  1081. }
  1082. /* Set the current position back to the start */
  1083. /* Reset has 3 simple steps:
  1084. *
  1085. * set position to head of list
  1086. * sync enumerator with object being enumerated
  1087. * return S_OK
  1088. */
  1089. STDMETHODIMP
  1090. CEnumMediaTypes::Reset()
  1091. {
  1092. m_Position = 0;
  1093. // Bring the enumerator back into step with the current state. This
  1094. // may be a noop but ensures that the enumerator will be valid on the
  1095. // next call.
  1096. m_Version = m_pPin->GetMediaTypeVersion();
  1097. return NOERROR;
  1098. }
  1099. //=====================================================================
  1100. //=====================================================================
  1101. // Implements CBasePin
  1102. //=====================================================================
  1103. //=====================================================================
  1104. /* NOTE The implementation of this class calls the CUnknown constructor with
  1105. a NULL outer unknown pointer. This has the effect of making us a self
  1106. contained class, ie any QueryInterface, AddRef or Release calls will be
  1107. routed to the class's NonDelegatingUnknown methods. You will typically
  1108. find that the classes that do this then override one or more of these
  1109. virtual functions to provide more specialised behaviour. A good example
  1110. of this is where a class wants to keep the QueryInterface internal but
  1111. still wants its lifetime controlled by the external object */
  1112. /* Constructor */
  1113. CBasePin::CBasePin(TCHAR *pObjectName,
  1114. CBaseFilter *pFilter,
  1115. CCritSec *pLock,
  1116. HRESULT *phr,
  1117. LPCWSTR pName,
  1118. PIN_DIRECTION dir) :
  1119. CUnknown( pObjectName, NULL ),
  1120. m_pFilter(pFilter),
  1121. m_pLock(pLock),
  1122. m_pName(NULL),
  1123. m_Connected(NULL),
  1124. m_dir(dir),
  1125. m_bRunTimeError(FALSE),
  1126. m_pQSink(NULL),
  1127. m_TypeVersion(1),
  1128. m_tStart(),
  1129. m_tStop(MAX_TIME),
  1130. m_dRate(1.0)
  1131. {
  1132. /* WARNING - pFilter is often not a properly constituted object at
  1133. this state (in particular QueryInterface may not work) - this
  1134. is because its owner is often its containing object and we
  1135. have been called from the containing object's constructor so
  1136. the filter's owner has not yet had its CUnknown constructor
  1137. called
  1138. */
  1139. _ASSERTE(pFilter != NULL);
  1140. _ASSERTE(pLock != NULL);
  1141. if (pName) {
  1142. DWORD nameLen = lstrlenW(pName)+1;
  1143. m_pName = new WCHAR[nameLen];
  1144. if (m_pName) {
  1145. CopyMemory(m_pName, pName, nameLen*sizeof(WCHAR));
  1146. }
  1147. }
  1148. #ifdef DEBUG
  1149. m_cRef = 0;
  1150. #endif
  1151. }
  1152. /* Destructor since a connected pin holds a reference count on us there is
  1153. no way that we can be deleted unless we are not currently connected */
  1154. CBasePin::~CBasePin()
  1155. {
  1156. // We don't call disconnect because if the filter is going away
  1157. // all the pins must have a reference count of zero so they must
  1158. // have been disconnected anyway - (but check the assumption)
  1159. _ASSERTE(m_Connected == FALSE);
  1160. if (m_pName)
  1161. delete[] m_pName;
  1162. // check the internal reference count is consistent
  1163. _ASSERTE(m_cRef == 0);
  1164. }
  1165. /* Override this to say what interfaces we support and where */
  1166. STDMETHODIMP
  1167. CBasePin::NonDelegatingQueryInterface(REFIID riid, void ** ppv)
  1168. {
  1169. /* Do we have this interface */
  1170. if (riid == IID_IPin) {
  1171. return GetInterface((IPin *) this, ppv);
  1172. } else if (riid == IID_IQualityControl) {
  1173. return GetInterface((IQualityControl *) this, ppv);
  1174. } else {
  1175. return CUnknown::NonDelegatingQueryInterface(riid, ppv);
  1176. }
  1177. }
  1178. /* Override to increment the owning filter's reference count */
  1179. STDMETHODIMP_(ULONG)
  1180. CBasePin::NonDelegatingAddRef()
  1181. {
  1182. _ASSERTE(InterlockedIncrement(&m_cRef) > 0);
  1183. return m_pFilter->AddRef();
  1184. }
  1185. /* Override to decrement the owning filter's reference count */
  1186. STDMETHODIMP_(ULONG)
  1187. CBasePin::NonDelegatingRelease()
  1188. {
  1189. _ASSERTE(InterlockedDecrement(&m_cRef) >= 0);
  1190. return m_pFilter->Release();
  1191. }
  1192. /* Displays pin connection information */
  1193. #ifdef DEBUG
  1194. void
  1195. CBasePin::DisplayPinInfo(IPin *pReceivePin)
  1196. {
  1197. if (DbgCheckModuleLevel(LOG_TRACE, CONNECT_TRACE_LEVEL)) {
  1198. PIN_INFO ConnectPinInfo;
  1199. PIN_INFO ReceivePinInfo;
  1200. if (FAILED(QueryPinInfo(&ConnectPinInfo))) {
  1201. lstrcpyW(ConnectPinInfo.achName, L"Bad Pin");
  1202. } else {
  1203. QueryPinInfoReleaseFilter(ConnectPinInfo);
  1204. }
  1205. if (FAILED(pReceivePin->QueryPinInfo(&ReceivePinInfo))) {
  1206. lstrcpyW(ReceivePinInfo.achName, L"Bad Pin");
  1207. } else {
  1208. QueryPinInfoReleaseFilter(ReceivePinInfo);
  1209. }
  1210. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Trying to connect Pins :")));
  1211. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" <%ls>"), ConnectPinInfo.achName));
  1212. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" <%ls>"), ReceivePinInfo.achName));
  1213. }
  1214. }
  1215. #endif
  1216. /* Displays general information on the pin media type */
  1217. #ifdef DEBUG
  1218. void CBasePin::DisplayTypeInfo(IPin *pPin, const CMediaType *pmt)
  1219. {
  1220. UNREFERENCED_PARAMETER(pPin);
  1221. if (DbgCheckModuleLevel(LOG_TRACE, CONNECT_TRACE_LEVEL)) {
  1222. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Trying media type:")));
  1223. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" major type: %s"),
  1224. GuidNames[*pmt->Type()]));
  1225. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" sub type : %s"),
  1226. GuidNames[*pmt->Subtype()]));
  1227. }
  1228. }
  1229. #endif
  1230. /* Asked to connect to a pin. A pin is always attached to an owning filter
  1231. object so we always delegate our locking to that object. We first of all
  1232. retrieve a media type enumerator for the input pin and see if we accept
  1233. any of the formats that it would ideally like, failing that we retrieve
  1234. our enumerator and see if it will accept any of our preferred types */
  1235. STDMETHODIMP
  1236. CBasePin::Connect(
  1237. IPin * pReceivePin,
  1238. const AM_MEDIA_TYPE *pmt // optional media type
  1239. )
  1240. {
  1241. CheckPointer(pReceivePin,E_POINTER);
  1242. ValidateReadPtr(pReceivePin,sizeof(IPin));
  1243. CAutoLock cObjectLock(m_pLock);
  1244. DisplayPinInfo(pReceivePin);
  1245. /* See if we are already connected */
  1246. if (m_Connected) {
  1247. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Already connected")));
  1248. return VFW_E_ALREADY_CONNECTED;
  1249. }
  1250. /* See if the filter is active */
  1251. if (!IsStopped()) {
  1252. return VFW_E_NOT_STOPPED;
  1253. }
  1254. // Find a mutually agreeable media type -
  1255. // Pass in the template media type. If this is partially specified,
  1256. // each of the enumerated media types will need to be checked against
  1257. // it. If it is non-null and fully specified, we will just try to connect
  1258. // with this.
  1259. const CMediaType * ptype = (CMediaType*)pmt;
  1260. HRESULT hr = AgreeMediaType(pReceivePin, ptype);
  1261. if (FAILED(hr)) {
  1262. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Failed to agree type")));
  1263. BreakConnect();
  1264. return hr;
  1265. }
  1266. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Connection succeeded")));
  1267. return NOERROR;
  1268. }
  1269. // given a specific media type, attempt a connection (includes
  1270. // checking that the type is acceptable to this pin)
  1271. HRESULT
  1272. CBasePin::AttemptConnection(
  1273. IPin* pReceivePin, // connect to this pin
  1274. const CMediaType* pmt // using this type
  1275. )
  1276. {
  1277. // Check that the connection is valid -- need to do this for every
  1278. // connect attempt since BreakConnect will undo it.
  1279. HRESULT hr = CheckConnect(pReceivePin);
  1280. if (FAILED(hr)) {
  1281. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("CheckConnect failed")));
  1282. BreakConnect();
  1283. return hr;
  1284. }
  1285. DisplayTypeInfo(pReceivePin, pmt);
  1286. /* Check we will accept this media type */
  1287. hr = CheckMediaType(pmt);
  1288. if (hr == NOERROR) {
  1289. /* Make ourselves look connected otherwise ReceiveConnection
  1290. may not be able to complete the connection
  1291. */
  1292. m_Connected = pReceivePin;
  1293. m_Connected->AddRef();
  1294. SetMediaType(pmt);
  1295. /* See if the other pin will accept this type */
  1296. hr = pReceivePin->ReceiveConnection((IPin *)this, pmt);
  1297. if (SUCCEEDED(hr)) {
  1298. /* Complete the connection */
  1299. hr = CompleteConnect(pReceivePin);
  1300. if (SUCCEEDED(hr)) {
  1301. return hr;
  1302. } else {
  1303. DbgLog((LOG_TRACE,
  1304. CONNECT_TRACE_LEVEL,
  1305. TEXT("Failed to complete connection")));
  1306. pReceivePin->Disconnect();
  1307. }
  1308. }
  1309. } else {
  1310. // we cannot use this media type
  1311. // return a specific media type error if there is one
  1312. // or map a general failure code to something more helpful
  1313. // (in particular S_FALSE gets changed to an error code)
  1314. if (SUCCEEDED(hr) ||
  1315. (hr == E_FAIL) ||
  1316. (hr == E_INVALIDARG)) {
  1317. hr = VFW_E_TYPE_NOT_ACCEPTED;
  1318. }
  1319. }
  1320. // BreakConnect and release any connection here in case CheckMediaType
  1321. // failed, or if we set anything up during a call back during
  1322. // ReceiveConnection.
  1323. BreakConnect();
  1324. /* If failed then undo our state */
  1325. if (m_Connected) {
  1326. m_Connected->Release();
  1327. m_Connected = NULL;
  1328. }
  1329. return hr;
  1330. }
  1331. /* Given an enumerator we cycle through all the media types it proposes and
  1332. firstly suggest them to our derived pin class and if that succeeds try
  1333. them with the pin in a ReceiveConnection call. This means that if our pin
  1334. proposes a media type we still check in here that we can support it. This
  1335. is deliberate so that in simple cases the enumerator can hold all of the
  1336. media types even if some of them are not really currently available */
  1337. HRESULT CBasePin::TryMediaTypes(
  1338. IPin *pReceivePin,
  1339. const CMediaType *pmt,
  1340. IEnumMediaTypes *pEnum)
  1341. {
  1342. /* Reset the current enumerator position */
  1343. HRESULT hr = pEnum->Reset();
  1344. if (FAILED(hr)) {
  1345. return hr;
  1346. }
  1347. CMediaType *pMediaType = NULL;
  1348. ULONG ulMediaCount = 0;
  1349. // attempt to remember a specific error code if there is one
  1350. HRESULT hrFailure = S_OK;
  1351. for (;;) {
  1352. /* Retrieve the next media type NOTE each time round the loop the
  1353. enumerator interface will allocate another AM_MEDIA_TYPE structure
  1354. If we are successful then we copy it into our output object, if
  1355. not then we must delete the memory allocated before returning */
  1356. hr = pEnum->Next(1, (AM_MEDIA_TYPE**)&pMediaType,&ulMediaCount);
  1357. if (hr != S_OK) {
  1358. if (S_OK == hrFailure) {
  1359. hrFailure = VFW_E_NO_ACCEPTABLE_TYPES;
  1360. }
  1361. return hrFailure;
  1362. }
  1363. _ASSERTE(ulMediaCount == 1);
  1364. _ASSERTE(pMediaType);
  1365. // check that this matches the partial type (if any)
  1366. if ((pmt == NULL) ||
  1367. pMediaType->MatchesPartial(pmt)) {
  1368. hr = AttemptConnection(pReceivePin, pMediaType);
  1369. // attempt to remember a specific error code
  1370. if (FAILED(hr) &&
  1371. SUCCEEDED(hrFailure) &&
  1372. (hr != E_FAIL) &&
  1373. (hr != E_INVALIDARG) &&
  1374. (hr != VFW_E_TYPE_NOT_ACCEPTED)) {
  1375. hrFailure = hr;
  1376. }
  1377. } else {
  1378. hr = VFW_E_NO_ACCEPTABLE_TYPES;
  1379. }
  1380. DeleteMediaType(pMediaType);
  1381. if (S_OK == hr) {
  1382. return hr;
  1383. }
  1384. }
  1385. }
  1386. /* This is called to make the connection, including the taask of finding
  1387. a media type for the pin connection. pmt is the proposed media type
  1388. from the Connect call: if this is fully specified, we will try that.
  1389. Otherwise we enumerate and try all the input pin's types first and
  1390. if that fails we then enumerate and try all our preferred media types.
  1391. For each media type we check it against pmt (if non-null and partially
  1392. specified) as well as checking that both pins will accept it.
  1393. */
  1394. HRESULT CBasePin::AgreeMediaType(
  1395. IPin *pReceivePin,
  1396. const CMediaType *pmt)
  1397. {
  1398. _ASSERTE(pReceivePin);
  1399. IEnumMediaTypes *pEnumMediaTypes = NULL;
  1400. // if the media type is fully specified then use that
  1401. if ( (pmt != NULL) && (!pmt->IsPartiallySpecified())) {
  1402. // if this media type fails, then we must fail the connection
  1403. // since if pmt is nonnull we are only allowed to connect
  1404. // using a type that matches it.
  1405. return AttemptConnection(pReceivePin, pmt);
  1406. }
  1407. /* Try the other pin's enumerator */
  1408. HRESULT hrFailure = VFW_E_NO_ACCEPTABLE_TYPES;
  1409. HRESULT hr = pReceivePin->EnumMediaTypes(&pEnumMediaTypes);
  1410. if (SUCCEEDED(hr)) {
  1411. _ASSERTE(pEnumMediaTypes);
  1412. hr = TryMediaTypes(pReceivePin,pmt,pEnumMediaTypes);
  1413. pEnumMediaTypes->Release();
  1414. if (SUCCEEDED(hr)) {
  1415. return NOERROR;
  1416. } else {
  1417. // try to remember specific error codes if there are any
  1418. if ((hr != E_FAIL) &&
  1419. (hr != E_INVALIDARG) &&
  1420. (hr != VFW_E_TYPE_NOT_ACCEPTED)) {
  1421. hrFailure = hr;
  1422. }
  1423. }
  1424. }
  1425. /* Having failed with that try our enumerator */
  1426. hr = EnumMediaTypes(&pEnumMediaTypes);
  1427. if (SUCCEEDED(hr)) {
  1428. _ASSERTE(pEnumMediaTypes);
  1429. hr = TryMediaTypes(pReceivePin,pmt,pEnumMediaTypes);
  1430. pEnumMediaTypes->Release();
  1431. if (SUCCEEDED(hr)) {
  1432. return NOERROR;
  1433. } else {
  1434. // try to remember specific error codes if there are any
  1435. if ((hr != E_FAIL) &&
  1436. (hr != E_INVALIDARG) &&
  1437. (hr != VFW_E_TYPE_NOT_ACCEPTED)) {
  1438. hrFailure = hr;
  1439. }
  1440. }
  1441. }
  1442. return hrFailure;
  1443. }
  1444. /* Called when we want to complete a connection to another filter. Failing
  1445. this will also fail the connection and disconnect the other pin as well */
  1446. HRESULT
  1447. CBasePin::CompleteConnect(IPin *pReceivePin)
  1448. {
  1449. UNREFERENCED_PARAMETER(pReceivePin);
  1450. return NOERROR;
  1451. }
  1452. /* This is called to set the format for a pin connection - CheckMediaType
  1453. will have been called to check the connection format and if it didn't
  1454. return an error code then this (virtual) function will be invoked */
  1455. HRESULT
  1456. CBasePin::SetMediaType(const CMediaType *pmt)
  1457. {
  1458. m_mt = *pmt;
  1459. return NOERROR;
  1460. }
  1461. /* This is called during Connect() to provide a virtual method that can do
  1462. any specific check needed for connection such as QueryInterface. This
  1463. base class method just checks that the pin directions don't match */
  1464. HRESULT
  1465. CBasePin::CheckConnect(IPin * pPin)
  1466. {
  1467. /* Check that pin directions DONT match */
  1468. PIN_DIRECTION pd;
  1469. pPin->QueryDirection(&pd);
  1470. _ASSERTE((pd == PINDIR_OUTPUT) || (pd == PINDIR_INPUT));
  1471. _ASSERTE((m_dir == PINDIR_OUTPUT) || (m_dir == PINDIR_INPUT));
  1472. // we should allow for non-input and non-output connections?
  1473. if (pd == m_dir) {
  1474. return VFW_E_INVALID_DIRECTION;
  1475. }
  1476. return NOERROR;
  1477. }
  1478. /* This is called when we realise we can't make a connection to the pin and
  1479. must undo anything we did in CheckConnect - override to release QIs done */
  1480. HRESULT
  1481. CBasePin::BreakConnect()
  1482. {
  1483. return NOERROR;
  1484. }
  1485. /* Called normally by an output pin on an input pin to try and establish a
  1486. connection.
  1487. */
  1488. STDMETHODIMP
  1489. CBasePin::ReceiveConnection(
  1490. IPin * pConnector, // this is the pin who we will connect to
  1491. const AM_MEDIA_TYPE *pmt // this is the media type we will exchange
  1492. )
  1493. {
  1494. CheckPointer(pConnector,E_POINTER);
  1495. CheckPointer(pmt,E_POINTER);
  1496. ValidateReadPtr(pConnector,sizeof(IPin));
  1497. ValidateReadPtr(pmt,sizeof(AM_MEDIA_TYPE));
  1498. CAutoLock cObjectLock(m_pLock);
  1499. /* Are we already connected */
  1500. if (m_Connected) {
  1501. return VFW_E_ALREADY_CONNECTED;
  1502. }
  1503. /* See if the filter is active */
  1504. if (!IsStopped()) {
  1505. return VFW_E_NOT_STOPPED;
  1506. }
  1507. HRESULT hr = CheckConnect(pConnector);
  1508. if (FAILED(hr)) {
  1509. BreakConnect();
  1510. return hr;
  1511. }
  1512. /* Ask derived class if this media type is ok */
  1513. CMediaType * pcmt = (CMediaType*) pmt;
  1514. hr = CheckMediaType(pcmt);
  1515. if (hr != NOERROR) {
  1516. // no -we don't support this media type
  1517. BreakConnect();
  1518. // return a specific media type error if there is one
  1519. // or map a general failure code to something more helpful
  1520. // (in particular S_FALSE gets changed to an error code)
  1521. if (SUCCEEDED(hr) ||
  1522. (hr == E_FAIL) ||
  1523. (hr == E_INVALIDARG)) {
  1524. hr = VFW_E_TYPE_NOT_ACCEPTED;
  1525. }
  1526. return hr;
  1527. }
  1528. /* Complete the connection */
  1529. m_Connected = pConnector;
  1530. m_Connected->AddRef();
  1531. SetMediaType(pcmt);
  1532. hr = CompleteConnect(pConnector);
  1533. if (FAILED(hr)) {
  1534. DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Failed to complete connection")));
  1535. m_Connected->Release();
  1536. m_Connected = NULL;
  1537. BreakConnect();
  1538. return hr;
  1539. }
  1540. return NOERROR;
  1541. }
  1542. /* Called when we want to terminate a pin connection */
  1543. STDMETHODIMP
  1544. CBasePin::Disconnect()
  1545. {
  1546. CAutoLock cObjectLock(m_pLock);
  1547. /* See if the filter is active */
  1548. if (!IsStopped()) {
  1549. return VFW_E_NOT_STOPPED;
  1550. }
  1551. if (m_Connected) {
  1552. BreakConnect();
  1553. m_Connected->Release();
  1554. m_Connected = NULL;
  1555. return S_OK;
  1556. } else {
  1557. // no connection - not an error
  1558. return S_FALSE;
  1559. }
  1560. }
  1561. /* Return an AddRef()'d pointer to the connected pin if there is one */
  1562. STDMETHODIMP
  1563. CBasePin::ConnectedTo(
  1564. IPin **ppPin
  1565. )
  1566. {
  1567. CheckPointer(ppPin,E_POINTER);
  1568. ValidateReadWritePtr(ppPin,sizeof(IPin *));
  1569. //
  1570. // It's pointless to lock here.
  1571. // The caller should ensure integrity.
  1572. //
  1573. IPin *pPin = m_Connected;
  1574. *ppPin = pPin;
  1575. if (pPin != NULL) {
  1576. pPin->AddRef();
  1577. return S_OK;
  1578. } else {
  1579. _ASSERTE(*ppPin == NULL);
  1580. return VFW_E_NOT_CONNECTED;
  1581. }
  1582. }
  1583. /* Return the media type of the connection */
  1584. STDMETHODIMP
  1585. CBasePin::ConnectionMediaType(
  1586. AM_MEDIA_TYPE *pmt
  1587. )
  1588. {
  1589. CheckPointer(pmt,E_POINTER);
  1590. ValidateReadWritePtr(pmt,sizeof(AM_MEDIA_TYPE));
  1591. CAutoLock cObjectLock(m_pLock);
  1592. /* Copy constructor of m_mt allocates the memory */
  1593. if (IsConnected()) {
  1594. CopyMediaType( pmt, &m_mt );
  1595. return S_OK;
  1596. } else {
  1597. ((CMediaType *)pmt)->InitMediaType();
  1598. return VFW_E_NOT_CONNECTED;
  1599. }
  1600. }
  1601. /* Return information about the filter we are connect to */
  1602. STDMETHODIMP
  1603. CBasePin::QueryPinInfo(
  1604. PIN_INFO * pInfo
  1605. )
  1606. {
  1607. CheckPointer(pInfo,E_POINTER);
  1608. ValidateReadWritePtr(pInfo,sizeof(PIN_INFO));
  1609. pInfo->pFilter = m_pFilter;
  1610. if (m_pFilter) {
  1611. m_pFilter->AddRef();
  1612. }
  1613. if (m_pName) {
  1614. lstrcpyW(pInfo->achName, m_pName);
  1615. } else {
  1616. pInfo->achName[0] = L'\0';
  1617. }
  1618. pInfo->dir = m_dir;
  1619. return NOERROR;
  1620. }
  1621. STDMETHODIMP
  1622. CBasePin::QueryDirection(
  1623. PIN_DIRECTION * pPinDir
  1624. )
  1625. {
  1626. CheckPointer(pPinDir,E_POINTER);
  1627. ValidateReadWritePtr(pPinDir,sizeof(PIN_DIRECTION));
  1628. *pPinDir = m_dir;
  1629. return NOERROR;
  1630. }
  1631. // Default QueryId to return the pin's name
  1632. STDMETHODIMP
  1633. CBasePin::QueryId(
  1634. LPWSTR * Id
  1635. )
  1636. {
  1637. // We're not going away because someone's got a pointer to us
  1638. // so there's no need to lock
  1639. return AMGetWideString(Name(), Id);
  1640. }
  1641. /* Does this pin support this media type WARNING this interface function does
  1642. not lock the main object as it is meant to be asynchronous by nature - if
  1643. the media types you support depend on some internal state that is updated
  1644. dynamically then you will need to implement locking in a derived class */
  1645. STDMETHODIMP
  1646. CBasePin::QueryAccept(
  1647. const AM_MEDIA_TYPE *pmt
  1648. )
  1649. {
  1650. CheckPointer(pmt,E_POINTER);
  1651. ValidateReadPtr(pmt,sizeof(AM_MEDIA_TYPE));
  1652. /* The CheckMediaType method is valid to return error codes if the media
  1653. type is horrible, an example might be E_INVALIDARG. What we do here
  1654. is map all the error codes into either S_OK or S_FALSE regardless */
  1655. HRESULT hr = CheckMediaType((CMediaType*)pmt);
  1656. if (FAILED(hr)) {
  1657. return S_FALSE;
  1658. }
  1659. // note that the only defined success codes should be S_OK and S_FALSE...
  1660. return hr;
  1661. }
  1662. /* This can be called to return an enumerator for the pin's list of preferred
  1663. media types. An input pin is not obliged to have any preferred formats
  1664. although it can do. For example, the window renderer has a preferred type
  1665. which describes a video image that matches the current window size. All
  1666. output pins should expose at least one preferred format otherwise it is
  1667. possible that neither pin has any types and so no connection is possible */
  1668. STDMETHODIMP
  1669. CBasePin::EnumMediaTypes(
  1670. IEnumMediaTypes **ppEnum
  1671. )
  1672. {
  1673. CheckPointer(ppEnum,E_POINTER);
  1674. ValidateReadWritePtr(ppEnum,sizeof(IEnumMediaTypes *));
  1675. /* Create a new ref counted enumerator */
  1676. *ppEnum = new CEnumMediaTypes(this,
  1677. NULL);
  1678. if (*ppEnum == NULL) {
  1679. return E_OUTOFMEMORY;
  1680. }
  1681. return NOERROR;
  1682. }
  1683. /* This is a virtual function that returns a media type corresponding with
  1684. place iPosition in the list. This base class simply returns an error as
  1685. we support no media types by default but derived classes should override */
  1686. HRESULT CBasePin::GetMediaType(int iPosition, CMediaType *pMediaType)
  1687. {
  1688. UNREFERENCED_PARAMETER(iPosition);
  1689. UNREFERENCED_PARAMETER(pMediaType);
  1690. return E_UNEXPECTED;
  1691. }
  1692. /* This is a virtual function that returns the current media type version.
  1693. The base class initialises the media type enumerators with the value 1
  1694. By default we always returns that same value. A Derived class may change
  1695. the list of media types available and after doing so it should increment
  1696. the version either in a method derived from this, or more simply by just
  1697. incrementing the m_TypeVersion base pin variable. The type enumerators
  1698. call this when they want to see if their enumerations are out of date */
  1699. LONG CBasePin::GetMediaTypeVersion()
  1700. {
  1701. return m_TypeVersion;
  1702. }
  1703. /* Increment the cookie representing the current media type version */
  1704. void CBasePin::IncrementTypeVersion()
  1705. {
  1706. InterlockedIncrement(&m_TypeVersion);
  1707. }
  1708. /* Called by IMediaFilter implementation when the state changes from Stopped
  1709. to either paused or running and in derived classes could do things like
  1710. commit memory and grab hardware resource (the default is to do nothing) */
  1711. HRESULT
  1712. CBasePin::Active(void)
  1713. {
  1714. return NOERROR;
  1715. }
  1716. /* Called by IMediaFilter implementation when the state changes from
  1717. to either paused to running and in derived classes could do things like
  1718. commit memory and grab hardware resource (the default is to do nothing) */
  1719. HRESULT
  1720. CBasePin::Run(REFERENCE_TIME tStart)
  1721. {
  1722. UNREFERENCED_PARAMETER(tStart);
  1723. return NOERROR;
  1724. }
  1725. /* Also called by the IMediaFilter implementation when the state changes to
  1726. Stopped at which point you should decommit allocators and free hardware
  1727. resources you grabbed in the Active call (default is also to do nothing) */
  1728. HRESULT
  1729. CBasePin::Inactive(void)
  1730. {
  1731. m_bRunTimeError = FALSE;
  1732. return NOERROR;
  1733. }
  1734. // Called when no more data will arrive
  1735. STDMETHODIMP
  1736. CBasePin::EndOfStream(void)
  1737. {
  1738. return S_FALSE;
  1739. }
  1740. STDMETHODIMP
  1741. CBasePin::SetSink(IQualityControl * piqc)
  1742. {
  1743. CAutoLock cObjectLock(m_pLock);
  1744. if (piqc) ValidateReadPtr(piqc,sizeof(IQualityControl));
  1745. m_pQSink = piqc;
  1746. return NOERROR;
  1747. } // SetSink
  1748. STDMETHODIMP
  1749. CBasePin::Notify(IBaseFilter * pSender, Quality q)
  1750. {
  1751. UNREFERENCED_PARAMETER(q);
  1752. CheckPointer(pSender,E_POINTER);
  1753. ValidateReadPtr(pSender,sizeof(IBaseFilter));
  1754. DbgBreak("IQualityControl::Notify not over-ridden from CBasePin. (IGNORE is OK)");
  1755. return E_FAIL;
  1756. } //Notify
  1757. // NewSegment notifies of the start/stop/rate applying to the data
  1758. // about to be received. Default implementation records data and
  1759. // returns S_OK.
  1760. // Override this to pass downstream.
  1761. STDMETHODIMP
  1762. CBasePin::NewSegment(
  1763. REFERENCE_TIME tStart,
  1764. REFERENCE_TIME tStop,
  1765. double dRate)
  1766. {
  1767. m_tStart = tStart;
  1768. m_tStop = tStop;
  1769. m_dRate = dRate;
  1770. return S_OK;
  1771. }
  1772. //=====================================================================
  1773. //=====================================================================
  1774. // Implements CBaseOutputPin
  1775. //=====================================================================
  1776. //=====================================================================
  1777. CBaseOutputPin::CBaseOutputPin(TCHAR *pObjectName,
  1778. CBaseFilter *pFilter,
  1779. CCritSec *pLock,
  1780. HRESULT *phr,
  1781. LPCWSTR pName) :
  1782. CBasePin(pObjectName, pFilter, pLock, phr, pName, PINDIR_OUTPUT),
  1783. m_pAllocator(NULL),
  1784. m_pInputPin(NULL)
  1785. {
  1786. _ASSERTE(pFilter);
  1787. }
  1788. /* Since an input pin connected to us holds a reference count on us we will
  1789. never be deleted unless all connections have already been terminated */
  1790. CBaseOutputPin::~CBaseOutputPin()
  1791. {
  1792. }
  1793. /* This is called after a media type has been proposed
  1794. Try to complete the connection by agreeing the allocator
  1795. */
  1796. HRESULT
  1797. CBaseOutputPin::CompleteConnect(IPin *pReceivePin)
  1798. {
  1799. UNREFERENCED_PARAMETER(pReceivePin);
  1800. return DecideAllocator(m_pInputPin, &m_pAllocator);
  1801. }
  1802. /* This method is called when the output pin is about to try and connect to
  1803. an input pin. It is at this point that you should try and grab any extra
  1804. interfaces that you need, in this case IMemInputPin. Because this is
  1805. only called if we are not currently connected we do NOT need to call
  1806. BreakConnect. This also makes it easier to derive classes from us as
  1807. BreakConnect is only called when we actually have to break a connection
  1808. (or a partly made connection) and not when we are checking a connection */
  1809. /* Overriden from CBasePin */
  1810. HRESULT
  1811. CBaseOutputPin::CheckConnect(IPin * pPin)
  1812. {
  1813. HRESULT hr = CBasePin::CheckConnect(pPin);
  1814. if (FAILED(hr)) {
  1815. return hr;
  1816. }
  1817. // get an input pin and an allocator interface
  1818. hr = pPin->QueryInterface(IID_IMemInputPin, (void **) &m_pInputPin);
  1819. if (FAILED(hr)) {
  1820. return hr;
  1821. }
  1822. return NOERROR;
  1823. }
  1824. /* Overriden from CBasePin */
  1825. HRESULT
  1826. CBaseOutputPin::BreakConnect()
  1827. {
  1828. /* Release any allocator we hold */
  1829. if (m_pAllocator) {
  1830. m_pAllocator->Release();
  1831. m_pAllocator = NULL;
  1832. }
  1833. /* Release any input pin interface we hold */
  1834. if (m_pInputPin) {
  1835. m_pInputPin->Release();
  1836. m_pInputPin = NULL;
  1837. }
  1838. return NOERROR;
  1839. }
  1840. /* This is called when the input pin didn't give us a valid allocator */
  1841. HRESULT
  1842. CBaseOutputPin::InitAllocator(IMemAllocator **ppAlloc)
  1843. {
  1844. HRESULT hr = NOERROR;
  1845. *ppAlloc = NULL;
  1846. CMemAllocator *pMemObject = NULL;
  1847. /* Create a default memory allocator */
  1848. pMemObject = new CMemAllocator(NAME("Base memory allocator"),NULL, &hr);
  1849. if (pMemObject == NULL) {
  1850. return E_OUTOFMEMORY;
  1851. }
  1852. if (FAILED(hr)) {
  1853. delete pMemObject;
  1854. return hr;
  1855. }
  1856. /* Get a reference counted IID_IMemAllocator interface */
  1857. EXECUTE_ASSERT(SUCCEEDED(pMemObject->QueryInterface(IID_IMemAllocator,(void **)ppAlloc)));
  1858. _ASSERTE(*ppAlloc != NULL);
  1859. return NOERROR;
  1860. }
  1861. /* Decide on an allocator, override this if you want to use your own allocator
  1862. Override DecideBufferSize to call SetProperties. If the input pin fails
  1863. the GetAllocator call then this will construct a CMemAllocator and call
  1864. DecideBufferSize on that, and if that fails then we are completely hosed.
  1865. If the you succeed the DecideBufferSize call, we will notify the input
  1866. pin of the selected allocator. NOTE this is called during Connect() which
  1867. therefore looks after grabbing and locking the object's critical section */
  1868. // We query the input pin for its requested properties and pass this to
  1869. // DecideBufferSize to allow it to fulfill requests that it is happy
  1870. // with (eg most people don't care about alignment and are thus happy to
  1871. // use the downstream pin's alignment request).
  1872. HRESULT
  1873. CBaseOutputPin::DecideAllocator(IMemInputPin *pPin, IMemAllocator **ppAlloc)
  1874. {
  1875. HRESULT hr = NOERROR;
  1876. *ppAlloc = NULL;
  1877. // get downstream prop request
  1878. // the derived class may modify this in DecideBufferSize, but
  1879. // we assume that he will consistently modify it the same way,
  1880. // so we only get it once
  1881. ALLOCATOR_PROPERTIES prop;
  1882. ZeroMemory(&prop, sizeof(prop));
  1883. // whatever he returns, we assume prop is either all zeros
  1884. // or he has filled it out.
  1885. pPin->GetAllocatorRequirements(&prop);
  1886. // if he doesn't care about alignment, then set it to 1
  1887. if (prop.cbAlign == 0) {
  1888. prop.cbAlign = 1;
  1889. }
  1890. /* Try the allocator provided by the input pin */
  1891. hr = pPin->GetAllocator(ppAlloc);
  1892. if (SUCCEEDED(hr)) {
  1893. hr = DecideBufferSize(*ppAlloc, &prop);
  1894. if (SUCCEEDED(hr)) {
  1895. hr = pPin->NotifyAllocator(*ppAlloc, FALSE);
  1896. if (SUCCEEDED(hr)) {
  1897. return NOERROR;
  1898. }
  1899. }
  1900. }
  1901. /* If the GetAllocator failed we may not have an interface */
  1902. if (*ppAlloc) {
  1903. (*ppAlloc)->Release();
  1904. *ppAlloc = NULL;
  1905. }
  1906. /* Try the output pin's allocator by the same method */
  1907. hr = InitAllocator(ppAlloc);
  1908. if (SUCCEEDED(hr)) {
  1909. // note - the properties passed here are in the same
  1910. // structure as above and may have been modified by
  1911. // the previous call to DecideBufferSize
  1912. hr = DecideBufferSize(*ppAlloc, &prop);
  1913. if (SUCCEEDED(hr)) {
  1914. hr = pPin->NotifyAllocator(*ppAlloc, FALSE);
  1915. if (SUCCEEDED(hr)) {
  1916. return NOERROR;
  1917. }
  1918. }
  1919. }
  1920. /* Likewise we may not have an interface to release */
  1921. if (*ppAlloc) {
  1922. (*ppAlloc)->Release();
  1923. *ppAlloc = NULL;
  1924. }
  1925. return hr;
  1926. }
  1927. /* This returns an empty sample buffer from the allocator WARNING the same
  1928. dangers and restrictions apply here as described below for Deliver() */
  1929. HRESULT
  1930. CBaseOutputPin::GetDeliveryBuffer(IMediaSample ** ppSample,
  1931. REFERENCE_TIME * pStartTime,
  1932. REFERENCE_TIME * pEndTime,
  1933. DWORD dwFlags)
  1934. {
  1935. if (m_pAllocator != NULL) {
  1936. return m_pAllocator->GetBuffer(ppSample,pStartTime,pEndTime,dwFlags);
  1937. } else {
  1938. return E_NOINTERFACE;
  1939. }
  1940. }
  1941. /* Deliver a filled-in sample to the connected input pin. NOTE the object must
  1942. have locked itself before calling us otherwise we may get halfway through
  1943. executing this method only to find the filter graph has got in and
  1944. disconnected us from the input pin. If the filter has no worker threads
  1945. then the lock is best applied on Receive(), otherwise it should be done
  1946. when the worker thread is ready to deliver. There is a wee snag to worker
  1947. threads that this shows up. The worker thread must lock the object when
  1948. it is ready to deliver a sample, but it may have to wait until a state
  1949. change has completed, but that may never complete because the state change
  1950. is waiting for the worker thread to complete. The way to handle this is for
  1951. the state change code to grab the critical section, then set an abort event
  1952. for the worker thread, then release the critical section and wait for the
  1953. worker thread to see the event we set and then signal that it has finished
  1954. (with another event). At which point the state change code can complete */
  1955. // note (if you've still got any breath left after reading that) that you
  1956. // need to release the sample yourself after this call. if the connected
  1957. // input pin needs to hold onto the sample beyond the call, it will addref
  1958. // the sample itself.
  1959. // of course you must release this one and call GetDeliveryBuffer for the
  1960. // next. You cannot reuse it directly.
  1961. HRESULT
  1962. CBaseOutputPin::Deliver(IMediaSample * pSample)
  1963. {
  1964. if (m_pInputPin == NULL) {
  1965. return VFW_E_NOT_CONNECTED;
  1966. }
  1967. return m_pInputPin->Receive(pSample);
  1968. }
  1969. // called from elsewhere in our filter to pass EOS downstream to
  1970. // our connected input pin
  1971. HRESULT
  1972. CBaseOutputPin::DeliverEndOfStream(void)
  1973. {
  1974. // remember this is on IPin not IMemInputPin
  1975. if (m_Connected == NULL) {
  1976. return VFW_E_NOT_CONNECTED;
  1977. }
  1978. return m_Connected->EndOfStream();
  1979. }
  1980. /* Commit the allocator's memory, this is called through IMediaFilter
  1981. which is responsible for locking the object before calling us */
  1982. HRESULT
  1983. CBaseOutputPin::Active(void)
  1984. {
  1985. if (m_pAllocator == NULL) {
  1986. return VFW_E_NO_ALLOCATOR;
  1987. }
  1988. return m_pAllocator->Commit();
  1989. }
  1990. /* Free up or unprepare allocator's memory, this is called through
  1991. IMediaFilter which is responsible for locking the object first */
  1992. HRESULT
  1993. CBaseOutputPin::Inactive(void)
  1994. {
  1995. m_bRunTimeError = FALSE;
  1996. if (m_pAllocator == NULL) {
  1997. return VFW_E_NO_ALLOCATOR;
  1998. }
  1999. return m_pAllocator->Decommit();
  2000. }
  2001. // we have a default handling of EndOfStream which is to return
  2002. // an error, since this should be called on input pins only
  2003. STDMETHODIMP
  2004. CBaseOutputPin::EndOfStream(void)
  2005. {
  2006. return E_UNEXPECTED;
  2007. }
  2008. // BeginFlush should be called on input pins only
  2009. STDMETHODIMP
  2010. CBaseOutputPin::BeginFlush(void)
  2011. {
  2012. return E_UNEXPECTED;
  2013. }
  2014. // EndFlush should be called on input pins only
  2015. STDMETHODIMP
  2016. CBaseOutputPin::EndFlush(void)
  2017. {
  2018. return E_UNEXPECTED;
  2019. }
  2020. // call BeginFlush on the connected input pin
  2021. HRESULT
  2022. CBaseOutputPin::DeliverBeginFlush(void)
  2023. {
  2024. // remember this is on IPin not IMemInputPin
  2025. if (m_Connected == NULL) {
  2026. return VFW_E_NOT_CONNECTED;
  2027. }
  2028. return m_Connected->BeginFlush();
  2029. }
  2030. // call EndFlush on the connected input pin
  2031. HRESULT
  2032. CBaseOutputPin::DeliverEndFlush(void)
  2033. {
  2034. // remember this is on IPin not IMemInputPin
  2035. if (m_Connected == NULL) {
  2036. return VFW_E_NOT_CONNECTED;
  2037. }
  2038. return m_Connected->EndFlush();
  2039. }
  2040. // deliver NewSegment to connected pin
  2041. HRESULT
  2042. CBaseOutputPin::DeliverNewSegment(
  2043. REFERENCE_TIME tStart,
  2044. REFERENCE_TIME tStop,
  2045. double dRate)
  2046. {
  2047. if (m_Connected == NULL) {
  2048. return VFW_E_NOT_CONNECTED;
  2049. }
  2050. return m_Connected->NewSegment(tStart, tStop, dRate);
  2051. }
  2052. //=====================================================================
  2053. //=====================================================================
  2054. // Implements CBaseInputPin
  2055. //=====================================================================
  2056. //=====================================================================
  2057. /* Constructor creates a default allocator object */
  2058. CBaseInputPin::CBaseInputPin(TCHAR *pObjectName,
  2059. CBaseFilter *pFilter,
  2060. CCritSec *pLock,
  2061. HRESULT *phr,
  2062. LPCWSTR pPinName) :
  2063. CBasePin(pObjectName, pFilter, pLock, phr, pPinName, PINDIR_INPUT),
  2064. m_pAllocator(NULL),
  2065. m_bReadOnly(FALSE),
  2066. m_bFlushing(FALSE)
  2067. {
  2068. ZeroMemory(&m_SampleProps, sizeof(m_SampleProps));
  2069. }
  2070. /* Destructor releases it's reference count on the default allocator */
  2071. CBaseInputPin::~CBaseInputPin()
  2072. {
  2073. if (m_pAllocator != NULL) {
  2074. m_pAllocator->Release();
  2075. m_pAllocator = NULL;
  2076. }
  2077. if (m_SampleProps.pMediaType) {
  2078. DeleteMediaType(m_SampleProps.pMediaType);
  2079. }
  2080. }
  2081. // override this to publicise our interfaces
  2082. STDMETHODIMP
  2083. CBaseInputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv)
  2084. {
  2085. /* Do we know about this interface */
  2086. if (riid == IID_IMemInputPin) {
  2087. return GetInterface((IMemInputPin *) this, ppv);
  2088. } else {
  2089. return CBasePin::NonDelegatingQueryInterface(riid, ppv);
  2090. }
  2091. }
  2092. /* Return the allocator interface that this input pin would like the output
  2093. pin to use. NOTE subsequent calls to GetAllocator should all return an
  2094. interface onto the SAME object so we create one object at the start
  2095. Note:
  2096. The allocator is Release()'d on disconnect and replaced on
  2097. NotifyAllocator().
  2098. Override this to provide your own allocator.
  2099. */
  2100. STDMETHODIMP
  2101. CBaseInputPin::GetAllocator(
  2102. IMemAllocator **ppAllocator)
  2103. {
  2104. CheckPointer(ppAllocator,E_POINTER);
  2105. ValidateReadWritePtr(ppAllocator,sizeof(IMemAllocator *));
  2106. CAutoLock cObjectLock(m_pLock);
  2107. if (m_pAllocator == NULL) {
  2108. HRESULT hr = S_OK;
  2109. /* Create the new allocator object */
  2110. CMemAllocator *pMemObject = new CMemAllocator(NAME("Default memory allocator"),
  2111. NULL, &hr);
  2112. if (pMemObject == NULL) {
  2113. return E_OUTOFMEMORY;
  2114. }
  2115. if (FAILED(hr)) {
  2116. _ASSERTE(pMemObject);
  2117. delete pMemObject;
  2118. return hr;
  2119. }
  2120. m_pAllocator = pMemObject;
  2121. /* We AddRef() our own allocator */
  2122. m_pAllocator->AddRef();
  2123. }
  2124. _ASSERTE(m_pAllocator != NULL);
  2125. *ppAllocator = m_pAllocator;
  2126. m_pAllocator->AddRef();
  2127. return NOERROR;
  2128. }
  2129. /* Tell the input pin which allocator the output pin is actually going to use
  2130. Override this if you care - NOTE the locking we do both here and also in
  2131. GetAllocator is unnecessary but derived classes that do something useful
  2132. will undoubtedly have to lock the object so this might help remind people */
  2133. STDMETHODIMP
  2134. CBaseInputPin::NotifyAllocator(
  2135. IMemAllocator * pAllocator,
  2136. BOOL bReadOnly)
  2137. {
  2138. CheckPointer(pAllocator,E_POINTER);
  2139. ValidateReadPtr(pAllocator,sizeof(IMemAllocator));
  2140. CAutoLock cObjectLock(m_pLock);
  2141. IMemAllocator *pOldAllocator = m_pAllocator;
  2142. pAllocator->AddRef();
  2143. m_pAllocator = pAllocator;
  2144. if (pOldAllocator != NULL) {
  2145. pOldAllocator->Release();
  2146. }
  2147. // the readonly flag indicates whether samples from this allocator should
  2148. // be regarded as readonly - if true, then inplace transforms will not be
  2149. // allowed.
  2150. m_bReadOnly = bReadOnly;
  2151. return NOERROR;
  2152. }
  2153. /* Disconnect */
  2154. STDMETHODIMP CBaseInputPin::Disconnect()
  2155. {
  2156. CAutoLock cObjectLock(m_pLock);
  2157. /* Call base class first because it calls Inactive() for us */
  2158. HRESULT hr = CBasePin::Disconnect();
  2159. if (S_OK == hr) {
  2160. /* We don't need our allocator any more */
  2161. if (m_pAllocator) {
  2162. m_pAllocator->Release();
  2163. m_pAllocator = NULL;
  2164. }
  2165. }
  2166. return hr;
  2167. }
  2168. /* Do something with this media sample - this base class checks to see if the
  2169. format has changed with this media sample and if so checks that the filter
  2170. will accept it, generating a run time error if not. Once we have raised a
  2171. run time error we set a flag so that no more samples will be accepted
  2172. It is important that any filter should override this method and implement
  2173. synchronization so that samples are not processed when the pin is
  2174. disconnected etc
  2175. */
  2176. STDMETHODIMP
  2177. CBaseInputPin::Receive(IMediaSample *pSample)
  2178. {
  2179. CheckPointer(pSample,E_POINTER);
  2180. ValidateReadPtr(pSample,sizeof(IMediaSample));
  2181. AM_MEDIA_TYPE *pmt = NULL;
  2182. _ASSERTE(pSample);
  2183. HRESULT hr = CheckStreaming();
  2184. if (S_OK != hr) {
  2185. return hr;
  2186. }
  2187. /* Check for IMediaSample2 */
  2188. if (m_SampleProps.pMediaType) {
  2189. DeleteMediaType(m_SampleProps.pMediaType);
  2190. }
  2191. IMediaSample2 *pSample2;
  2192. if (SUCCEEDED(pSample->QueryInterface(IID_IMediaSample2, (void **)&pSample2))) {
  2193. hr = pSample2->GetProperties(sizeof(m_SampleProps), (PBYTE)&m_SampleProps);
  2194. pSample2->Release();
  2195. if (FAILED(hr)) {
  2196. return hr;
  2197. }
  2198. } else {
  2199. /* Get the properties the hard way */
  2200. m_SampleProps.cbData = sizeof(m_SampleProps);
  2201. m_SampleProps.dwTypeSpecificFlags = 0;
  2202. m_SampleProps.dwSampleFlags = 0;
  2203. if (S_OK == pSample->IsDiscontinuity()) {
  2204. m_SampleProps.dwSampleFlags |= AM_SAMPLE_DATADISCONTINUITY;
  2205. }
  2206. if (S_OK == pSample->IsPreroll()) {
  2207. m_SampleProps.dwSampleFlags |= AM_SAMPLE_PREROLL;
  2208. }
  2209. if (S_OK == pSample->IsSyncPoint()) {
  2210. m_SampleProps.dwSampleFlags |= AM_SAMPLE_SPLICEPOINT;
  2211. }
  2212. if (S_OK == pSample->GetTime(&m_SampleProps.tStart,
  2213. &m_SampleProps.tStop)) {
  2214. m_SampleProps.dwSampleFlags |= AM_SAMPLE_TIMEVALID |
  2215. AM_SAMPLE_STOPVALID;
  2216. }
  2217. if (S_OK == pSample->GetMediaType(&m_SampleProps.pMediaType)) {
  2218. m_SampleProps.dwSampleFlags |= AM_SAMPLE_TYPECHANGED;
  2219. }
  2220. pSample->GetPointer(&m_SampleProps.pbBuffer);
  2221. m_SampleProps.lActual = pSample->GetActualDataLength();
  2222. m_SampleProps.cbBuffer = pSample->GetSize();
  2223. }
  2224. /* Has the format changed in this sample */
  2225. if (!(m_SampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)) {
  2226. return NOERROR;
  2227. }
  2228. /* Check the derived class accepts this format */
  2229. /* This shouldn't fail as the source must call QueryAccept first */
  2230. hr = CheckMediaType((CMediaType *)m_SampleProps.pMediaType);
  2231. if (hr == NOERROR) {
  2232. return NOERROR;
  2233. }
  2234. /* Raise a runtime error if we fail the media type */
  2235. m_bRunTimeError = TRUE;
  2236. EndOfStream();
  2237. m_pFilter->NotifyEvent(EC_ERRORABORT,VFW_E_TYPE_NOT_ACCEPTED,0);
  2238. return VFW_E_INVALIDMEDIATYPE;
  2239. }
  2240. /* Receive multiple samples */
  2241. STDMETHODIMP
  2242. CBaseInputPin::ReceiveMultiple (
  2243. IMediaSample **pSamples,
  2244. long nSamples,
  2245. long *nSamplesProcessed)
  2246. {
  2247. CheckPointer(pSamples,E_POINTER);
  2248. ValidateReadPtr(pSamples,nSamples * sizeof(IMediaSample *));
  2249. HRESULT hr = S_OK;
  2250. *nSamplesProcessed = 0;
  2251. while (nSamples-- > 0) {
  2252. hr = Receive(pSamples[*nSamplesProcessed]);
  2253. /* S_FALSE means don't send any more */
  2254. if (hr != S_OK) {
  2255. break;
  2256. }
  2257. (*nSamplesProcessed)++;
  2258. }
  2259. return hr;
  2260. }
  2261. /* See if Receive() might block */
  2262. STDMETHODIMP
  2263. CBaseInputPin::ReceiveCanBlock()
  2264. {
  2265. /* Ask all the output pins if they block
  2266. If there are no output pin assume we do block
  2267. */
  2268. int cPins = m_pFilter->GetPinCount();
  2269. int cOutputPins = 0;
  2270. for (int c = 0; c < cPins; c++) {
  2271. CBasePin *pPin = m_pFilter->GetPin(c);
  2272. PIN_DIRECTION pd;
  2273. HRESULT hr = pPin->QueryDirection(&pd);
  2274. if (FAILED(hr)) {
  2275. return hr;
  2276. }
  2277. if (pd == PINDIR_OUTPUT) {
  2278. IPin *pConnected;
  2279. hr = pPin->ConnectedTo(&pConnected);
  2280. if (SUCCEEDED(hr)) {
  2281. _ASSERTE(pConnected != NULL);
  2282. cOutputPins++;
  2283. IMemInputPin *pInputPin;
  2284. hr = pConnected->QueryInterface(
  2285. IID_IMemInputPin,
  2286. (void **)&pInputPin);
  2287. pConnected->Release();
  2288. if (SUCCEEDED(hr)) {
  2289. hr = pInputPin->ReceiveCanBlock();
  2290. pInputPin->Release();
  2291. if (hr != S_FALSE) {
  2292. return S_OK;
  2293. }
  2294. } else {
  2295. /* There's a transport we don't understand here */
  2296. return S_OK;
  2297. }
  2298. }
  2299. }
  2300. }
  2301. return cOutputPins == 0 ? S_OK : S_FALSE;
  2302. }
  2303. // Default handling for BeginFlush - call at the beginning
  2304. // of your implementation (makes sure that all Receive calls
  2305. // fail). After calling this, you need to free any queued data
  2306. // and then call downstream.
  2307. STDMETHODIMP
  2308. CBaseInputPin::BeginFlush(void)
  2309. {
  2310. // BeginFlush is NOT synchronized with streaming but is part of
  2311. // a control action - hence we synchronize with the filter
  2312. CAutoLock lck(m_pLock);
  2313. // if we are already in mid-flush, this is probably a mistake
  2314. // though not harmful - try to pick it up for now so I can think about it
  2315. _ASSERTE(!m_bFlushing);
  2316. // first thing to do is ensure that no further Receive calls succeed
  2317. m_bFlushing = TRUE;
  2318. // now discard any data and call downstream - must do that
  2319. // in derived classes
  2320. return S_OK;
  2321. }
  2322. // default handling for EndFlush - call at end of your implementation
  2323. // - before calling this, ensure that there is no queued data and no thread
  2324. // pushing any more without a further receive, then call downstream,
  2325. // then call this method to clear the m_bFlushing flag and re-enable
  2326. // receives
  2327. STDMETHODIMP
  2328. CBaseInputPin::EndFlush(void)
  2329. {
  2330. // Endlush is NOT synchronized with streaming but is part of
  2331. // a control action - hence we synchronize with the filter
  2332. CAutoLock lck(m_pLock);
  2333. // almost certainly a mistake if we are not in mid-flush
  2334. _ASSERTE(m_bFlushing);
  2335. // before calling, sync with pushing thread and ensure
  2336. // no more data is going downstream, then call EndFlush on
  2337. // downstream pins.
  2338. // now re-enable Receives
  2339. m_bFlushing = FALSE;
  2340. return S_OK;
  2341. }
  2342. STDMETHODIMP
  2343. CBaseInputPin::Notify(IBaseFilter * pSender, Quality q)
  2344. {
  2345. UNREFERENCED_PARAMETER(q);
  2346. CheckPointer(pSender,E_POINTER);
  2347. ValidateReadPtr(pSender,sizeof(IBaseFilter));
  2348. DbgBreak("IQuality::Notify called on an input pin");
  2349. return NOERROR;
  2350. } // Notify
  2351. /* Free up or unprepare allocator's memory, this is called through
  2352. IMediaFilter which is responsible for locking the object first */
  2353. HRESULT
  2354. CBaseInputPin::Inactive(void)
  2355. {
  2356. m_bRunTimeError = FALSE;
  2357. if (m_pAllocator == NULL) {
  2358. return VFW_E_NO_ALLOCATOR;
  2359. }
  2360. m_bFlushing = FALSE;
  2361. return m_pAllocator->Decommit();
  2362. }
  2363. // what requirements do we have of the allocator - override if you want
  2364. // to support other people's allocators but need a specific alignment
  2365. // or prefix.
  2366. STDMETHODIMP
  2367. CBaseInputPin::GetAllocatorRequirements(ALLOCATOR_PROPERTIES*pProps)
  2368. {
  2369. UNREFERENCED_PARAMETER(pProps);
  2370. return E_NOTIMPL;
  2371. }
  2372. // Check if it's OK to process data
  2373. //
  2374. HRESULT
  2375. CBaseInputPin::CheckStreaming()
  2376. {
  2377. // Shouldn't be able to get any data if we're not connected!
  2378. _ASSERTE(IsConnected());
  2379. // Don't process stuff in Stopped state
  2380. if (IsStopped()) {
  2381. return VFW_E_WRONG_STATE;
  2382. }
  2383. if (m_bFlushing) {
  2384. return S_FALSE;
  2385. }
  2386. if (m_bRunTimeError) {
  2387. return VFW_E_RUNTIME_ERROR;
  2388. }
  2389. return S_OK;
  2390. }
  2391. #endif
  2392. //=====================================================================
  2393. //=====================================================================
  2394. // Memory allocation class, implements CMediaSampleImpl
  2395. //=====================================================================
  2396. //=====================================================================
  2397. /* NOTE The implementation of this class calls the CUnknown constructor with
  2398. a NULL outer unknown pointer. This has the effect of making us a self
  2399. contained class, ie any QueryInterface, AddRef or Release calls will be
  2400. routed to the class's NonDelegatingUnknown methods. You will typically
  2401. find that the classes that do this then override one or more of these
  2402. virtual functions to provide more specialised behaviour. A good example
  2403. of this is where a class wants to keep the QueryInterface internal but
  2404. still wants it's lifetime controlled by the external object */
  2405. /* The last two parameters have default values of NULL and zero */
  2406. template <class _S, class _A>
  2407. CAMMediaSampleImpl<_S, _A>::CAMMediaSampleImpl() :
  2408. m_pBuffer(NULL), // Initialise the buffer
  2409. m_cbBuffer(0), // And it's length
  2410. m_lActual(0), // By default, actual = length
  2411. m_pMediaType(NULL), // No media type change
  2412. m_dwFlags(0), // Nothing set
  2413. m_cRef(0), // 0 ref count
  2414. m_pAllocator(NULL) // Allocator
  2415. {
  2416. }
  2417. #if 0
  2418. /* Destructor deletes the media type memory */
  2419. template <class _S, class _A>
  2420. CAMMediaSampleImpl<_S, _A>::~CAMMediaSampleImpl()
  2421. {
  2422. if (m_pMediaType) {
  2423. DeleteMediaType(m_pMediaType);
  2424. }
  2425. }
  2426. #endif
  2427. /* Override this to publicise our interfaces */
  2428. template <class _S, class _A>
  2429. STDMETHODIMP
  2430. CAMMediaSampleImpl<_S, _A>::QueryInterface(REFIID riid, void **ppv)
  2431. {
  2432. if (ppv == NULL) {
  2433. return E_POINTER;
  2434. }
  2435. if (riid == IID_IMediaSample ||
  2436. riid == IID_IMediaSample2 ||
  2437. riid == IID_IUnknown) {
  2438. *ppv = (IMediaSample *)this;
  2439. AddRef();
  2440. return S_OK;
  2441. } else {
  2442. return E_NOINTERFACE;
  2443. }
  2444. }
  2445. template <class _S, class _A>
  2446. STDMETHODIMP_(ULONG)
  2447. CAMMediaSampleImpl<_S, _A>::AddRef()
  2448. {
  2449. return InterlockedIncrement(&m_cRef);
  2450. }
  2451. // -- CMediaSample lifetimes --
  2452. //
  2453. // On final release of this sample buffer it is not deleted but
  2454. // returned to the freelist of the owning memory allocator
  2455. //
  2456. // The allocator may be waiting for the last buffer to be placed on the free
  2457. // list in order to decommit all the memory, so the ReleaseBuffer() call may
  2458. // result in this sample being deleted. We also need to hold a refcount on
  2459. // the allocator to stop that going away until we have finished with this.
  2460. // However, we cannot release the allocator before the ReleaseBuffer, as the
  2461. // release may cause us to be deleted. Similarly we can't do it afterwards.
  2462. //
  2463. // Thus we must leave it to the allocator to hold an addref on our behalf.
  2464. // When he issues us in GetBuffer, he addref's himself. When ReleaseBuffer
  2465. // is called, he releases himself, possibly causing us and him to be deleted.
  2466. template <class _S, class _A>
  2467. STDMETHODIMP_(ULONG)
  2468. CAMMediaSampleImpl<_S, _A>::Release()
  2469. {
  2470. /* Decrement our own private reference count */
  2471. LONG lRef;
  2472. if (m_cRef == 1) {
  2473. lRef = 0;
  2474. m_cRef = 0;
  2475. } else {
  2476. lRef = InterlockedDecrement(&m_cRef);
  2477. }
  2478. _ASSERTE(lRef >= 0);
  2479. //DbgLog((LOG_MEMORY,3,TEXT(" Unknown %X ref-- = %d"),
  2480. // this, m_cRef));
  2481. /* Did we release our final reference count */
  2482. if (lRef == 0) {
  2483. /* Free all resources */
  2484. if (m_dwFlags & Sample_TypeChanged) {
  2485. SetMediaType(NULL);
  2486. }
  2487. _ASSERTE(m_pMediaType == NULL);
  2488. m_dwFlags = 0;
  2489. /* This may cause us to be deleted */
  2490. // Our refcount is reliably 0 thus no-one will mess with us
  2491. m_pAllocator->ReleaseBuffer(this);
  2492. }
  2493. return (ULONG)lRef;
  2494. }
  2495. #if 0
  2496. // set the buffer pointer and length. Used by allocators that
  2497. // want variable sized pointers or pointers into already-read data.
  2498. // This is only available through a CMediaSample* not an IMediaSample*
  2499. // and so cannot be changed by clients.
  2500. template <class _S, class _A>
  2501. HRESULT
  2502. CAMMediaSampleImpl<_S, _A>::SetPointer(BYTE * ptr, LONG cBytes)
  2503. {
  2504. m_pBuffer = ptr; // new buffer area (could be null)
  2505. m_cbBuffer = cBytes; // length of buffer
  2506. m_lActual = cBytes; // length of data in buffer (assume full)
  2507. return S_OK;
  2508. }
  2509. #endif
  2510. // get me a read/write pointer to this buffer's memory. I will actually
  2511. // want to use sizeUsed bytes.
  2512. template <class _S, class _A>
  2513. STDMETHODIMP
  2514. CAMMediaSampleImpl<_S, _A>::GetPointer(BYTE ** ppBuffer)
  2515. {
  2516. //ValidateReadWritePtr(ppBuffer,sizeof(BYTE *));
  2517. // creator must have set pointer either during
  2518. // constructor or by SetPointer
  2519. _ASSERTE(m_pBuffer);
  2520. *ppBuffer = m_pBuffer;
  2521. return NOERROR;
  2522. }
  2523. // return the size in bytes of this buffer
  2524. template <class _S, class _A>
  2525. STDMETHODIMP_(LONG)
  2526. CAMMediaSampleImpl<_S, _A>::GetSize(void)
  2527. {
  2528. return m_cbBuffer;
  2529. }
  2530. // get the stream time at which this sample should start and finish.
  2531. template <class _S, class _A>
  2532. STDMETHODIMP
  2533. CAMMediaSampleImpl<_S, _A>::GetTime(
  2534. REFERENCE_TIME * pTimeStart, // put time here
  2535. REFERENCE_TIME * pTimeEnd
  2536. )
  2537. {
  2538. //ValidateReadWritePtr(pTimeStart,sizeof(REFERENCE_TIME));
  2539. //ValidateReadWritePtr(pTimeEnd,sizeof(REFERENCE_TIME));
  2540. if (!(m_dwFlags & Sample_TimeValid)) {
  2541. return VFW_E_SAMPLE_TIME_NOT_SET;
  2542. }
  2543. *pTimeStart = m_Start;
  2544. *pTimeEnd = m_End;
  2545. return NOERROR;
  2546. }
  2547. // Set the stream time at which this sample should start and finish.
  2548. // NULL pointers means the time is reset
  2549. template <class _S, class _A>
  2550. STDMETHODIMP
  2551. CAMMediaSampleImpl<_S, _A>::SetTime(
  2552. REFERENCE_TIME * pTimeStart,
  2553. REFERENCE_TIME * pTimeEnd
  2554. )
  2555. {
  2556. if (pTimeStart == NULL) {
  2557. _ASSERTE(pTimeEnd == NULL);
  2558. m_dwFlags &= ~(Sample_TimeValid | Sample_StopValid);
  2559. } else {
  2560. //ValidateReadPtr(pTimeStart,sizeof(REFERENCE_TIME));
  2561. //ValidateReadPtr(pTimeEnd,sizeof(REFERENCE_TIME));
  2562. _ASSERTE(*pTimeEnd >= *pTimeStart);
  2563. m_Start = *pTimeStart;
  2564. m_End = *pTimeEnd;
  2565. m_dwFlags |= Sample_TimeValid | Sample_StopValid;
  2566. }
  2567. return NOERROR;
  2568. }
  2569. // get the media times (eg bytes) for this sample
  2570. template <class _S, class _A>
  2571. STDMETHODIMP
  2572. CAMMediaSampleImpl<_S, _A>::GetMediaTime(
  2573. LONGLONG * pTimeStart,
  2574. LONGLONG * pTimeEnd
  2575. )
  2576. {
  2577. //ValidateReadWritePtr(pTimeStart,sizeof(LONGLONG));
  2578. //ValidateReadWritePtr(pTimeEnd,sizeof(LONGLONG));
  2579. if (!(m_dwFlags & Sample_MediaTimeValid)) {
  2580. return VFW_E_MEDIA_TIME_NOT_SET;
  2581. }
  2582. *pTimeStart = m_MediaStart;
  2583. *pTimeEnd = (m_MediaStart + m_MediaEnd);
  2584. return NOERROR;
  2585. }
  2586. // Set the media times for this sample
  2587. template <class _S, class _A>
  2588. STDMETHODIMP
  2589. CAMMediaSampleImpl<_S, _A>::SetMediaTime(
  2590. LONGLONG * pTimeStart,
  2591. LONGLONG * pTimeEnd
  2592. )
  2593. {
  2594. if (pTimeStart == NULL) {
  2595. _ASSERTE(pTimeEnd == NULL);
  2596. m_dwFlags &= ~Sample_MediaTimeValid;
  2597. } else {
  2598. //ValidateReadPtr(pTimeStart,sizeof(LONGLONG));
  2599. //ValidateReadPtr(pTimeEnd,sizeof(LONGLONG));
  2600. _ASSERTE(*pTimeEnd >= *pTimeStart);
  2601. m_MediaStart = *pTimeStart;
  2602. m_MediaEnd = (LONG)(*pTimeEnd - *pTimeStart);
  2603. m_dwFlags |= Sample_MediaTimeValid;
  2604. }
  2605. return NOERROR;
  2606. }
  2607. template <class _S, class _A>
  2608. STDMETHODIMP
  2609. CAMMediaSampleImpl<_S, _A>::IsSyncPoint(void)
  2610. {
  2611. if (m_dwFlags & Sample_SyncPoint) {
  2612. return S_OK;
  2613. } else {
  2614. return S_FALSE;
  2615. }
  2616. }
  2617. template <class _S, class _A>
  2618. STDMETHODIMP
  2619. CAMMediaSampleImpl<_S, _A>::SetSyncPoint(BOOL bIsSyncPoint)
  2620. {
  2621. if (bIsSyncPoint) {
  2622. m_dwFlags |= Sample_SyncPoint;
  2623. } else {
  2624. m_dwFlags &= ~Sample_SyncPoint;
  2625. }
  2626. return NOERROR;
  2627. }
  2628. // returns S_OK if there is a discontinuity in the data (this same is
  2629. // not a continuation of the previous stream of data
  2630. // - there has been a seek).
  2631. template <class _S, class _A>
  2632. STDMETHODIMP
  2633. CAMMediaSampleImpl<_S, _A>::IsDiscontinuity(void)
  2634. {
  2635. if (m_dwFlags & Sample_Discontinuity) {
  2636. return S_OK;
  2637. } else {
  2638. return S_FALSE;
  2639. }
  2640. }
  2641. // set the discontinuity property - TRUE if this sample is not a
  2642. // continuation, but a new sample after a seek.
  2643. template <class _S, class _A>
  2644. STDMETHODIMP
  2645. CAMMediaSampleImpl<_S, _A>::SetDiscontinuity(BOOL bDiscont)
  2646. {
  2647. // should be TRUE or FALSE
  2648. if (bDiscont) {
  2649. m_dwFlags |= Sample_Discontinuity;
  2650. } else {
  2651. m_dwFlags &= ~Sample_Discontinuity;
  2652. }
  2653. return S_OK;
  2654. }
  2655. template <class _S, class _A>
  2656. STDMETHODIMP
  2657. CAMMediaSampleImpl<_S, _A>::IsPreroll(void)
  2658. {
  2659. if (m_dwFlags & Sample_Preroll) {
  2660. return S_OK;
  2661. } else {
  2662. return S_FALSE;
  2663. }
  2664. }
  2665. template <class _S, class _A>
  2666. STDMETHODIMP
  2667. CAMMediaSampleImpl<_S, _A>::SetPreroll(BOOL bIsPreroll)
  2668. {
  2669. if (bIsPreroll) {
  2670. m_dwFlags |= Sample_Preroll;
  2671. } else {
  2672. m_dwFlags &= ~Sample_Preroll;
  2673. }
  2674. return NOERROR;
  2675. }
  2676. template <class _S, class _A>
  2677. STDMETHODIMP_(LONG)
  2678. CAMMediaSampleImpl<_S, _A>::GetActualDataLength(void)
  2679. {
  2680. return m_lActual;
  2681. }
  2682. template <class _S, class _A>
  2683. STDMETHODIMP
  2684. CAMMediaSampleImpl<_S, _A>::SetActualDataLength(LONG lActual)
  2685. {
  2686. if (lActual > m_cbBuffer) {
  2687. _ASSERTE(lActual <= GetSize());
  2688. return VFW_E_BUFFER_OVERFLOW;
  2689. }
  2690. m_lActual = lActual;
  2691. return NOERROR;
  2692. }
  2693. /* These allow for limited format changes in band */
  2694. template <class _S, class _A>
  2695. STDMETHODIMP
  2696. CAMMediaSampleImpl<_S, _A>::GetMediaType(AM_MEDIA_TYPE **ppMediaType)
  2697. {
  2698. //ValidateReadWritePtr(ppMediaType,sizeof(AM_MEDIA_TYPE *));
  2699. _ASSERTE(ppMediaType);
  2700. /* Do we have a new media type for them */
  2701. if (!(m_dwFlags & Sample_TypeChanged)) {
  2702. _ASSERTE(m_pMediaType == NULL);
  2703. *ppMediaType = NULL;
  2704. return S_FALSE;
  2705. }
  2706. _ASSERTE(m_pMediaType);
  2707. /* Create a copy of our media type */
  2708. *ppMediaType = CreateMediaType(m_pMediaType);
  2709. if (*ppMediaType == NULL) {
  2710. return E_OUTOFMEMORY;
  2711. }
  2712. return NOERROR;
  2713. }
  2714. /* Mark this sample as having a different format type */
  2715. template <class _S, class _A>
  2716. STDMETHODIMP
  2717. CAMMediaSampleImpl<_S, _A>::SetMediaType(AM_MEDIA_TYPE *pMediaType)
  2718. {
  2719. /* Delete the current media type */
  2720. if (m_pMediaType) {
  2721. DeleteMediaType(m_pMediaType);
  2722. m_pMediaType = NULL;
  2723. }
  2724. /* Mechanism for resetting the format type */
  2725. if (pMediaType == NULL) {
  2726. m_dwFlags &= ~Sample_TypeChanged;
  2727. return NOERROR;
  2728. }
  2729. _ASSERTE(pMediaType);
  2730. //ValidateReadPtr(pMediaType,sizeof(AM_MEDIA_TYPE));
  2731. /* Take a copy of the media type */
  2732. m_pMediaType = CreateMediaType(pMediaType);
  2733. if (m_pMediaType == NULL) {
  2734. m_dwFlags &= ~Sample_TypeChanged;
  2735. return E_OUTOFMEMORY;
  2736. }
  2737. m_dwFlags |= Sample_TypeChanged;
  2738. return NOERROR;
  2739. }
  2740. // Set and get properties (IMediaSample2)
  2741. template <class _S, class _A>
  2742. STDMETHODIMP CAMMediaSampleImpl<_S, _A>::GetProperties(
  2743. DWORD cbProperties,
  2744. BYTE * pbProperties
  2745. )
  2746. {
  2747. if (0 != cbProperties) {
  2748. if (pbProperties == NULL) {
  2749. return E_POINTER;
  2750. }
  2751. // Return generic stuff up to the length
  2752. AM_SAMPLE2_PROPERTIES Props;
  2753. Props.cbData = min(cbProperties, sizeof(Props));
  2754. Props.dwSampleFlags = m_dwFlags & ~Sample_MediaTimeValid;
  2755. Props.dwTypeSpecificFlags = m_dwTypeSpecificFlags;
  2756. Props.pbBuffer = m_pBuffer;
  2757. Props.cbBuffer = m_cbBuffer;
  2758. Props.lActual = m_lActual;
  2759. Props.tStart = m_Start;
  2760. Props.tStop = m_End;
  2761. if (m_dwFlags & AM_SAMPLE_TYPECHANGED) {
  2762. Props.pMediaType = m_pMediaType;
  2763. } else {
  2764. Props.pMediaType = NULL;
  2765. }
  2766. CopyMemory(pbProperties, &Props, Props.cbData);
  2767. }
  2768. return S_OK;
  2769. }
  2770. #define CONTAINS_FIELD(type, field, offset) \
  2771. ((FIELD_OFFSET(type, field) + sizeof(((type *)0)->field)) <= offset)
  2772. template <class _S, class _A>
  2773. HRESULT CAMMediaSampleImpl<_S, _A>::SetProperties(
  2774. DWORD cbProperties,
  2775. const BYTE * pbProperties
  2776. )
  2777. {
  2778. /* Generic properties */
  2779. AM_MEDIA_TYPE *pMediaType = NULL;
  2780. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbData, cbProperties)) {
  2781. if (pbProperties == NULL) {
  2782. return E_POINTER;
  2783. }
  2784. AM_SAMPLE2_PROPERTIES *pProps =
  2785. (AM_SAMPLE2_PROPERTIES *)pbProperties;
  2786. /* Don't use more data than is actually there */
  2787. if (pProps->cbData < cbProperties) {
  2788. cbProperties = pProps->cbData;
  2789. }
  2790. /* We only handle IMediaSample2 */
  2791. if (cbProperties > sizeof(*pProps) ||
  2792. pProps->cbData > sizeof(*pProps)) {
  2793. return E_INVALIDARG;
  2794. }
  2795. /* Do checks first, the assignments (for backout) */
  2796. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwSampleFlags, cbProperties)) {
  2797. /* Check the flags */
  2798. if (pProps->dwSampleFlags &
  2799. (~Sample_ValidFlags | Sample_MediaTimeValid)) {
  2800. return E_INVALIDARG;
  2801. }
  2802. /* Check a flag isn't being set for a property
  2803. not being provided
  2804. */
  2805. if ((pProps->dwSampleFlags & AM_SAMPLE_TIMEVALID) &&
  2806. !(m_dwFlags & AM_SAMPLE_TIMEVALID) &&
  2807. !CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStop, cbProperties)) {
  2808. return E_INVALIDARG;
  2809. }
  2810. }
  2811. /* NB - can't SET the pointer or size */
  2812. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pbBuffer, cbProperties)) {
  2813. /* Check pbBuffer */
  2814. if (pProps->pbBuffer != 0 && pProps->pbBuffer != m_pBuffer) {
  2815. return E_INVALIDARG;
  2816. }
  2817. }
  2818. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbBuffer, cbProperties)) {
  2819. /* Check cbBuffer */
  2820. if (pProps->cbBuffer != 0 && pProps->cbBuffer != m_cbBuffer) {
  2821. return E_INVALIDARG;
  2822. }
  2823. }
  2824. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbBuffer, cbProperties) &&
  2825. CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, lActual, cbProperties)) {
  2826. /* Check lActual */
  2827. if (pProps->cbBuffer < pProps->lActual) {
  2828. return E_INVALIDARG;
  2829. }
  2830. }
  2831. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pMediaType, cbProperties)) {
  2832. /* Check pMediaType */
  2833. if (pProps->dwSampleFlags & AM_SAMPLE_TYPECHANGED) {
  2834. if (pProps->pMediaType == NULL) {
  2835. return E_POINTER;
  2836. }
  2837. pMediaType = CreateMediaType(pProps->pMediaType);
  2838. if (pMediaType == NULL) {
  2839. return E_OUTOFMEMORY;
  2840. }
  2841. }
  2842. }
  2843. /* Now do the assignments */
  2844. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwSampleFlags, cbProperties)) {
  2845. /* Set the flags */
  2846. m_dwFlags = pProps->dwSampleFlags |
  2847. (m_dwFlags & Sample_MediaTimeValid);
  2848. m_dwTypeSpecificFlags = pProps->dwTypeSpecificFlags;
  2849. } else {
  2850. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwTypeSpecificFlags, cbProperties)) {
  2851. m_dwTypeSpecificFlags = pProps->dwTypeSpecificFlags;
  2852. }
  2853. }
  2854. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, lActual, cbProperties)) {
  2855. /* Set lActual */
  2856. m_lActual = pProps->lActual;
  2857. }
  2858. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStop, cbProperties)) {
  2859. /* Set the times */
  2860. m_End = pProps->tStop;
  2861. }
  2862. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStart, cbProperties)) {
  2863. /* Set the times */
  2864. m_Start = pProps->tStart;
  2865. }
  2866. if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pMediaType, cbProperties)) {
  2867. /* Set pMediaType */
  2868. if (pProps->dwSampleFlags & AM_SAMPLE_TYPECHANGED) {
  2869. if (m_pMediaType != NULL) {
  2870. DeleteMediaType(m_pMediaType);
  2871. }
  2872. m_pMediaType = pMediaType;
  2873. }
  2874. }
  2875. }
  2876. return S_OK;
  2877. }
  2878. //=====================================================================
  2879. //=====================================================================
  2880. // Implements CAMBaseAllocator
  2881. //=====================================================================
  2882. //=====================================================================
  2883. /* Constructor overrides the default settings for the free list to request
  2884. that it be alertable (ie the list can be cast to a handle which can be
  2885. passed to WaitForSingleObject). Both of the allocator lists also ask for
  2886. object locking, the all list matches the object default settings but I
  2887. have included them here just so it is obvious what kind of list it is */
  2888. template <class _A, class _S>
  2889. CAMBaseAllocator<_A, _S>::CAMBaseAllocator() :
  2890. m_lAllocated(0),
  2891. m_bChanged(FALSE),
  2892. m_bCommitted(FALSE),
  2893. m_bDecommitInProgress(FALSE),
  2894. m_lSize(0),
  2895. m_lCount(0),
  2896. m_lAlignment(0),
  2897. m_lPrefix(0),
  2898. m_hSem(NULL),
  2899. m_lWaiting(0)
  2900. {
  2901. }
  2902. template <class _A, class _S>
  2903. HRESULT CAMBaseAllocator<_A, _S>::FinalConstruct()
  2904. {
  2905. HRESULT hr = CComObjectRoot::FinalConstruct();
  2906. if (FAILED(hr)) {
  2907. return hr;
  2908. }
  2909. m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL);
  2910. if (m_hSem == NULL) {
  2911. return E_OUTOFMEMORY;
  2912. } else {
  2913. return S_OK;
  2914. }
  2915. }
  2916. /* Destructor */
  2917. template <class _A, class _S>
  2918. CAMBaseAllocator<_A, _S>::~CAMBaseAllocator()
  2919. {
  2920. // we can't call Decommit here since that would mean a call to a
  2921. // pure virtual in destructor.
  2922. // We must assume that the derived class has gone into decommit state in
  2923. // its destructor.
  2924. _ASSERTE(!m_bCommitted);
  2925. if (m_hSem != NULL) {
  2926. EXECUTE_ASSERT(CloseHandle(m_hSem));
  2927. }
  2928. }
  2929. /* This sets the size and count of the required samples. The memory isn't
  2930. actually allocated until Commit() is called, if memory has already been
  2931. allocated then assuming no samples are outstanding the user may call us
  2932. to change the buffering, the memory will be released in Commit() */
  2933. template <class _A, class _S>
  2934. STDMETHODIMP
  2935. CAMBaseAllocator<_A, _S>::SetProperties(
  2936. ALLOCATOR_PROPERTIES* pRequest,
  2937. ALLOCATOR_PROPERTIES* pActual)
  2938. {
  2939. if (pRequest == NULL || pActual == NULL) {
  2940. return E_POINTER;
  2941. }
  2942. // ValidateReadWritePtr(pActual, sizeof(ALLOCATOR_PROPERTIES));
  2943. CAutoLock cObjectLock(&m_Lock);
  2944. ZeroMemory(pActual, sizeof(ALLOCATOR_PROPERTIES));
  2945. _ASSERTE(pRequest->cbBuffer > 0);
  2946. /* Check the alignment requested */
  2947. if (pRequest->cbAlign != 1) {
  2948. #if 0 // No decent logging macros in ATL
  2949. DbgLog((LOG_ERROR, 2, TEXT("Alignment requested was 0x%x, not 1"),
  2950. pRequest->cbAlign));
  2951. #endif
  2952. return VFW_E_BADALIGN;
  2953. }
  2954. /* Can't do this if already committed, there is an argument that says we
  2955. should not reject the SetProperties call if there are buffers still
  2956. active. However this is called by the source filter, which is the same
  2957. person who is holding the samples. Therefore it is not unreasonable
  2958. for them to free all their samples before changing the requirements */
  2959. if (m_bCommitted) {
  2960. return VFW_E_ALREADY_COMMITTED;
  2961. }
  2962. /* Must be no outstanding buffers */
  2963. if (m_lAllocated != m_lFree.GetCount()) {
  2964. return VFW_E_BUFFERS_OUTSTANDING;
  2965. }
  2966. /* There isn't any real need to check the parameters as they
  2967. will just be rejected when the user finally calls Commit */
  2968. pActual->cbBuffer = m_lSize = pRequest->cbBuffer;
  2969. pActual->cBuffers = m_lCount = pRequest->cBuffers;
  2970. pActual->cbAlign = m_lAlignment = pRequest->cbAlign;
  2971. pActual->cbPrefix = m_lPrefix = pRequest->cbPrefix;
  2972. m_bChanged = TRUE;
  2973. return NOERROR;
  2974. }
  2975. template <class _A, class _S>
  2976. STDMETHODIMP
  2977. CAMBaseAllocator<_A, _S>::GetProperties(
  2978. ALLOCATOR_PROPERTIES * pActual)
  2979. {
  2980. if (pActual == NULL) {
  2981. return E_POINTER;
  2982. }
  2983. // ValidateReadWritePtr(pActual,sizeof(ALLOCATOR_PROPERTIES));
  2984. CAutoLock cObjectLock(&m_Lock);
  2985. pActual->cbBuffer = m_lSize;
  2986. pActual->cBuffers = m_lCount;
  2987. pActual->cbAlign = m_lAlignment;
  2988. pActual->cbPrefix = m_lPrefix;
  2989. return NOERROR;
  2990. }
  2991. // get container for a sample. Blocking, synchronous call to get the
  2992. // next free buffer (as represented by an IMediaSample interface).
  2993. // on return, the time etc properties will be invalid, but the buffer
  2994. // pointer and size will be correct.
  2995. template <class _A, class _S>
  2996. HRESULT CAMBaseAllocator<_A, _S>::GetBuffer(IMediaSample **ppBuffer,
  2997. REFERENCE_TIME *pStartTime,
  2998. REFERENCE_TIME *pEndTime,
  2999. DWORD dwFlags
  3000. )
  3001. {
  3002. UNREFERENCED_PARAMETER(pStartTime);
  3003. UNREFERENCED_PARAMETER(pEndTime);
  3004. UNREFERENCED_PARAMETER(dwFlags);
  3005. _S *pSample;
  3006. *ppBuffer = NULL;
  3007. for (;;)
  3008. {
  3009. { // scope for lock
  3010. CAutoLock cObjectLock(&m_Lock);
  3011. /* Check we are committed */
  3012. if (!m_bCommitted) {
  3013. return VFW_E_NOT_COMMITTED;
  3014. }
  3015. pSample = (_S *)m_lFree.RemoveHead();
  3016. if (pSample == NULL) {
  3017. SetWaiting();
  3018. }
  3019. }
  3020. /* If we didn't get a sample then wait for the list to signal */
  3021. if (pSample) {
  3022. break;
  3023. }
  3024. _ASSERTE(m_hSem != NULL);
  3025. WaitForSingleObject(m_hSem, INFINITE);
  3026. }
  3027. /* Addref the buffer up to one. On release
  3028. back to zero instead of being deleted, it will requeue itself by
  3029. calling the ReleaseBuffer member function. NOTE the owner of a
  3030. media sample must always be derived from CAMBaseAllocator */
  3031. _ASSERTE(pSample->m_cRef == 0);
  3032. pSample->m_cRef = 1;
  3033. *ppBuffer = pSample;
  3034. return NOERROR;
  3035. }
  3036. /* Final release of a CAMMediaSampleImpl<CAMMediaSampleImpl, _F> will call this */
  3037. template <class _A, class _S>
  3038. STDMETHODIMP
  3039. CAMBaseAllocator<_A, _S>::ReleaseBuffer(IMediaSample * pSample)
  3040. {
  3041. if (pSample == NULL) {
  3042. return E_POINTER;
  3043. }
  3044. //ValidateReadPtr(pSample,sizeof(IMediaSample));
  3045. BOOL bRelease = FALSE;
  3046. {
  3047. CAutoLock cal(&m_Lock);
  3048. /* Put back on the free list */
  3049. m_lFree.Add((_S *)pSample);
  3050. if (m_lWaiting != 0) {
  3051. NotifySample();
  3052. }
  3053. // if there is a pending Decommit, then we need to complete it by
  3054. // calling Free() when the last buffer is placed on the free list
  3055. LONG l1 = m_lFree.GetCount();
  3056. if (m_bDecommitInProgress && (l1 == m_lAllocated)) {
  3057. Free();
  3058. m_bDecommitInProgress = FALSE;
  3059. bRelease = TRUE;
  3060. }
  3061. }
  3062. /* For each buffer there is one AddRef, made in GetBuffer and released
  3063. here. This may cause the allocator and all samples to be deleted */
  3064. if (bRelease) {
  3065. Release();
  3066. }
  3067. return NOERROR;
  3068. }
  3069. template <class _A, class _S>
  3070. void
  3071. CAMBaseAllocator<_A, _S>::NotifySample()
  3072. {
  3073. if (m_lWaiting != 0) {
  3074. _ASSERTE(m_hSem != NULL);
  3075. ReleaseSemaphore(m_hSem, m_lWaiting, 0);
  3076. m_lWaiting = 0;
  3077. }
  3078. }
  3079. template <class _A, class _S>
  3080. STDMETHODIMP
  3081. CAMBaseAllocator<_A, _S>::Commit()
  3082. {
  3083. /* Check we are not decommitted */
  3084. CAutoLock cObjectLock(&m_Lock);
  3085. // cannot need to alloc or re-alloc if we are committed
  3086. if (m_bCommitted) {
  3087. return NOERROR;
  3088. }
  3089. /* Allow GetBuffer calls */
  3090. m_bCommitted = TRUE;
  3091. // is there a pending decommit ? if so, just cancel it
  3092. if (m_bDecommitInProgress) {
  3093. m_bDecommitInProgress = FALSE;
  3094. // don't call Alloc at this point. He cannot allow SetProperties
  3095. // between Decommit and the last free, so the buffer size cannot have
  3096. // changed. And because some of the buffers are not free yet, he
  3097. // cannot re-alloc anyway.
  3098. return NOERROR;
  3099. }
  3100. // DbgLog((LOG_MEMORY, 1, TEXT("Allocating: %ldx%ld"), m_lCount, m_lSize));
  3101. // actually need to allocate the samples
  3102. HRESULT hr = Alloc();
  3103. if (FAILED(hr)) {
  3104. m_bCommitted = FALSE;
  3105. return hr;
  3106. }
  3107. AddRef();
  3108. return NOERROR;
  3109. }
  3110. template <class _A, class _S>
  3111. STDMETHODIMP
  3112. CAMBaseAllocator<_A, _S>::Decommit()
  3113. {
  3114. BOOL bRelease = FALSE;
  3115. {
  3116. /* Check we are not already decommitted */
  3117. CAutoLock cObjectLock(&m_Lock);
  3118. if (m_bCommitted == FALSE) {
  3119. if (m_bDecommitInProgress == FALSE) {
  3120. return NOERROR;
  3121. }
  3122. }
  3123. /* No more GetBuffer calls will succeed */
  3124. m_bCommitted = FALSE;
  3125. // are any buffers outstanding?
  3126. if (m_lFree.GetCount() < m_lAllocated) {
  3127. // please complete the decommit when last buffer is freed
  3128. m_bDecommitInProgress = TRUE;
  3129. } else {
  3130. m_bDecommitInProgress = FALSE;
  3131. // need to complete the decommit here as there are no
  3132. // outstanding buffers
  3133. Free();
  3134. bRelease = TRUE;
  3135. }
  3136. // Tell anyone waiting that they can go now so we can
  3137. // reject their call
  3138. NotifySample();
  3139. }
  3140. if (bRelease) {
  3141. Release();
  3142. }
  3143. return NOERROR;
  3144. }
  3145. /* Base definition of allocation which checks we are ok to go ahead and do
  3146. the full allocation. We return S_FALSE if the requirements are the same */
  3147. template <class _A, class _S>
  3148. HRESULT
  3149. CAMBaseAllocator<_A, _S>::Alloc(void)
  3150. {
  3151. /* Error if he hasn't set the size yet */
  3152. if (m_lCount <= 0 || m_lSize <= 0 || m_lAlignment <= 0) {
  3153. return VFW_E_SIZENOTSET;
  3154. }
  3155. /* should never get here while buffers outstanding */
  3156. _ASSERTE(m_lFree.GetCount() == m_lAllocated);
  3157. /* If the requirements haven't changed then don't reallocate */
  3158. if (m_bChanged == FALSE) {
  3159. return S_FALSE;
  3160. }
  3161. return NOERROR;
  3162. }
  3163. /* Implement CAMBaseAllocator::CSampleList::Remove(pSample)
  3164. Removes pSample from the list
  3165. */
  3166. template <class _A, class _S>
  3167. void
  3168. CAMBaseAllocator<_A, _S>::CSampleList::Remove(_S * pSample)
  3169. {
  3170. _S **pSearch;
  3171. for (pSearch = &m_List;
  3172. *pSearch != NULL;
  3173. pSearch = &(NextSample(*pSearch))) {
  3174. if (*pSearch == pSample) {
  3175. *pSearch = NextSample(pSample);
  3176. NextSample(pSample) = NULL;
  3177. m_nOnList--;
  3178. return;
  3179. }
  3180. }
  3181. DbgBreak("Couldn't find sample in list");
  3182. }
  3183. //=====================================================================
  3184. //=====================================================================
  3185. // Implements CMemAllocator
  3186. //=====================================================================
  3187. //=====================================================================
  3188. CAMMemAllocator::CAMMemAllocator() : m_pBuffer(NULL)
  3189. {
  3190. }
  3191. /* This sets the size and count of the required samples. The memory isn't
  3192. actually allocated until Commit() is called, if memory has already been
  3193. allocated then assuming no samples are outstanding the user may call us
  3194. to change the buffering, the memory will be released in Commit() */
  3195. STDMETHODIMP
  3196. CAMMemAllocator::SetProperties(
  3197. ALLOCATOR_PROPERTIES* pRequest,
  3198. ALLOCATOR_PROPERTIES* pActual)
  3199. {
  3200. if (pActual == NULL) {
  3201. return E_POINTER;
  3202. }
  3203. // ValidateReadWritePtr(pActual,sizeof(ALLOCATOR_PROPERTIES));
  3204. CAutoLock cObjectLock(&m_Lock);
  3205. ZeroMemory(pActual, sizeof(ALLOCATOR_PROPERTIES));
  3206. _ASSERTE(pRequest->cbBuffer > 0);
  3207. SYSTEM_INFO SysInfo;
  3208. GetSystemInfo(&SysInfo);
  3209. /* Check the alignment request is a power of 2 */
  3210. if ((-pRequest->cbAlign & pRequest->cbAlign) != pRequest->cbAlign) {
  3211. #if 0
  3212. DbgLog((LOG_ERROR, 1, TEXT("Alignment requested 0x%x not a power of 2!"),
  3213. pRequest->cbAlign));
  3214. #endif
  3215. }
  3216. /* Check the alignment requested */
  3217. if (pRequest->cbAlign == 0 ||
  3218. SysInfo.dwAllocationGranularity & (pRequest->cbAlign - 1) != 0) {
  3219. #if 0
  3220. DbgLog((LOG_ERROR, 1, TEXT("Invalid alignment 0x%x requested - granularity = 0x%x"),
  3221. pRequest->cbAlign, SysInfo.dwAllocationGranularity));
  3222. #endif
  3223. return VFW_E_BADALIGN;
  3224. }
  3225. /* Can't do this if already committed, there is an argument that says we
  3226. should not reject the SetProperties call if there are buffers still
  3227. active. However this is called by the source filter, which is the same
  3228. person who is holding the samples. Therefore it is not unreasonable
  3229. for them to free all their samples before changing the requirements */
  3230. if (m_bCommitted == TRUE) {
  3231. return VFW_E_ALREADY_COMMITTED;
  3232. }
  3233. /* Must be no outstanding buffers */
  3234. if (m_lFree.GetCount() < m_lAllocated) {
  3235. return VFW_E_BUFFERS_OUTSTANDING;
  3236. }
  3237. /* There isn't any real need to check the parameters as they
  3238. will just be rejected when the user finally calls Commit */
  3239. // round length up to alignment - remember that prefix is included in
  3240. // the alignment
  3241. LONG lSize = pRequest->cbBuffer + pRequest->cbPrefix;
  3242. LONG lRemainder = lSize % pRequest->cbAlign;
  3243. if (lRemainder != 0) {
  3244. lSize = lSize - lRemainder + pRequest->cbAlign;
  3245. }
  3246. pActual->cbBuffer = m_lSize = (lSize - pRequest->cbPrefix);
  3247. pActual->cBuffers = m_lCount = pRequest->cBuffers;
  3248. pActual->cbAlign = m_lAlignment = pRequest->cbAlign;
  3249. pActual->cbPrefix = m_lPrefix = pRequest->cbPrefix;
  3250. m_bChanged = TRUE;
  3251. return NOERROR;
  3252. }
  3253. // override this to allocate our resources when Commit is called.
  3254. //
  3255. // note that our resources may be already allocated when this is called,
  3256. // since we don't free them on Decommit. We will only be called when in
  3257. // decommit state with all buffers free.
  3258. //
  3259. // object locked by caller
  3260. HRESULT
  3261. CAMMemAllocator::Alloc(void)
  3262. {
  3263. CAutoLock lck(&m_Lock);
  3264. /* Check he has called SetProperties */
  3265. HRESULT hr = _BaseAllocator::Alloc();
  3266. if (FAILED(hr)) {
  3267. return hr;
  3268. }
  3269. /* If the requirements haven't changed then don't reallocate */
  3270. if (hr == S_FALSE) {
  3271. _ASSERTE(m_pBuffer);
  3272. return NOERROR;
  3273. }
  3274. _ASSERTE(hr == S_OK); // we use this fact in the loop below
  3275. /* Free the old resources */
  3276. if (m_pBuffer) {
  3277. ReallyFree();
  3278. }
  3279. /* Create the contiguous memory block for the samples
  3280. making sure it's properly aligned (64K should be enough!)
  3281. */
  3282. _ASSERTE(m_lAlignment != 0 &&
  3283. (m_lSize + m_lPrefix) % m_lAlignment == 0);
  3284. m_pBuffer = (PBYTE)VirtualAlloc(NULL,
  3285. m_lCount * (m_lSize + m_lPrefix),
  3286. MEM_COMMIT,
  3287. PAGE_READWRITE);
  3288. if (m_pBuffer == NULL) {
  3289. return E_OUTOFMEMORY;
  3290. }
  3291. LPBYTE pNext = m_pBuffer;
  3292. CAMMediaSample<CAMMemAllocator> *pSample;
  3293. _ASSERTE(m_lAllocated == 0);
  3294. // Create the new samples - we have allocated m_lSize bytes for each sample
  3295. // plus m_lPrefix bytes per sample as a prefix. We set the pointer to
  3296. // the memory after the prefix - so that GetPointer() will return a pointer
  3297. // to m_lSize bytes.
  3298. for (; m_lAllocated < m_lCount; m_lAllocated++, pNext += (m_lSize + m_lPrefix)) {
  3299. pSample = new CAMMediaSample<CAMMemAllocator>;
  3300. _ASSERTE(SUCCEEDED(hr));
  3301. if (pSample == NULL) {
  3302. return E_OUTOFMEMORY;
  3303. }
  3304. pSample->Init(this);
  3305. pSample->SetPointer(pNext + m_lPrefix, m_lSize);
  3306. // This CANNOT fail
  3307. m_lFree.Add(pSample);
  3308. }
  3309. m_bChanged = FALSE;
  3310. return NOERROR;
  3311. }
  3312. // override this to free up any resources we have allocated.
  3313. // called from the base class on Decommit when all buffers have been
  3314. // returned to the free list.
  3315. //
  3316. // caller has already locked the object.
  3317. // in our case, we keep the memory until we are deleted, so
  3318. // we do nothing here. The memory is deleted in the destructor by
  3319. // calling ReallyFree()
  3320. void
  3321. CAMMemAllocator::Free(void)
  3322. {
  3323. return;
  3324. }
  3325. // called from the destructor (and from Alloc if changing size/count) to
  3326. // actually free up the memory
  3327. void
  3328. CAMMemAllocator::ReallyFree(void)
  3329. {
  3330. /* Should never be deleting this unless all buffers are freed */
  3331. _ASSERTE(m_lAllocated == m_lFree.GetCount());
  3332. /* Free up all the CAMMediaSamples */
  3333. CAMMediaSample<CAMMemAllocator> *pSample;
  3334. for (;;) {
  3335. pSample = m_lFree.RemoveHead();
  3336. if (pSample != NULL) {
  3337. delete pSample;
  3338. } else {
  3339. break;
  3340. }
  3341. }
  3342. m_lAllocated = 0;
  3343. // free the block of buffer memory
  3344. if (m_pBuffer) {
  3345. EXECUTE_ASSERT(VirtualFree(m_pBuffer, 0, MEM_RELEASE));
  3346. m_pBuffer = NULL;
  3347. }
  3348. }
  3349. /* Destructor frees our memory resources */
  3350. CAMMemAllocator::~CAMMemAllocator()
  3351. {
  3352. Decommit();
  3353. ReallyFree();
  3354. }
  3355. // Remove warnings about unreferenced inline functions
  3356. #pragma warning(disable:4514)