Leaked source code of windows server 2003
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.

2685 lines
92 KiB

  1. //------------------------------------------------------------------------------
  2. // File: WinUtil.cpp
  3. //
  4. // Desc: DirectShow base classes - implements generic window handler class.
  5. //
  6. //@@BEGIN_MSINTERNAL
  7. //
  8. // December 1995
  9. //
  10. //@@END_MSINTERNAL
  11. // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved.
  12. //------------------------------------------------------------------------------
  13. #include <streams.h>
  14. #include <limits.h>
  15. #include <dvdmedia.h>
  16. static UINT MsgDestroy;
  17. // Constructor
  18. CBaseWindow::CBaseWindow(BOOL bDoGetDC, bool bDoPostToDestroy) :
  19. m_hInstance(g_hInst),
  20. m_hwnd(NULL),
  21. m_hdc(NULL),
  22. m_bActivated(FALSE),
  23. m_pClassName(NULL),
  24. m_ClassStyles(0),
  25. m_WindowStyles(0),
  26. m_WindowStylesEx(0),
  27. m_ShowStageMessage(0),
  28. m_ShowStageTop(0),
  29. m_MemoryDC(NULL),
  30. m_hPalette(NULL),
  31. m_bBackground(FALSE),
  32. #ifdef DEBUG
  33. m_bRealizing(FALSE),
  34. #endif
  35. m_bNoRealize(FALSE),
  36. m_bDoPostToDestroy(bDoPostToDestroy)
  37. {
  38. m_bDoGetDC = bDoGetDC;
  39. }
  40. // Prepare a window by spinning off a worker thread to do the creation and
  41. // also poll the message input queue. We leave this to be called by derived
  42. // classes because they might want to override methods like MessageLoop and
  43. // InitialiseWindow, if we do this during construction they'll ALWAYS call
  44. // this base class methods. We make the worker thread create the window so
  45. // it owns it rather than the filter graph thread which is constructing us
  46. HRESULT CBaseWindow::PrepareWindow()
  47. {
  48. if (m_hwnd) return NOERROR;
  49. ASSERT(m_hwnd == NULL);
  50. ASSERT(m_hdc == NULL);
  51. // Get the derived object's window and class styles
  52. m_pClassName = GetClassWindowStyles(&m_ClassStyles,
  53. &m_WindowStyles,
  54. &m_WindowStylesEx);
  55. if (m_pClassName == NULL) {
  56. return E_FAIL;
  57. }
  58. // Register our special private messages
  59. m_ShowStageMessage = RegisterWindowMessage(SHOWSTAGE);
  60. // RegisterWindowMessage() returns 0 if an error occurs.
  61. if (0 == m_ShowStageMessage) {
  62. return AmGetLastErrorToHResult();
  63. }
  64. m_ShowStageTop = RegisterWindowMessage(SHOWSTAGETOP);
  65. if (0 == m_ShowStageTop) {
  66. return AmGetLastErrorToHResult();
  67. }
  68. m_RealizePalette = RegisterWindowMessage(REALIZEPALETTE);
  69. if (0 == m_RealizePalette) {
  70. return AmGetLastErrorToHResult();
  71. }
  72. MsgDestroy = RegisterWindowMessage(TEXT("AM_DESTROY"));
  73. if (0 == MsgDestroy) {
  74. return AmGetLastErrorToHResult();
  75. }
  76. return DoCreateWindow();
  77. }
  78. // Destructor just a placeholder so that we know it becomes virtual
  79. // Derived classes MUST call DoneWithWindow in their destructors so
  80. // that no messages arrive after the derived class constructor ends
  81. #ifdef DEBUG
  82. CBaseWindow::~CBaseWindow()
  83. {
  84. ASSERT(m_hwnd == NULL);
  85. ASSERT(m_hdc == NULL);
  86. }
  87. #endif
  88. // We use the sync worker event to have the window destroyed. All we do is
  89. // signal the event and wait on the window thread handle. Trying to send it
  90. // messages causes too many problems, furthermore to be on the safe side we
  91. // just wait on the thread handle while it returns WAIT_TIMEOUT or there is
  92. // a sent message to process on this thread. If the constructor failed to
  93. // create the thread in the first place then the loop will get terminated
  94. HRESULT CBaseWindow::DoneWithWindow()
  95. {
  96. if (!IsWindow(m_hwnd) || (GetWindowThreadProcessId(m_hwnd, NULL) != GetCurrentThreadId())) {
  97. if (IsWindow(m_hwnd)) {
  98. if (m_bDoPostToDestroy) {
  99. CAMEvent m_evDone;
  100. // We must post a message to destroy the window
  101. // That way we can't be in the middle of processing a
  102. // message posted to our window when we do go away
  103. // Sending a message gives less synchronization.
  104. PostMessage(m_hwnd, MsgDestroy, (WPARAM)(HANDLE)m_evDone, 0);
  105. WaitDispatchingMessages(m_evDone, INFINITE);
  106. } else {
  107. SendMessage(m_hwnd, MsgDestroy, 0, 0);
  108. }
  109. }
  110. //
  111. // This is not a leak, the window manager automatically free's
  112. // hdc's that were got via GetDC, which is the case here.
  113. // We set it to NULL so that we don't get any asserts later.
  114. //
  115. m_hdc = NULL;
  116. //
  117. // We need to free this DC though because USER32 does not know
  118. // anything about it.
  119. //
  120. if (m_MemoryDC)
  121. {
  122. EXECUTE_ASSERT(DeleteDC(m_MemoryDC));
  123. m_MemoryDC = NULL;
  124. }
  125. // Reset the window variables
  126. m_hwnd = NULL;
  127. return NOERROR;
  128. }
  129. const HWND hwnd = m_hwnd;
  130. if (hwnd == NULL) {
  131. return NOERROR;
  132. }
  133. InactivateWindow();
  134. NOTE("Inactivated");
  135. // Reset the window styles before destruction
  136. SetWindowLong(hwnd,GWL_STYLE,m_WindowStyles);
  137. ASSERT(GetParent(hwnd) == NULL);
  138. NOTE1("Reset window styles %d",m_WindowStyles);
  139. // UnintialiseWindow sets m_hwnd to NULL so save a copy
  140. UninitialiseWindow();
  141. DbgLog((LOG_TRACE, 2, TEXT("Destroying 0x%8.8X"), hwnd));
  142. if (!DestroyWindow(hwnd)) {
  143. DbgLog((LOG_TRACE, 0, TEXT("DestroyWindow %8.8X failed code %d"),
  144. hwnd, GetLastError()));
  145. DbgBreak("");
  146. }
  147. // Reset our state so we can be prepared again
  148. m_pClassName = NULL;
  149. m_ClassStyles = 0;
  150. m_WindowStyles = 0;
  151. m_WindowStylesEx = 0;
  152. m_ShowStageMessage = 0;
  153. m_ShowStageTop = 0;
  154. return NOERROR;
  155. }
  156. // Called at the end to put the window in an inactive state. The pending list
  157. // will always have been cleared by this time so event if the worker thread
  158. // gets has been signaled and gets in to render something it will find both
  159. // the state has been changed and that there are no available sample images
  160. // Since we wait on the window thread to complete we don't lock the object
  161. HRESULT CBaseWindow::InactivateWindow()
  162. {
  163. // Has the window been activated
  164. if (m_bActivated == FALSE) {
  165. return S_FALSE;
  166. }
  167. m_bActivated = FALSE;
  168. ShowWindow(m_hwnd,SW_HIDE);
  169. return NOERROR;
  170. }
  171. HRESULT CBaseWindow::CompleteConnect()
  172. {
  173. m_bActivated = FALSE;
  174. return NOERROR;
  175. }
  176. // This displays a normal window. We ask the base window class for default
  177. // sizes which unless overriden will return DEFWIDTH and DEFHEIGHT. We go
  178. // through a couple of extra hoops to get the client area the right size
  179. // as the object specifies which accounts for the AdjustWindowRectEx calls
  180. // We also DWORD align the left and top coordinates of the window here to
  181. // maximise the chance of being able to use DCI/DirectDraw primary surface
  182. HRESULT CBaseWindow::ActivateWindow()
  183. {
  184. // Has the window been sized and positioned already
  185. if (m_bActivated == TRUE || GetParent(m_hwnd) != NULL) {
  186. SetWindowPos(m_hwnd, // Our window handle
  187. HWND_TOP, // Put it at the top
  188. 0, 0, 0, 0, // Leave in current position
  189. SWP_NOMOVE | // Don't change it's place
  190. SWP_NOSIZE); // Change Z-order only
  191. m_bActivated = TRUE;
  192. return S_FALSE;
  193. }
  194. // Calculate the desired client rectangle
  195. RECT WindowRect, ClientRect = GetDefaultRect();
  196. GetWindowRect(m_hwnd,&WindowRect);
  197. AdjustWindowRectEx(&ClientRect,GetWindowLong(m_hwnd,GWL_STYLE),
  198. FALSE,GetWindowLong(m_hwnd,GWL_EXSTYLE));
  199. // Align left and top edges on DWORD boundaries
  200. UINT WindowFlags = (SWP_NOACTIVATE | SWP_FRAMECHANGED);
  201. WindowRect.left -= (WindowRect.left & 3);
  202. WindowRect.top -= (WindowRect.top & 3);
  203. SetWindowPos(m_hwnd, // Window handle
  204. HWND_TOP, // Put it at the top
  205. WindowRect.left, // Align left edge
  206. WindowRect.top, // And also top place
  207. WIDTH(&ClientRect), // Horizontal size
  208. HEIGHT(&ClientRect), // Vertical size
  209. WindowFlags); // Don't show window
  210. m_bActivated = TRUE;
  211. return NOERROR;
  212. }
  213. // This can be used to DWORD align the window for maximum performance
  214. HRESULT CBaseWindow::PerformanceAlignWindow()
  215. {
  216. RECT ClientRect,WindowRect;
  217. GetWindowRect(m_hwnd,&WindowRect);
  218. ASSERT(m_bActivated == TRUE);
  219. // Don't do this if we're owned
  220. if (GetParent(m_hwnd)) {
  221. return NOERROR;
  222. }
  223. // Align left and top edges on DWORD boundaries
  224. GetClientRect(m_hwnd, &ClientRect);
  225. MapWindowPoints(m_hwnd, HWND_DESKTOP, (LPPOINT) &ClientRect, 2);
  226. WindowRect.left -= (ClientRect.left & 3);
  227. WindowRect.top -= (ClientRect.top & 3);
  228. UINT WindowFlags = (SWP_NOACTIVATE | SWP_NOSIZE);
  229. SetWindowPos(m_hwnd, // Window handle
  230. HWND_TOP, // Put it at the top
  231. WindowRect.left, // Align left edge
  232. WindowRect.top, // And also top place
  233. (int) 0,(int) 0, // Ignore these sizes
  234. WindowFlags); // Don't show window
  235. return NOERROR;
  236. }
  237. // Install a palette into the base window - we may be called by a different
  238. // thread to the one that owns the window. We have to be careful how we do
  239. // the palette realisation as we could be a different thread to the window
  240. // which would cause an inter thread send message. Therefore we realise the
  241. // palette by sending it a special message but without the window locked
  242. HRESULT CBaseWindow::SetPalette(HPALETTE hPalette)
  243. {
  244. // We must own the window lock during the change
  245. {
  246. CAutoLock cWindowLock(&m_WindowLock);
  247. CAutoLock cPaletteLock(&m_PaletteLock);
  248. ASSERT(hPalette);
  249. m_hPalette = hPalette;
  250. }
  251. return SetPalette();
  252. }
  253. HRESULT CBaseWindow::SetPalette()
  254. {
  255. if (!m_bNoRealize) {
  256. SendMessage(m_hwnd, m_RealizePalette, 0, 0);
  257. return S_OK;
  258. } else {
  259. // Just select the palette
  260. ASSERT(m_hdc);
  261. ASSERT(m_MemoryDC);
  262. CAutoLock cPaletteLock(&m_PaletteLock);
  263. SelectPalette(m_hdc,m_hPalette,m_bBackground);
  264. SelectPalette(m_MemoryDC,m_hPalette,m_bBackground);
  265. return S_OK;
  266. }
  267. }
  268. void CBaseWindow::UnsetPalette()
  269. {
  270. CAutoLock cWindowLock(&m_WindowLock);
  271. CAutoLock cPaletteLock(&m_PaletteLock);
  272. // Get a standard VGA colour palette
  273. HPALETTE hPalette = (HPALETTE) GetStockObject(DEFAULT_PALETTE);
  274. ASSERT(hPalette);
  275. SelectPalette(GetWindowHDC(), hPalette, TRUE);
  276. SelectPalette(GetMemoryHDC(), hPalette, TRUE);
  277. m_hPalette = NULL;
  278. }
  279. void CBaseWindow::LockPaletteLock()
  280. {
  281. m_PaletteLock.Lock();
  282. }
  283. void CBaseWindow::UnlockPaletteLock()
  284. {
  285. m_PaletteLock.Unlock();
  286. }
  287. // Realise our palettes in the window and device contexts
  288. HRESULT CBaseWindow::DoRealisePalette(BOOL bForceBackground)
  289. {
  290. {
  291. CAutoLock cPaletteLock(&m_PaletteLock);
  292. if (m_hPalette == NULL) {
  293. return NOERROR;
  294. }
  295. // Realize the palette on the window thread
  296. ASSERT(m_hdc);
  297. ASSERT(m_MemoryDC);
  298. SelectPalette(m_hdc,m_hPalette,m_bBackground || bForceBackground);
  299. SelectPalette(m_MemoryDC,m_hPalette,m_bBackground);
  300. }
  301. // If we grab a critical section here we can deadlock
  302. // with the window thread because one of the side effects
  303. // of RealizePalette is to send a WM_PALETTECHANGED message
  304. // to every window in the system. In our handling
  305. // of WM_PALETTECHANGED we used to grab this CS too.
  306. // The really bad case is when our renderer calls DoRealisePalette()
  307. // while we're in the middle of processing a palette change
  308. // for another window.
  309. // So don't hold the critical section while actually realising
  310. // the palette. In any case USER is meant to manage palette
  311. // handling - we shouldn't have to serialize everything as well
  312. ASSERT(CritCheckOut(&m_WindowLock));
  313. ASSERT(CritCheckOut(&m_PaletteLock));
  314. EXECUTE_ASSERT(RealizePalette(m_hdc) != GDI_ERROR);
  315. EXECUTE_ASSERT(RealizePalette(m_MemoryDC) != GDI_ERROR);
  316. return (GdiFlush() == FALSE ? S_FALSE : S_OK);
  317. }
  318. // This is the global window procedure
  319. LRESULT CALLBACK WndProc(HWND hwnd, // Window handle
  320. UINT uMsg, // Message ID
  321. WPARAM wParam, // First parameter
  322. LPARAM lParam) // Other parameter
  323. {
  324. // Get the window long that holds our window object pointer
  325. // If it is NULL then we are initialising the window in which
  326. // case the object pointer has been passed in the window creation
  327. // structure. IF we get any messages before WM_NCCREATE we will
  328. // pass them to DefWindowProc.
  329. CBaseWindow *pBaseWindow = (CBaseWindow *)GetWindowLongPtr(hwnd,0);
  330. if (pBaseWindow == NULL) {
  331. // Get the structure pointer from the create struct.
  332. // We can only do this for WM_NCCREATE which should be one of
  333. // the first messages we receive. Anything before this will
  334. // have to be passed to DefWindowProc (i.e. WM_GETMINMAXINFO)
  335. // If the message is WM_NCCREATE we set our pBaseWindow pointer
  336. // and will then place it in the window structure
  337. // turn off WS_EX_LAYOUTRTL style for quartz windows
  338. if (uMsg == WM_NCCREATE) {
  339. SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) & ~0x400000);
  340. }
  341. if ((uMsg != WM_NCCREATE)
  342. || (NULL == (pBaseWindow = *(CBaseWindow**) ((LPCREATESTRUCT)lParam)->lpCreateParams)))
  343. {
  344. return(DefWindowProc(hwnd, uMsg, wParam, lParam));
  345. }
  346. // Set the window LONG to be the object who created us
  347. #ifdef DEBUG
  348. SetLastError(0); // because of the way SetWindowLong works
  349. #endif
  350. LONG_PTR rc = SetWindowLongPtr(hwnd, (DWORD) 0, (LONG_PTR) pBaseWindow);
  351. #ifdef DEBUG
  352. if (0 == rc) {
  353. // SetWindowLong MIGHT have failed. (Read the docs which admit
  354. // that it is awkward to work out if you have had an error.)
  355. LONG lasterror = GetLastError();
  356. ASSERT(0 == lasterror);
  357. // If this is not the case we have not set the pBaseWindow pointer
  358. // into the window structure and we will blow up.
  359. }
  360. #endif
  361. }
  362. // See if this is the packet of death
  363. if (uMsg == MsgDestroy && uMsg != 0) {
  364. pBaseWindow->DoneWithWindow();
  365. if (pBaseWindow->m_bDoPostToDestroy) {
  366. EXECUTE_ASSERT(SetEvent((HANDLE)wParam));
  367. }
  368. return 0;
  369. }
  370. return pBaseWindow->OnReceiveMessage(hwnd,uMsg,wParam,lParam);
  371. }
  372. // When the window size changes we adjust our member variables that
  373. // contain the dimensions of the client rectangle for our window so
  374. // that we come to render an image we will know whether to stretch
  375. BOOL CBaseWindow::OnSize(LONG Width, LONG Height)
  376. {
  377. m_Width = Width;
  378. m_Height = Height;
  379. return TRUE;
  380. }
  381. // This function handles the WM_CLOSE message
  382. BOOL CBaseWindow::OnClose()
  383. {
  384. ShowWindow(m_hwnd,SW_HIDE);
  385. return TRUE;
  386. }
  387. // This is called by the worker window thread when it receives a terminate
  388. // message from the window object destructor to delete all the resources we
  389. // allocated during initialisation. By the time the worker thread exits all
  390. // processing will have been completed as the source filter disconnection
  391. // flushes the image pending sample, therefore the GdiFlush should succeed
  392. HRESULT CBaseWindow::UninitialiseWindow()
  393. {
  394. // Have we already cleaned up
  395. if (m_hwnd == NULL) {
  396. ASSERT(m_hdc == NULL);
  397. ASSERT(m_MemoryDC == NULL);
  398. return NOERROR;
  399. }
  400. // Release the window resources
  401. EXECUTE_ASSERT(GdiFlush());
  402. if (m_hdc)
  403. {
  404. EXECUTE_ASSERT(ReleaseDC(m_hwnd,m_hdc));
  405. m_hdc = NULL;
  406. }
  407. if (m_MemoryDC)
  408. {
  409. EXECUTE_ASSERT(DeleteDC(m_MemoryDC));
  410. m_MemoryDC = NULL;
  411. }
  412. // Reset the window variables
  413. m_hwnd = NULL;
  414. return NOERROR;
  415. }
  416. // This is called by the worker window thread after it has created the main
  417. // window and it wants to initialise the rest of the owner objects window
  418. // variables such as the device contexts. We execute this function with the
  419. // critical section still locked. Nothing in this function must generate any
  420. // SendMessage calls to the window because this is executing on the window
  421. // thread so the message will never be processed and we will deadlock
  422. HRESULT CBaseWindow::InitialiseWindow(HWND hwnd)
  423. {
  424. // Initialise the window variables
  425. ASSERT(IsWindow(hwnd));
  426. m_hwnd = hwnd;
  427. if (m_bDoGetDC)
  428. {
  429. EXECUTE_ASSERT(m_hdc = GetDC(hwnd));
  430. EXECUTE_ASSERT(m_MemoryDC = CreateCompatibleDC(m_hdc));
  431. EXECUTE_ASSERT(SetStretchBltMode(m_hdc,COLORONCOLOR));
  432. EXECUTE_ASSERT(SetStretchBltMode(m_MemoryDC,COLORONCOLOR));
  433. }
  434. return NOERROR;
  435. }
  436. HRESULT CBaseWindow::DoCreateWindow()
  437. {
  438. WNDCLASS wndclass; // Used to register classes
  439. BOOL bRegistered; // Is this class registered
  440. HWND hwnd; // Handle to our window
  441. bRegistered = GetClassInfo(m_hInstance, // Module instance
  442. m_pClassName, // Window class
  443. &wndclass); // Info structure
  444. // if the window is to be used for drawing puposes and we are getting a DC
  445. // for the entire lifetime of the window then changes the class style to do
  446. // say so. If we don't set this flag then the DC comes from the cache and is
  447. // really bad.
  448. if (m_bDoGetDC)
  449. {
  450. m_ClassStyles |= CS_OWNDC;
  451. }
  452. if (bRegistered == FALSE) {
  453. // Register the renderer window class
  454. wndclass.lpszClassName = m_pClassName;
  455. wndclass.style = m_ClassStyles;
  456. wndclass.lpfnWndProc = WndProc;
  457. wndclass.cbClsExtra = 0;
  458. wndclass.cbWndExtra = sizeof(CBaseWindow *);
  459. wndclass.hInstance = m_hInstance;
  460. wndclass.hIcon = NULL;
  461. wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);
  462. wndclass.hbrBackground = (HBRUSH) NULL;
  463. wndclass.lpszMenuName = NULL;
  464. RegisterClass(&wndclass);
  465. }
  466. // Create the frame window. Pass the pBaseWindow information in the
  467. // CreateStruct which allows our message handling loop to get hold of
  468. // the pBaseWindow pointer.
  469. CBaseWindow *pBaseWindow = this; // The owner window object
  470. hwnd = CreateWindowEx(m_WindowStylesEx, // Extended styles
  471. m_pClassName, // Registered name
  472. TEXT("ActiveMovie Window"), // Window title
  473. m_WindowStyles, // Window styles
  474. CW_USEDEFAULT, // Start x position
  475. CW_USEDEFAULT, // Start y position
  476. DEFWIDTH, // Window width
  477. DEFHEIGHT, // Window height
  478. NULL, // Parent handle
  479. NULL, // Menu handle
  480. m_hInstance, // Instance handle
  481. &pBaseWindow); // Creation data
  482. // If we failed signal an error to the object constructor (based on the
  483. // last Win32 error on this thread) then signal the constructor thread
  484. // to continue, release the mutex to let others have a go and exit
  485. if (hwnd == NULL) {
  486. DWORD Error = GetLastError();
  487. return AmHresultFromWin32(Error);
  488. }
  489. // Check the window LONG is the object who created us
  490. ASSERT(GetWindowLongPtr(hwnd, 0) == (LONG_PTR)this);
  491. // Initialise the window and then signal the constructor so that it can
  492. // continue and then finally unlock the object's critical section. The
  493. // window class is left registered even after we terminate the thread
  494. // as we don't know when the last window has been closed. So we allow
  495. // the operating system to free the class resources as appropriate
  496. InitialiseWindow(hwnd);
  497. DbgLog((LOG_TRACE, 2, TEXT("Created window class (%s) HWND(%8.8X)"),
  498. m_pClassName, hwnd));
  499. return S_OK;
  500. }
  501. // The base class provides some default handling and calls DefWindowProc
  502. LRESULT CBaseWindow::OnReceiveMessage(HWND hwnd, // Window handle
  503. UINT uMsg, // Message ID
  504. WPARAM wParam, // First parameter
  505. LPARAM lParam) // Other parameter
  506. {
  507. ASSERT(IsWindow(hwnd));
  508. if (PossiblyEatMessage(uMsg, wParam, lParam))
  509. return 0;
  510. // This is sent by the IVideoWindow SetWindowForeground method. If the
  511. // window is invisible we will show it and make it topmost without the
  512. // foreground focus. If the window is visible it will also be made the
  513. // topmost window without the foreground focus. If wParam is TRUE then
  514. // for both cases the window will be forced into the foreground focus
  515. if (uMsg == m_ShowStageMessage) {
  516. BOOL bVisible = IsWindowVisible(hwnd);
  517. SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
  518. SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW |
  519. (bVisible ? SWP_NOACTIVATE : 0));
  520. // Should we bring the window to the foreground
  521. if (wParam == TRUE) {
  522. SetForegroundWindow(hwnd);
  523. }
  524. return (LRESULT) 1;
  525. }
  526. // When we go fullscreen we have to add the WS_EX_TOPMOST style to the
  527. // video window so that it comes out above any task bar (this is more
  528. // relevant to WindowsNT than Windows95). However the SetWindowPos call
  529. // must be on the same thread as that which created the window. The
  530. // wParam parameter can be TRUE or FALSE to set and reset the topmost
  531. if (uMsg == m_ShowStageTop) {
  532. HWND HwndTop = (wParam == TRUE ? HWND_TOPMOST : HWND_NOTOPMOST);
  533. BOOL bVisible = IsWindowVisible(hwnd);
  534. SetWindowPos(hwnd, HwndTop, 0, 0, 0, 0,
  535. SWP_NOMOVE | SWP_NOSIZE |
  536. (wParam == TRUE ? SWP_SHOWWINDOW : 0) |
  537. (bVisible ? SWP_NOACTIVATE : 0));
  538. return (LRESULT) 1;
  539. }
  540. // New palette stuff
  541. if (uMsg == m_RealizePalette) {
  542. ASSERT(m_hwnd == hwnd);
  543. return OnPaletteChange(m_hwnd,WM_QUERYNEWPALETTE);
  544. }
  545. switch (uMsg) {
  546. // Repaint the window if the system colours change
  547. case WM_SYSCOLORCHANGE:
  548. InvalidateRect(hwnd,NULL,FALSE);
  549. return (LRESULT) 1;
  550. // Somebody has changed the palette
  551. case WM_PALETTECHANGED:
  552. OnPaletteChange((HWND)wParam,uMsg);
  553. return (LRESULT) 0;
  554. // We are about to receive the keyboard focus so we ask GDI to realise
  555. // our logical palette again and hopefully it will be fully installed
  556. // without any mapping having to be done during any picture rendering
  557. case WM_QUERYNEWPALETTE:
  558. ASSERT(m_hwnd == hwnd);
  559. return OnPaletteChange(m_hwnd,uMsg);
  560. // do NOT fwd WM_MOVE. the parameters are the location of the parent
  561. // window, NOT what the renderer should be looking at. But we need
  562. // to make sure the overlay is moved with the parent window, so we
  563. // do this.
  564. case WM_MOVE:
  565. if (IsWindowVisible(m_hwnd)) {
  566. PostMessage(m_hwnd,WM_PAINT,0,0);
  567. }
  568. break;
  569. // Store the width and height as useful base class members
  570. case WM_SIZE:
  571. OnSize(LOWORD(lParam), HIWORD(lParam));
  572. return (LRESULT) 0;
  573. // Intercept the WM_CLOSE messages to hide the window
  574. case WM_CLOSE:
  575. OnClose();
  576. return (LRESULT) 0;
  577. }
  578. return DefWindowProc(hwnd,uMsg,wParam,lParam);
  579. }
  580. // This handles the Windows palette change messages - if we do realise our
  581. // palette then we return TRUE otherwise we return FALSE. If our window is
  582. // foreground application then we should get first choice of colours in the
  583. // system palette entries. We get best performance when our logical palette
  584. // includes the standard VGA colours (at the beginning and end) otherwise
  585. // GDI may have to map from our palette to the device palette while drawing
  586. LRESULT CBaseWindow::OnPaletteChange(HWND hwnd,UINT Message)
  587. {
  588. // First check we are not changing the palette during closedown
  589. if (m_hwnd == NULL || hwnd == NULL) {
  590. return (LRESULT) 0;
  591. }
  592. ASSERT(!m_bRealizing);
  593. // Should we realise our palette again
  594. if ((Message == WM_QUERYNEWPALETTE || hwnd != m_hwnd)) {
  595. // It seems that even if we're invisible that we can get asked
  596. // to realize our palette and this can cause really ugly side-effects
  597. // Seems like there's another bug but this masks it a least for the
  598. // shutting down case.
  599. if (!IsWindowVisible(m_hwnd)) {
  600. DbgLog((LOG_TRACE, 1, TEXT("Realizing when invisible!")));
  601. return (LRESULT) 0;
  602. }
  603. // Avoid recursion with multiple graphs in the same app
  604. #ifdef DEBUG
  605. m_bRealizing = TRUE;
  606. #endif
  607. DoRealisePalette(Message != WM_QUERYNEWPALETTE);
  608. #ifdef DEBUG
  609. m_bRealizing = FALSE;
  610. #endif
  611. // Should we redraw the window with the new palette
  612. if (Message == WM_PALETTECHANGED) {
  613. InvalidateRect(m_hwnd,NULL,FALSE);
  614. }
  615. }
  616. return (LRESULT) 1;
  617. }
  618. // Determine if the window exists.
  619. bool CBaseWindow::WindowExists()
  620. {
  621. return !!IsWindow(m_hwnd);
  622. }
  623. // Return the default window rectangle
  624. RECT CBaseWindow::GetDefaultRect()
  625. {
  626. RECT DefaultRect = {0,0,DEFWIDTH,DEFHEIGHT};
  627. ASSERT(m_hwnd);
  628. // ASSERT(m_hdc);
  629. return DefaultRect;
  630. }
  631. // Return the current window width
  632. LONG CBaseWindow::GetWindowWidth()
  633. {
  634. ASSERT(m_hwnd);
  635. // ASSERT(m_hdc);
  636. return m_Width;
  637. }
  638. // Return the current window height
  639. LONG CBaseWindow::GetWindowHeight()
  640. {
  641. ASSERT(m_hwnd);
  642. // ASSERT(m_hdc);
  643. return m_Height;
  644. }
  645. // Return the window handle
  646. HWND CBaseWindow::GetWindowHWND()
  647. {
  648. ASSERT(m_hwnd);
  649. // ASSERT(m_hdc);
  650. return m_hwnd;
  651. }
  652. // Return the window drawing device context
  653. HDC CBaseWindow::GetWindowHDC()
  654. {
  655. ASSERT(m_hwnd);
  656. ASSERT(m_hdc);
  657. return m_hdc;
  658. }
  659. // Return the offscreen window drawing device context
  660. HDC CBaseWindow::GetMemoryHDC()
  661. {
  662. ASSERT(m_hwnd);
  663. ASSERT(m_MemoryDC);
  664. return m_MemoryDC;
  665. }
  666. #ifdef DEBUG
  667. HPALETTE CBaseWindow::GetPalette()
  668. {
  669. // The palette lock should always be held when accessing
  670. // m_hPalette.
  671. ASSERT(CritCheckIn(&m_PaletteLock));
  672. return m_hPalette;
  673. }
  674. #endif // DEBUG
  675. // This is available to clients who want to change the window visiblity. It's
  676. // little more than an indirection to the Win32 ShowWindow although these is
  677. // some benefit in going through here as this function may change sometime
  678. HRESULT CBaseWindow::DoShowWindow(LONG ShowCmd)
  679. {
  680. ShowWindow(m_hwnd,ShowCmd);
  681. return NOERROR;
  682. }
  683. // Generate a WM_PAINT message for the video window
  684. void CBaseWindow::PaintWindow(BOOL bErase)
  685. {
  686. InvalidateRect(m_hwnd,NULL,bErase);
  687. }
  688. // Allow an application to have us set the video window in the foreground. We
  689. // have this because it is difficult for one thread to do do this to a window
  690. // owned by another thread. Rather than expose the message we use to execute
  691. // the inter thread send message we provide the interface function. All we do
  692. // is to SendMessage to the video window renderer thread with a WM_SHOWSTAGE
  693. void CBaseWindow::DoSetWindowForeground(BOOL bFocus)
  694. {
  695. SendMessage(m_hwnd,m_ShowStageMessage,(WPARAM) bFocus,(LPARAM) 0);
  696. }
  697. // Constructor initialises the owning object pointer. Since we are a worker
  698. // class for the main window object we have relatively few state variables to
  699. // look after. We are given device context handles to use later on as well as
  700. // the source and destination rectangles (but reset them here just in case)
  701. CDrawImage::CDrawImage(CBaseWindow *pBaseWindow) :
  702. m_pBaseWindow(pBaseWindow),
  703. m_hdc(NULL),
  704. m_MemoryDC(NULL),
  705. m_bStretch(FALSE),
  706. m_pMediaType(NULL),
  707. m_bUsingImageAllocator(FALSE)
  708. {
  709. ASSERT(pBaseWindow);
  710. ResetPaletteVersion();
  711. SetRectEmpty(&m_TargetRect);
  712. SetRectEmpty(&m_SourceRect);
  713. m_perfidRenderTime = MSR_REGISTER(TEXT("Single Blt time"));
  714. }
  715. // Overlay the image time stamps on the picture. Access to this method is
  716. // serialised by the caller. We display the sample start and end times on
  717. // top of the video using TextOut on the device context we are handed. If
  718. // there isn't enough room in the window for the times we don't show them
  719. void CDrawImage::DisplaySampleTimes(IMediaSample *pSample)
  720. {
  721. #ifdef DEBUG
  722. //
  723. // Only allow the "annoying" time messages if the users has turned the
  724. // logging "way up"
  725. //
  726. BOOL bAccept = DbgCheckModuleLevel(LOG_TRACE, 5);
  727. if (bAccept == FALSE) {
  728. return;
  729. }
  730. #endif
  731. TCHAR szTimes[TIMELENGTH]; // Time stamp strings
  732. ASSERT(pSample); // Quick sanity check
  733. RECT ClientRect; // Client window size
  734. SIZE Size; // Size of text output
  735. // Get the time stamps and window size
  736. pSample->GetTime((REFERENCE_TIME*)&m_StartSample, (REFERENCE_TIME*)&m_EndSample);
  737. HWND hwnd = m_pBaseWindow->GetWindowHWND();
  738. EXECUTE_ASSERT(GetClientRect(hwnd,&ClientRect));
  739. // Format the sample time stamps
  740. wsprintf(szTimes,TEXT("%08d : %08d"),
  741. m_StartSample.Millisecs(),
  742. m_EndSample.Millisecs());
  743. ASSERT(lstrlen(szTimes) < TIMELENGTH);
  744. // Put the times in the middle at the bottom of the window
  745. GetTextExtentPoint32(m_hdc,szTimes,lstrlen(szTimes),&Size);
  746. INT XPos = ((ClientRect.right - ClientRect.left) - Size.cx) / 2;
  747. INT YPos = ((ClientRect.bottom - ClientRect.top) - Size.cy) * 4 / 5;
  748. // Check the window is big enough to have sample times displayed
  749. if ((XPos > 0) && (YPos > 0)) {
  750. TextOut(m_hdc,XPos,YPos,szTimes,lstrlen(szTimes));
  751. }
  752. }
  753. // This is called when the drawing code sees that the image has a down level
  754. // palette cookie. We simply call the SetDIBColorTable Windows API with the
  755. // palette that is found after the BITMAPINFOHEADER - we return no errors
  756. void CDrawImage::UpdateColourTable(HDC hdc,BITMAPINFOHEADER *pbmi)
  757. {
  758. ASSERT(pbmi->biClrUsed);
  759. RGBQUAD *pColourTable = (RGBQUAD *)(pbmi+1);
  760. // Set the new palette in the device context
  761. UINT uiReturn = SetDIBColorTable(hdc,(UINT) 0,
  762. pbmi->biClrUsed,
  763. pColourTable);
  764. // Should always succeed but check in debug builds
  765. ASSERT(uiReturn == pbmi->biClrUsed);
  766. }
  767. // No source rectangle scaling is done by the base class
  768. RECT CDrawImage::ScaleSourceRect(const RECT *pSource)
  769. {
  770. ASSERT(pSource);
  771. return *pSource;
  772. }
  773. // This is called when the funky output pin uses our allocator. The samples we
  774. // allocate are special because the memory is shared between us and GDI thus
  775. // removing one copy when we ask for the image to be rendered. The source type
  776. // information is in the main renderer m_mtIn field which is initialised when
  777. // the media type is agreed in SetMediaType, the media type may be changed on
  778. // the fly if, for example, the source filter needs to change the palette
  779. void CDrawImage::FastRender(IMediaSample *pMediaSample)
  780. {
  781. BITMAPINFOHEADER *pbmi; // Image format data
  782. DIBDATA *pDibData; // Stores DIB information
  783. BYTE *pImage; // Pointer to image data
  784. HBITMAP hOldBitmap; // Store the old bitmap
  785. CImageSample *pSample; // Pointer to C++ object
  786. ASSERT(m_pMediaType);
  787. // From the untyped source format block get the VIDEOINFO and subsequently
  788. // the BITMAPINFOHEADER structure. We can cast the IMediaSample interface
  789. // to a CImageSample object so we can retrieve it's DIBSECTION details
  790. pbmi = HEADER(m_pMediaType->Format());
  791. pSample = (CImageSample *) pMediaSample;
  792. pDibData = pSample->GetDIBData();
  793. hOldBitmap = (HBITMAP) SelectObject(m_MemoryDC,pDibData->hBitmap);
  794. // Get a pointer to the real image data
  795. HRESULT hr = pMediaSample->GetPointer(&pImage);
  796. if (FAILED(hr)) {
  797. return;
  798. }
  799. // Do we need to update the colour table, we increment our palette cookie
  800. // each time we get a dynamic format change. The sample palette cookie is
  801. // stored in the DIBDATA structure so we try to keep the fields in sync
  802. // By the time we get to draw the images the format change will be done
  803. // so all we do is ask the renderer for what it's palette version is
  804. if (pDibData->PaletteVersion < GetPaletteVersion()) {
  805. ASSERT(pbmi->biBitCount <= iPALETTE);
  806. UpdateColourTable(m_MemoryDC,pbmi);
  807. pDibData->PaletteVersion = GetPaletteVersion();
  808. }
  809. // This allows derived classes to change the source rectangle that we do
  810. // the drawing with. For example a renderer may ask a codec to stretch
  811. // the video from 320x240 to 640x480, in which case the source we see in
  812. // here will still be 320x240, although the source we want to draw with
  813. // should be scaled up to 640x480. The base class implementation of this
  814. // method does nothing but return the same rectangle as we are passed in
  815. RECT SourceRect = ScaleSourceRect(&m_SourceRect);
  816. // Is the window the same size as the video
  817. if (m_bStretch == FALSE) {
  818. // Put the image straight into the window
  819. BitBlt(
  820. (HDC) m_hdc, // Target device HDC
  821. m_TargetRect.left, // X sink position
  822. m_TargetRect.top, // Y sink position
  823. m_TargetRect.right - m_TargetRect.left, // Destination width
  824. m_TargetRect.bottom - m_TargetRect.top, // Destination height
  825. m_MemoryDC, // Source device context
  826. SourceRect.left, // X source position
  827. SourceRect.top, // Y source position
  828. SRCCOPY); // Simple copy
  829. } else {
  830. // Stretch the image when copying to the window
  831. StretchBlt(
  832. (HDC) m_hdc, // Target device HDC
  833. m_TargetRect.left, // X sink position
  834. m_TargetRect.top, // Y sink position
  835. m_TargetRect.right - m_TargetRect.left, // Destination width
  836. m_TargetRect.bottom - m_TargetRect.top, // Destination height
  837. m_MemoryDC, // Source device HDC
  838. SourceRect.left, // X source position
  839. SourceRect.top, // Y source position
  840. SourceRect.right - SourceRect.left, // Source width
  841. SourceRect.bottom - SourceRect.top, // Source height
  842. SRCCOPY); // Simple copy
  843. }
  844. // This displays the sample times over the top of the image. This used to
  845. // draw the times into the offscreen device context however that actually
  846. // writes the text into the image data buffer which may not be writable
  847. #ifdef DEBUG
  848. DisplaySampleTimes(pMediaSample);
  849. #endif
  850. // Put the old bitmap back into the device context so we don't leak
  851. SelectObject(m_MemoryDC,hOldBitmap);
  852. }
  853. // This is called when there is a sample ready to be drawn, unfortunately the
  854. // output pin was being rotten and didn't choose our super excellent shared
  855. // memory DIB allocator so we have to do this slow render using boring old GDI
  856. // SetDIBitsToDevice and StretchDIBits. The down side of using these GDI
  857. // functions is that the image data has to be copied across from our address
  858. // space into theirs before going to the screen (although in reality the cost
  859. // is small because all they do is to map the buffer into their address space)
  860. void CDrawImage::SlowRender(IMediaSample *pMediaSample)
  861. {
  862. // Get the BITMAPINFOHEADER for the connection
  863. ASSERT(m_pMediaType);
  864. BITMAPINFOHEADER *pbmi = HEADER(m_pMediaType->Format());
  865. BYTE *pImage;
  866. // Get the image data buffer
  867. HRESULT hr = pMediaSample->GetPointer(&pImage);
  868. if (FAILED(hr)) {
  869. return;
  870. }
  871. // This allows derived classes to change the source rectangle that we do
  872. // the drawing with. For example a renderer may ask a codec to stretch
  873. // the video from 320x240 to 640x480, in which case the source we see in
  874. // here will still be 320x240, although the source we want to draw with
  875. // should be scaled up to 640x480. The base class implementation of this
  876. // method does nothing but return the same rectangle as we are passed in
  877. RECT SourceRect = ScaleSourceRect(&m_SourceRect);
  878. LONG lAdjustedSourceTop = SourceRect.top;
  879. // if the origin of bitmap is bottom-left, adjust soruce_rect_top
  880. // to be the bottom-left corner instead of the top-left.
  881. if (pbmi->biHeight > 0) {
  882. lAdjustedSourceTop = pbmi->biHeight - SourceRect.bottom;
  883. }
  884. // Is the window the same size as the video
  885. if (m_bStretch == FALSE) {
  886. // Put the image straight into the window
  887. SetDIBitsToDevice(
  888. (HDC) m_hdc, // Target device HDC
  889. m_TargetRect.left, // X sink position
  890. m_TargetRect.top, // Y sink position
  891. m_TargetRect.right - m_TargetRect.left, // Destination width
  892. m_TargetRect.bottom - m_TargetRect.top, // Destination height
  893. SourceRect.left, // X source position
  894. lAdjustedSourceTop, // Adjusted Y source position
  895. (UINT) 0, // Start scan line
  896. pbmi->biHeight, // Scan lines present
  897. pImage, // Image data
  898. (BITMAPINFO *) pbmi, // DIB header
  899. DIB_RGB_COLORS); // Type of palette
  900. } else {
  901. // Stretch the image when copying to the window
  902. StretchDIBits(
  903. (HDC) m_hdc, // Target device HDC
  904. m_TargetRect.left, // X sink position
  905. m_TargetRect.top, // Y sink position
  906. m_TargetRect.right - m_TargetRect.left, // Destination width
  907. m_TargetRect.bottom - m_TargetRect.top, // Destination height
  908. SourceRect.left, // X source position
  909. lAdjustedSourceTop, // Adjusted Y source position
  910. SourceRect.right - SourceRect.left, // Source width
  911. SourceRect.bottom - SourceRect.top, // Source height
  912. pImage, // Image data
  913. (BITMAPINFO *) pbmi, // DIB header
  914. DIB_RGB_COLORS, // Type of palette
  915. SRCCOPY); // Simple image copy
  916. }
  917. // This shows the sample reference times over the top of the image which
  918. // looks a little flickery. I tried using GdiSetBatchLimit and GdiFlush to
  919. // control the screen updates but it doesn't quite work as expected and
  920. // only partially reduces the flicker. I also tried using a memory context
  921. // and combining the two in that before doing a final BitBlt operation to
  922. // the screen, unfortunately this has considerable performance penalties
  923. // and also means that this code is not executed when compiled retail
  924. #ifdef DEBUG
  925. DisplaySampleTimes(pMediaSample);
  926. #endif
  927. }
  928. // This is called with an IMediaSample interface on the image to be drawn. We
  929. // decide on the drawing mechanism based on who's allocator we are using. We
  930. // may be called when the window wants an image painted by WM_PAINT messages
  931. // We can't realise the palette here because we have the renderer lock, any
  932. // call to realise may cause an interthread send message to the window thread
  933. // which may in turn be waiting to get the renderer lock before servicing it
  934. BOOL CDrawImage::DrawImage(IMediaSample *pMediaSample)
  935. {
  936. ASSERT(m_hdc);
  937. ASSERT(m_MemoryDC);
  938. NotifyStartDraw();
  939. // If the output pin used our allocator then the samples passed are in
  940. // fact CVideoSample objects that contain CreateDIBSection data that we
  941. // use to do faster image rendering, they may optionally also contain a
  942. // DirectDraw surface pointer in which case we do not do the drawing
  943. if (m_bUsingImageAllocator == FALSE) {
  944. SlowRender(pMediaSample);
  945. EXECUTE_ASSERT(GdiFlush());
  946. NotifyEndDraw();
  947. return TRUE;
  948. }
  949. // This is a DIBSECTION buffer
  950. FastRender(pMediaSample);
  951. EXECUTE_ASSERT(GdiFlush());
  952. NotifyEndDraw();
  953. return TRUE;
  954. }
  955. BOOL CDrawImage::DrawVideoImageHere(
  956. HDC hdc,
  957. IMediaSample *pMediaSample,
  958. LPRECT lprcSrc,
  959. LPRECT lprcDst
  960. )
  961. {
  962. ASSERT(m_pMediaType);
  963. BITMAPINFOHEADER *pbmi = HEADER(m_pMediaType->Format());
  964. BYTE *pImage;
  965. // Get the image data buffer
  966. HRESULT hr = pMediaSample->GetPointer(&pImage);
  967. if (FAILED(hr)) {
  968. return FALSE;
  969. }
  970. RECT SourceRect;
  971. RECT TargetRect;
  972. if (lprcSrc) {
  973. SourceRect = *lprcSrc;
  974. }
  975. else SourceRect = ScaleSourceRect(&m_SourceRect);
  976. if (lprcDst) {
  977. TargetRect = *lprcDst;
  978. }
  979. else TargetRect = m_TargetRect;
  980. LONG lAdjustedSourceTop = SourceRect.top;
  981. // if the origin of bitmap is bottom-left, adjust soruce_rect_top
  982. // to be the bottom-left corner instead of the top-left.
  983. if (pbmi->biHeight > 0) {
  984. lAdjustedSourceTop = pbmi->biHeight - SourceRect.bottom;
  985. }
  986. // Stretch the image when copying to the DC
  987. BOOL bRet = (0 != StretchDIBits(hdc,
  988. TargetRect.left,
  989. TargetRect.top,
  990. TargetRect.right - TargetRect.left,
  991. TargetRect.bottom - TargetRect.top,
  992. SourceRect.left,
  993. lAdjustedSourceTop,
  994. SourceRect.right - SourceRect.left,
  995. SourceRect.bottom - SourceRect.top,
  996. pImage,
  997. (BITMAPINFO *)pbmi,
  998. DIB_RGB_COLORS,
  999. SRCCOPY));
  1000. return bRet;
  1001. }
  1002. // This is called by the owning window object after it has created the window
  1003. // and it's drawing contexts. We are constructed with the base window we'll
  1004. // be drawing into so when given the notification we retrive the device HDCs
  1005. // to draw with. We cannot call these in our constructor as they are virtual
  1006. void CDrawImage::SetDrawContext()
  1007. {
  1008. m_MemoryDC = m_pBaseWindow->GetMemoryHDC();
  1009. m_hdc = m_pBaseWindow->GetWindowHDC();
  1010. }
  1011. // This is called to set the target rectangle in the video window, it will be
  1012. // called whenever a WM_SIZE message is retrieved from the message queue. We
  1013. // simply store the rectangle and use it later when we do the drawing calls
  1014. void CDrawImage::SetTargetRect(RECT *pTargetRect)
  1015. {
  1016. ASSERT(pTargetRect);
  1017. m_TargetRect = *pTargetRect;
  1018. SetStretchMode();
  1019. }
  1020. // Return the current target rectangle
  1021. void CDrawImage::GetTargetRect(RECT *pTargetRect)
  1022. {
  1023. ASSERT(pTargetRect);
  1024. *pTargetRect = m_TargetRect;
  1025. }
  1026. // This is called when we want to change the section of the image to draw. We
  1027. // use this information in the drawing operation calls later on. We must also
  1028. // see if the source and destination rectangles have the same dimensions. If
  1029. // not we must stretch during the drawing rather than a direct pixel copy
  1030. void CDrawImage::SetSourceRect(RECT *pSourceRect)
  1031. {
  1032. ASSERT(pSourceRect);
  1033. m_SourceRect = *pSourceRect;
  1034. SetStretchMode();
  1035. }
  1036. // Return the current source rectangle
  1037. void CDrawImage::GetSourceRect(RECT *pSourceRect)
  1038. {
  1039. ASSERT(pSourceRect);
  1040. *pSourceRect = m_SourceRect;
  1041. }
  1042. // This is called when either the source or destination rectanges change so we
  1043. // can update the stretch flag. If the rectangles don't match we stretch the
  1044. // video during the drawing otherwise we call the fast pixel copy functions
  1045. // NOTE the source and/or the destination rectangle may be completely empty
  1046. void CDrawImage::SetStretchMode()
  1047. {
  1048. // Calculate the overall rectangle dimensions
  1049. LONG SourceWidth = m_SourceRect.right - m_SourceRect.left;
  1050. LONG SinkWidth = m_TargetRect.right - m_TargetRect.left;
  1051. LONG SourceHeight = m_SourceRect.bottom - m_SourceRect.top;
  1052. LONG SinkHeight = m_TargetRect.bottom - m_TargetRect.top;
  1053. m_bStretch = TRUE;
  1054. if (SourceWidth == SinkWidth) {
  1055. if (SourceHeight == SinkHeight) {
  1056. m_bStretch = FALSE;
  1057. }
  1058. }
  1059. }
  1060. // Tell us whose allocator we are using. This should be called with TRUE if
  1061. // the filter agrees to use an allocator based around the CImageAllocator
  1062. // SDK base class - whose image buffers are made through CreateDIBSection.
  1063. // Otherwise this should be called with FALSE and we will draw the images
  1064. // using SetDIBitsToDevice and StretchDIBitsToDevice. None of these calls
  1065. // can handle buffers which have non zero strides (like DirectDraw uses)
  1066. void CDrawImage::NotifyAllocator(BOOL bUsingImageAllocator)
  1067. {
  1068. m_bUsingImageAllocator = bUsingImageAllocator;
  1069. }
  1070. // Are we using the image DIBSECTION allocator
  1071. BOOL CDrawImage::UsingImageAllocator()
  1072. {
  1073. return m_bUsingImageAllocator;
  1074. }
  1075. // We need the media type of the connection so that we can get the BITMAPINFO
  1076. // from it. We use that in the calls to draw the image such as StretchDIBits
  1077. // and also when updating the colour table held in shared memory DIBSECTIONs
  1078. void CDrawImage::NotifyMediaType(CMediaType *pMediaType)
  1079. {
  1080. m_pMediaType = pMediaType;
  1081. }
  1082. // We store in this object a cookie maintaining the current palette version.
  1083. // Each time a palettised format is changed we increment this value so that
  1084. // when we come to draw the images we look at the colour table value they
  1085. // have and if less than the current we know to update it. This version is
  1086. // only needed and indeed used when working with shared memory DIBSECTIONs
  1087. LONG CDrawImage::GetPaletteVersion()
  1088. {
  1089. return m_PaletteVersion;
  1090. }
  1091. // Resets the current palette version number
  1092. void CDrawImage::ResetPaletteVersion()
  1093. {
  1094. m_PaletteVersion = PALETTE_VERSION;
  1095. }
  1096. // Increment the current palette version
  1097. void CDrawImage::IncrementPaletteVersion()
  1098. {
  1099. m_PaletteVersion++;
  1100. }
  1101. // Constructor must initialise the base allocator. Each sample we create has a
  1102. // palette version cookie on board. When the source filter changes the palette
  1103. // during streaming the window object increments an internal cookie counter it
  1104. // keeps as well. When it comes to render the samples it looks at the cookie
  1105. // values and if they don't match then it knows to update the sample's colour
  1106. // table. However we always create samples with a cookie of PALETTE_VERSION
  1107. // If there have been multiple format changes and we disconnect and reconnect
  1108. // thereby causing the samples to be reallocated we will create them with a
  1109. // cookie much lower than the current version, this isn't a problem since it
  1110. // will be seen by the window object and the versions will then be updated
  1111. CImageAllocator::CImageAllocator(CBaseFilter *pFilter,
  1112. TCHAR *pName,
  1113. HRESULT *phr) :
  1114. CBaseAllocator(pName,NULL,phr,TRUE,TRUE),
  1115. m_pFilter(pFilter)
  1116. {
  1117. ASSERT(phr);
  1118. ASSERT(pFilter);
  1119. }
  1120. // Check our DIB buffers have been released
  1121. #ifdef DEBUG
  1122. CImageAllocator::~CImageAllocator()
  1123. {
  1124. ASSERT(m_bCommitted == FALSE);
  1125. }
  1126. #endif
  1127. // Called from destructor and also from base class to free resources. We work
  1128. // our way through the list of media samples deleting the DIBSECTION created
  1129. // for each. All samples should be back in our list so there is no chance a
  1130. // filter is still using one to write on the display or hold on a pending list
  1131. void CImageAllocator::Free()
  1132. {
  1133. ASSERT(m_lAllocated == m_lFree.GetCount());
  1134. EXECUTE_ASSERT(GdiFlush());
  1135. CImageSample *pSample;
  1136. DIBDATA *pDibData;
  1137. while (m_lFree.GetCount() != 0) {
  1138. pSample = (CImageSample *) m_lFree.RemoveHead();
  1139. pDibData = pSample->GetDIBData();
  1140. EXECUTE_ASSERT(DeleteObject(pDibData->hBitmap));
  1141. EXECUTE_ASSERT(CloseHandle(pDibData->hMapping));
  1142. delete pSample;
  1143. }
  1144. m_lAllocated = 0;
  1145. }
  1146. // Prepare the allocator by checking all the input parameters
  1147. STDMETHODIMP CImageAllocator::CheckSizes(ALLOCATOR_PROPERTIES *pRequest)
  1148. {
  1149. // Check we have a valid connection
  1150. if (m_pMediaType == NULL) {
  1151. return VFW_E_NOT_CONNECTED;
  1152. }
  1153. // NOTE We always create a DIB section with the source format type which
  1154. // may contain a source palette. When we do the BitBlt drawing operation
  1155. // the target display device may contain a different palette (we may not
  1156. // have the focus) in which case GDI will do after the palette mapping
  1157. VIDEOINFOHEADER *pVideoInfo = (VIDEOINFOHEADER *) m_pMediaType->Format();
  1158. // When we call CreateDIBSection it implicitly maps only enough memory
  1159. // for the image as defined by thee BITMAPINFOHEADER. If the user asks
  1160. // for an image smaller than this then we reject the call, if they ask
  1161. // for an image larger than this then we return what they can have
  1162. if ((DWORD) pRequest->cbBuffer < pVideoInfo->bmiHeader.biSizeImage) {
  1163. return E_INVALIDARG;
  1164. }
  1165. // Reject buffer prefixes
  1166. if (pRequest->cbPrefix > 0) {
  1167. return E_INVALIDARG;
  1168. }
  1169. pRequest->cbBuffer = pVideoInfo->bmiHeader.biSizeImage;
  1170. return NOERROR;
  1171. }
  1172. // Agree the number of media sample buffers and their sizes. The base class
  1173. // this allocator is derived from allows samples to be aligned only on byte
  1174. // boundaries NOTE the buffers are not allocated until the Commit call
  1175. STDMETHODIMP CImageAllocator::SetProperties(
  1176. ALLOCATOR_PROPERTIES * pRequest,
  1177. ALLOCATOR_PROPERTIES * pActual)
  1178. {
  1179. ALLOCATOR_PROPERTIES Adjusted = *pRequest;
  1180. // Check the parameters fit with the current connection
  1181. HRESULT hr = CheckSizes(&Adjusted);
  1182. if (FAILED(hr)) {
  1183. return hr;
  1184. }
  1185. return CBaseAllocator::SetProperties(&Adjusted, pActual);
  1186. }
  1187. // Commit the memory by allocating the agreed number of media samples. For
  1188. // each sample we are committed to creating we have a CImageSample object
  1189. // that we use to manage it's resources. This is initialised with a DIBDATA
  1190. // structure that contains amongst other things the GDI DIBSECTION handle
  1191. // We will access the renderer media type during this so we must have locked
  1192. // (to prevent the format changing for example). The class overrides Commit
  1193. // and Decommit to do this locking (base class Commit in turn calls Alloc)
  1194. HRESULT CImageAllocator::Alloc(void)
  1195. {
  1196. ASSERT(m_pMediaType);
  1197. CImageSample *pSample;
  1198. DIBDATA DibData;
  1199. // Check the base allocator says it's ok to continue
  1200. HRESULT hr = CBaseAllocator::Alloc();
  1201. if (FAILED(hr)) {
  1202. return hr;
  1203. }
  1204. // We create a new memory mapped object although we don't map it into our
  1205. // address space because GDI does that in CreateDIBSection. It is possible
  1206. // that we run out of resources before creating all the samples in which
  1207. // case the available sample list is left with those already created
  1208. ASSERT(m_lAllocated == 0);
  1209. while (m_lAllocated < m_lCount) {
  1210. // Create and initialise a shared memory GDI buffer
  1211. HRESULT hr = CreateDIB(m_lSize,DibData);
  1212. if (FAILED(hr)) {
  1213. return hr;
  1214. }
  1215. // Create the sample object and pass it the DIBDATA
  1216. pSample = CreateImageSample(DibData.pBase,m_lSize);
  1217. if (pSample == NULL) {
  1218. EXECUTE_ASSERT(DeleteObject(DibData.hBitmap));
  1219. EXECUTE_ASSERT(CloseHandle(DibData.hMapping));
  1220. return E_OUTOFMEMORY;
  1221. }
  1222. // Add the completed sample to the available list
  1223. pSample->SetDIBData(&DibData);
  1224. m_lFree.Add(pSample);
  1225. m_lAllocated++;
  1226. }
  1227. return NOERROR;
  1228. }
  1229. // We have a virtual method that allocates the samples so that a derived class
  1230. // may override it and allocate more specialised sample objects. So long as it
  1231. // derives its samples from CImageSample then all this code will still work ok
  1232. CImageSample *CImageAllocator::CreateImageSample(LPBYTE pData,LONG Length)
  1233. {
  1234. HRESULT hr = NOERROR;
  1235. CImageSample *pSample;
  1236. // Allocate the new sample and check the return codes
  1237. pSample = new CImageSample((CBaseAllocator *) this, // Base class
  1238. NAME("Video sample"), // DEBUG name
  1239. (HRESULT *) &hr, // Return code
  1240. (LPBYTE) pData, // DIB address
  1241. (LONG) Length); // Size of DIB
  1242. if (pSample == NULL || FAILED(hr)) {
  1243. delete pSample;
  1244. return NULL;
  1245. }
  1246. return pSample;
  1247. }
  1248. // This function allocates a shared memory block for use by the source filter
  1249. // generating DIBs for us to render. The memory block is created in shared
  1250. // memory so that GDI doesn't have to copy the memory when we do a BitBlt
  1251. HRESULT CImageAllocator::CreateDIB(LONG InSize,DIBDATA &DibData)
  1252. {
  1253. BITMAPINFO *pbmi; // Format information for pin
  1254. BYTE *pBase; // Pointer to the actual image
  1255. HANDLE hMapping; // Handle to mapped object
  1256. HBITMAP hBitmap; // DIB section bitmap handle
  1257. // Create a file mapping object and map into our address space
  1258. hMapping = CreateFileMapping(hMEMORY, // Use system page file
  1259. NULL, // No security attributes
  1260. PAGE_READWRITE, // Full access to memory
  1261. (DWORD) 0, // Less than 4Gb in size
  1262. InSize, // Size of buffer
  1263. NULL); // No name to section
  1264. if (hMapping == NULL) {
  1265. DWORD Error = GetLastError();
  1266. return MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, Error);
  1267. }
  1268. // NOTE We always create a DIB section with the source format type which
  1269. // may contain a source palette. When we do the BitBlt drawing operation
  1270. // the target display device may contain a different palette (we may not
  1271. // have the focus) in which case GDI will do after the palette mapping
  1272. pbmi = (BITMAPINFO *) HEADER(m_pMediaType->Format());
  1273. if (m_pMediaType == NULL) {
  1274. DbgBreak("Invalid media type");
  1275. }
  1276. hBitmap = CreateDIBSection((HDC) NULL, // NO device context
  1277. pbmi, // Format information
  1278. DIB_RGB_COLORS, // Use the palette
  1279. (VOID **) &pBase, // Pointer to image data
  1280. hMapping, // Mapped memory handle
  1281. (DWORD) 0); // Offset into memory
  1282. if (hBitmap == NULL || pBase == NULL) {
  1283. EXECUTE_ASSERT(CloseHandle(hMapping));
  1284. DWORD Error = GetLastError();
  1285. return MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, Error);
  1286. }
  1287. // Initialise the DIB information structure
  1288. DibData.hBitmap = hBitmap;
  1289. DibData.hMapping = hMapping;
  1290. DibData.pBase = pBase;
  1291. DibData.PaletteVersion = PALETTE_VERSION;
  1292. GetObject(hBitmap,sizeof(DIBSECTION),(VOID *)&DibData.DibSection);
  1293. return NOERROR;
  1294. }
  1295. // We use the media type during the DIBSECTION creation
  1296. void CImageAllocator::NotifyMediaType(CMediaType *pMediaType)
  1297. {
  1298. m_pMediaType = pMediaType;
  1299. }
  1300. // Overriden to increment the owning object's reference count
  1301. STDMETHODIMP_(ULONG) CImageAllocator::NonDelegatingAddRef()
  1302. {
  1303. return m_pFilter->AddRef();
  1304. }
  1305. // Overriden to decrement the owning object's reference count
  1306. STDMETHODIMP_(ULONG) CImageAllocator::NonDelegatingRelease()
  1307. {
  1308. return m_pFilter->Release();
  1309. }
  1310. // If you derive a class from CMediaSample that has to transport specialised
  1311. // member variables and entry points then there are three alternate solutions
  1312. // The first is to create a memory buffer larger than actually required by the
  1313. // sample and store your information either at the beginning of it or at the
  1314. // end, the former being moderately safer allowing for misbehaving transform
  1315. // filters. You then adjust the buffer address when you create the base media
  1316. // sample. This has the disadvantage of breaking up the memory allocated to
  1317. // the samples into separate blocks. The second solution is to implement a
  1318. // class derived from CMediaSample and support additional interface(s) that
  1319. // convey your private data. This means defining a custom interface. The final
  1320. // alternative is to create a class that inherits from CMediaSample and adds
  1321. // the private data structures, when you get an IMediaSample in your Receive()
  1322. // call check to see if your allocator is being used, and if it is then cast
  1323. // the IMediaSample into one of your objects. Additional checks can be made
  1324. // to ensure the sample's this pointer is known to be one of your own objects
  1325. CImageSample::CImageSample(CBaseAllocator *pAllocator,
  1326. TCHAR *pName,
  1327. HRESULT *phr,
  1328. LPBYTE pBuffer,
  1329. LONG length) :
  1330. CMediaSample(pName,pAllocator,phr,pBuffer,length),
  1331. m_bInit(FALSE)
  1332. {
  1333. ASSERT(pAllocator);
  1334. ASSERT(pBuffer);
  1335. }
  1336. // Set the shared memory DIB information
  1337. void CImageSample::SetDIBData(DIBDATA *pDibData)
  1338. {
  1339. ASSERT(pDibData);
  1340. m_DibData = *pDibData;
  1341. m_bInit = TRUE;
  1342. }
  1343. // Retrieve the shared memory DIB data
  1344. DIBDATA *CImageSample::GetDIBData()
  1345. {
  1346. ASSERT(m_bInit == TRUE);
  1347. return &m_DibData;
  1348. }
  1349. // This class handles the creation of a palette. It is fairly specialist and
  1350. // is intended to simplify palette management for video renderer filters. It
  1351. // is for this reason that the constructor requires three other objects with
  1352. // which it interacts, namely a base media filter, a base window and a base
  1353. // drawing object although the base window or the draw object may be NULL to
  1354. // ignore that part of us. We try not to create and install palettes unless
  1355. // absolutely necessary as they typically require WM_PALETTECHANGED messages
  1356. // to be sent to every window thread in the system which is very expensive
  1357. CImagePalette::CImagePalette(CBaseFilter *pBaseFilter,
  1358. CBaseWindow *pBaseWindow,
  1359. CDrawImage *pDrawImage) :
  1360. m_pBaseWindow(pBaseWindow),
  1361. m_pFilter(pBaseFilter),
  1362. m_pDrawImage(pDrawImage),
  1363. m_hPalette(NULL)
  1364. {
  1365. ASSERT(m_pFilter);
  1366. }
  1367. // Destructor
  1368. #ifdef DEBUG
  1369. CImagePalette::~CImagePalette()
  1370. {
  1371. ASSERT(m_hPalette == NULL);
  1372. }
  1373. #endif
  1374. // We allow dynamic format changes of the palette but rather than change the
  1375. // palette every time we call this to work out whether an update is required.
  1376. // If the original type didn't use a palette and the new one does (or vica
  1377. // versa) then we return TRUE. If neither formats use a palette we'll return
  1378. // FALSE. If both formats use a palette we compare their colours and return
  1379. // FALSE if they match. This therefore short circuits palette creation unless
  1380. // absolutely necessary since installing palettes is an expensive operation
  1381. BOOL CImagePalette::ShouldUpdate(const VIDEOINFOHEADER *pNewInfo,
  1382. const VIDEOINFOHEADER *pOldInfo)
  1383. {
  1384. // We may not have a current format yet
  1385. if (pOldInfo == NULL) {
  1386. return TRUE;
  1387. }
  1388. // Do both formats not require a palette
  1389. if (ContainsPalette(pNewInfo) == FALSE) {
  1390. if (ContainsPalette(pOldInfo) == FALSE) {
  1391. return FALSE;
  1392. }
  1393. }
  1394. // Compare the colours to see if they match
  1395. DWORD VideoEntries = pNewInfo->bmiHeader.biClrUsed;
  1396. if (ContainsPalette(pNewInfo) == TRUE)
  1397. if (ContainsPalette(pOldInfo) == TRUE)
  1398. if (pOldInfo->bmiHeader.biClrUsed == VideoEntries)
  1399. if (pOldInfo->bmiHeader.biClrUsed > 0)
  1400. if (memcmp((PVOID) GetBitmapPalette(pNewInfo),
  1401. (PVOID) GetBitmapPalette(pOldInfo),
  1402. VideoEntries * sizeof(RGBQUAD)) == 0) {
  1403. return FALSE;
  1404. }
  1405. return TRUE;
  1406. }
  1407. // This is normally called when the input pin type is set to install a palette
  1408. // We will typically be called from two different places. The first is when we
  1409. // have negotiated a palettised media type after connection, the other is when
  1410. // we receive a new type during processing with an updated palette in which
  1411. // case we must remove and release the resources held by the current palette
  1412. // We can be passed an optional device name if we wish to prepare a palette
  1413. // for a specific monitor on a multi monitor system
  1414. HRESULT CImagePalette::PreparePalette(const CMediaType *pmtNew,
  1415. const CMediaType *pmtOld,
  1416. LPSTR szDevice)
  1417. {
  1418. const VIDEOINFOHEADER *pNewInfo = (VIDEOINFOHEADER *) pmtNew->Format();
  1419. const VIDEOINFOHEADER *pOldInfo = (VIDEOINFOHEADER *) pmtOld->Format();
  1420. ASSERT(pNewInfo);
  1421. // This is an performance optimisation, when we get a media type we check
  1422. // to see if the format requires a palette change. If either we need one
  1423. // when previously we didn't or vica versa then this returns TRUE, if we
  1424. // previously needed a palette and we do now it compares their colours
  1425. if (ShouldUpdate(pNewInfo,pOldInfo) == FALSE) {
  1426. NOTE("No update needed");
  1427. return S_FALSE;
  1428. }
  1429. // We must notify the filter graph that the application may have changed
  1430. // the palette although in practice we don't bother checking to see if it
  1431. // is really different. If it tries to get the palette either the window
  1432. // or renderer lock will ensure it doesn't get in until we are finished
  1433. RemovePalette();
  1434. m_pFilter->NotifyEvent(EC_PALETTE_CHANGED,0,0);
  1435. // Do we need a palette for the new format
  1436. if (ContainsPalette(pNewInfo) == FALSE) {
  1437. NOTE("New has no palette");
  1438. return S_FALSE;
  1439. }
  1440. if (m_pBaseWindow) {
  1441. m_pBaseWindow->LockPaletteLock();
  1442. }
  1443. // If we're changing the palette on the fly then we increment our palette
  1444. // cookie which is compared against the cookie also stored in all of our
  1445. // DIBSECTION media samples. If they don't match when we come to draw it
  1446. // then we know the sample is out of date and we'll update it's palette
  1447. NOTE("Making new colour palette");
  1448. m_hPalette = MakePalette(pNewInfo, szDevice);
  1449. ASSERT(m_hPalette != NULL);
  1450. if (m_pBaseWindow) {
  1451. m_pBaseWindow->UnlockPaletteLock();
  1452. }
  1453. // The window in which the new palette is to be realised may be a NULL
  1454. // pointer to signal that no window is in use, if so we don't call it
  1455. // Some filters just want to use this object to create/manage palettes
  1456. if (m_pBaseWindow) m_pBaseWindow->SetPalette(m_hPalette);
  1457. // This is the only time where we need access to the draw object to say
  1458. // to it that a new palette will be arriving on a sample real soon. The
  1459. // constructor may take a NULL pointer in which case we don't call this
  1460. if (m_pDrawImage) m_pDrawImage->IncrementPaletteVersion();
  1461. return NOERROR;
  1462. }
  1463. // Helper function to copy a palette out of any kind of VIDEOINFO (ie it may
  1464. // be YUV or true colour) into a palettised VIDEOINFO. We use this changing
  1465. // palettes on DirectDraw samples as a source filter can attach a palette to
  1466. // any buffer (eg YUV) and hand it back. We make a new palette out of that
  1467. // format and then copy the palette colours into the current connection type
  1468. HRESULT CImagePalette::CopyPalette(const CMediaType *pSrc,CMediaType *pDest)
  1469. {
  1470. // Reset the destination palette before starting
  1471. VIDEOINFOHEADER *pDestInfo = (VIDEOINFOHEADER *) pDest->Format();
  1472. pDestInfo->bmiHeader.biClrUsed = 0;
  1473. pDestInfo->bmiHeader.biClrImportant = 0;
  1474. // Does the destination have a palette
  1475. if (PALETTISED(pDestInfo) == FALSE) {
  1476. NOTE("No destination palette");
  1477. return S_FALSE;
  1478. }
  1479. // Does the source contain a palette
  1480. const VIDEOINFOHEADER *pSrcInfo = (VIDEOINFOHEADER *) pSrc->Format();
  1481. if (ContainsPalette(pSrcInfo) == FALSE) {
  1482. NOTE("No source palette");
  1483. return S_FALSE;
  1484. }
  1485. // The number of colours may be zero filled
  1486. DWORD PaletteEntries = pSrcInfo->bmiHeader.biClrUsed;
  1487. if (PaletteEntries == 0) {
  1488. DWORD Maximum = (1 << pSrcInfo->bmiHeader.biBitCount);
  1489. NOTE1("Setting maximum colours (%d)",Maximum);
  1490. PaletteEntries = Maximum;
  1491. }
  1492. // Make sure the destination has enough room for the palette
  1493. ASSERT(pSrcInfo->bmiHeader.biClrUsed <= iPALETTE_COLORS);
  1494. ASSERT(pSrcInfo->bmiHeader.biClrImportant <= PaletteEntries);
  1495. ASSERT(COLORS(pDestInfo) == GetBitmapPalette(pDestInfo));
  1496. pDestInfo->bmiHeader.biClrUsed = PaletteEntries;
  1497. pDestInfo->bmiHeader.biClrImportant = pSrcInfo->bmiHeader.biClrImportant;
  1498. ULONG BitmapSize = GetBitmapFormatSize(HEADER(pSrcInfo));
  1499. if (pDest->FormatLength() < BitmapSize) {
  1500. NOTE("Reallocating destination");
  1501. pDest->ReallocFormatBuffer(BitmapSize);
  1502. }
  1503. // Now copy the palette colours across
  1504. CopyMemory((PVOID) COLORS(pDestInfo),
  1505. (PVOID) GetBitmapPalette(pSrcInfo),
  1506. PaletteEntries * sizeof(RGBQUAD));
  1507. return NOERROR;
  1508. }
  1509. // This is normally called when the palette is changed (typically during a
  1510. // dynamic format change) to remove any palette we previously installed. We
  1511. // replace it (if necessary) in the video window with a standard VGA palette
  1512. // that should always be available even if this is a true colour display
  1513. HRESULT CImagePalette::RemovePalette()
  1514. {
  1515. if (m_pBaseWindow) {
  1516. m_pBaseWindow->LockPaletteLock();
  1517. }
  1518. // Do we have a palette to remove
  1519. if (m_hPalette != NULL) {
  1520. if (m_pBaseWindow) {
  1521. // Make sure that the window's palette handle matches
  1522. // our palette handle.
  1523. ASSERT(m_hPalette == m_pBaseWindow->GetPalette());
  1524. m_pBaseWindow->UnsetPalette();
  1525. }
  1526. EXECUTE_ASSERT(DeleteObject(m_hPalette));
  1527. m_hPalette = NULL;
  1528. }
  1529. if (m_pBaseWindow) {
  1530. m_pBaseWindow->UnlockPaletteLock();
  1531. }
  1532. return NOERROR;
  1533. }
  1534. // Called to create a palette for the object, the data structure used by GDI
  1535. // to describe a palette is a LOGPALETTE, this includes a variable number of
  1536. // PALETTEENTRY fields which are the colours, we have to convert the RGBQUAD
  1537. // colour fields we are handed in a BITMAPINFO from the media type into these
  1538. // This handles extraction of palettes from true colour and YUV media formats
  1539. // We can be passed an optional device name if we wish to prepare a palette
  1540. // for a specific monitor on a multi monitor system
  1541. HPALETTE CImagePalette::MakePalette(const VIDEOINFOHEADER *pVideoInfo, LPSTR szDevice)
  1542. {
  1543. ASSERT(ContainsPalette(pVideoInfo) == TRUE);
  1544. ASSERT(pVideoInfo->bmiHeader.biClrUsed <= iPALETTE_COLORS);
  1545. BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
  1546. const RGBQUAD *pColours; // Pointer to the palette
  1547. LOGPALETTE *lp; // Used to create a palette
  1548. HPALETTE hPalette; // Logical palette object
  1549. lp = (LOGPALETTE *) new BYTE[sizeof(LOGPALETTE) + SIZE_PALETTE];
  1550. if (lp == NULL) {
  1551. return NULL;
  1552. }
  1553. // Unfortunately for some hare brained reason a GDI palette entry (a
  1554. // PALETTEENTRY structure) is different to a palette entry from a DIB
  1555. // format (a RGBQUAD structure) so we have to do the field conversion
  1556. // The VIDEOINFO containing the palette may be a true colour type so
  1557. // we use GetBitmapPalette to skip over any bit fields if they exist
  1558. lp->palVersion = PALVERSION;
  1559. lp->palNumEntries = (USHORT) pHeader->biClrUsed;
  1560. if (lp->palNumEntries == 0) lp->palNumEntries = (1 << pHeader->biBitCount);
  1561. pColours = GetBitmapPalette(pVideoInfo);
  1562. for (DWORD dwCount = 0;dwCount < lp->palNumEntries;dwCount++) {
  1563. lp->palPalEntry[dwCount].peRed = pColours[dwCount].rgbRed;
  1564. lp->palPalEntry[dwCount].peGreen = pColours[dwCount].rgbGreen;
  1565. lp->palPalEntry[dwCount].peBlue = pColours[dwCount].rgbBlue;
  1566. lp->palPalEntry[dwCount].peFlags = 0;
  1567. }
  1568. MakeIdentityPalette(lp->palPalEntry, lp->palNumEntries, szDevice);
  1569. // Create a logical palette
  1570. hPalette = CreatePalette(lp);
  1571. ASSERT(hPalette != NULL);
  1572. delete[] lp;
  1573. return hPalette;
  1574. }
  1575. // GDI does a fair job of compressing the palette entries you give it, so for
  1576. // example if you have five entries with an RGB colour (0,0,0) it will remove
  1577. // all but one of them. When you subsequently draw an image it will map from
  1578. // your logical palette to the compressed device palette. This function looks
  1579. // to see if it is trying to be an identity palette and if so sets the flags
  1580. // field in the PALETTEENTRYs so they remain expanded to boost performance
  1581. // We can be passed an optional device name if we wish to prepare a palette
  1582. // for a specific monitor on a multi monitor system
  1583. HRESULT CImagePalette::MakeIdentityPalette(PALETTEENTRY *pEntry,INT iColours, LPSTR szDevice)
  1584. {
  1585. PALETTEENTRY SystemEntries[10]; // System palette entries
  1586. BOOL bIdentityPalette = TRUE; // Is an identity palette
  1587. ASSERT(iColours <= iPALETTE_COLORS); // Should have a palette
  1588. const int PalLoCount = 10; // First ten reserved colours
  1589. const int PalHiStart = 246; // Last VGA palette entries
  1590. // Does this have the full colour range
  1591. if (iColours < 10) {
  1592. return S_FALSE;
  1593. }
  1594. // Apparently some displays have odd numbers of system colours
  1595. // Get a DC on the right monitor - it's ugly, but this is the way you have
  1596. // to do it
  1597. HDC hdc;
  1598. if (szDevice == NULL || lstrcmpiA(szDevice, "DISPLAY") == 0)
  1599. hdc = CreateDCA("DISPLAY", NULL, NULL, NULL);
  1600. else
  1601. hdc = CreateDCA(NULL, szDevice, NULL, NULL);
  1602. if (NULL == hdc) {
  1603. return E_OUTOFMEMORY;
  1604. }
  1605. INT Reserved = GetDeviceCaps(hdc,NUMRESERVED);
  1606. if (Reserved != 20) {
  1607. DeleteDC(hdc);
  1608. return S_FALSE;
  1609. }
  1610. // Compare our palette against the first ten system entries. The reason I
  1611. // don't do a memory compare between our two arrays of colours is because
  1612. // I am not sure what will be in the flags fields for the system entries
  1613. UINT Result = GetSystemPaletteEntries(hdc,0,PalLoCount,SystemEntries);
  1614. for (UINT Count = 0;Count < Result;Count++) {
  1615. if (SystemEntries[Count].peRed != pEntry[Count].peRed ||
  1616. SystemEntries[Count].peGreen != pEntry[Count].peGreen ||
  1617. SystemEntries[Count].peBlue != pEntry[Count].peBlue) {
  1618. bIdentityPalette = FALSE;
  1619. }
  1620. }
  1621. // And likewise compare against the last ten entries
  1622. Result = GetSystemPaletteEntries(hdc,PalHiStart,PalLoCount,SystemEntries);
  1623. for (Count = 0;Count < Result;Count++) {
  1624. if (INT(Count) + PalHiStart < iColours) {
  1625. if (SystemEntries[Count].peRed != pEntry[PalHiStart + Count].peRed ||
  1626. SystemEntries[Count].peGreen != pEntry[PalHiStart + Count].peGreen ||
  1627. SystemEntries[Count].peBlue != pEntry[PalHiStart + Count].peBlue) {
  1628. bIdentityPalette = FALSE;
  1629. }
  1630. }
  1631. }
  1632. // If not an identity palette then return S_FALSE
  1633. DeleteDC(hdc);
  1634. if (bIdentityPalette == FALSE) {
  1635. return S_FALSE;
  1636. }
  1637. // Set the non VGA entries so that GDI doesn't map them
  1638. for (Count = PalLoCount;INT(Count) < min(PalHiStart,iColours);Count++) {
  1639. pEntry[Count].peFlags = PC_NOCOLLAPSE;
  1640. }
  1641. return NOERROR;
  1642. }
  1643. // Constructor initialises the VIDEOINFO we keep storing the current display
  1644. // format. The format can be changed at any time, to reset the format held
  1645. // by us call the RefreshDisplayType directly (it's a public method). Since
  1646. // more than one thread will typically call us (ie window threads resetting
  1647. // the type and source threads in the type checking methods) we have a lock
  1648. CImageDisplay::CImageDisplay()
  1649. {
  1650. RefreshDisplayType(NULL);
  1651. }
  1652. // This initialises the format we hold which contains the display device type
  1653. // We do a conversion on the display device type in here so that when we start
  1654. // type checking input formats we can assume that certain fields have been set
  1655. // correctly, an example is when we make the 16 bit mask fields explicit. This
  1656. // is normally called when we receive WM_DEVMODECHANGED device change messages
  1657. // The optional szDeviceName parameter tells us which monitor we are interested
  1658. // in for a multi monitor system
  1659. HRESULT CImageDisplay::RefreshDisplayType(LPSTR szDeviceName)
  1660. {
  1661. CAutoLock cDisplayLock(this);
  1662. // Set the preferred format type
  1663. ZeroMemory((PVOID)&m_Display,sizeof(VIDEOINFOHEADER)+sizeof(TRUECOLORINFO));
  1664. m_Display.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  1665. m_Display.bmiHeader.biBitCount = FALSE;
  1666. // Get the bit depth of a device compatible bitmap
  1667. // get caps of whichever monitor they are interested in (multi monitor)
  1668. HDC hdcDisplay;
  1669. // it's ugly, but this is the way you have to do it
  1670. if (szDeviceName == NULL || lstrcmpiA(szDeviceName, "DISPLAY") == 0)
  1671. hdcDisplay = CreateDCA("DISPLAY", NULL, NULL, NULL);
  1672. else
  1673. hdcDisplay = CreateDCA(NULL, szDeviceName, NULL, NULL);
  1674. if (hdcDisplay == NULL) {
  1675. ASSERT(FALSE);
  1676. DbgLog((LOG_ERROR,1,TEXT("ACK! Can't get a DC for %hs"),
  1677. szDeviceName ? szDeviceName : "<NULL>"));
  1678. return E_FAIL;
  1679. } else {
  1680. DbgLog((LOG_TRACE,3,TEXT("Created a DC for %s"),
  1681. szDeviceName ? szDeviceName : "<NULL>"));
  1682. }
  1683. HBITMAP hbm = CreateCompatibleBitmap(hdcDisplay,1,1);
  1684. if ( hbm )
  1685. {
  1686. GetDIBits(hdcDisplay,hbm,0,1,NULL,(BITMAPINFO *)&m_Display.bmiHeader,DIB_RGB_COLORS);
  1687. // This call will get the colour table or the proper bitfields
  1688. GetDIBits(hdcDisplay,hbm,0,1,NULL,(BITMAPINFO *)&m_Display.bmiHeader,DIB_RGB_COLORS);
  1689. DeleteObject(hbm);
  1690. }
  1691. DeleteDC(hdcDisplay);
  1692. // Complete the display type initialisation
  1693. ASSERT(CheckHeaderValidity(&m_Display));
  1694. UpdateFormat(&m_Display);
  1695. DbgLog((LOG_TRACE,3,TEXT("New DISPLAY bit depth =%d"),
  1696. m_Display.bmiHeader.biBitCount));
  1697. return NOERROR;
  1698. }
  1699. // We assume throughout this code that any bitfields masks are allowed no
  1700. // more than eight bits to store a colour component. This checks that the
  1701. // bit count assumption is enforced and also makes sure that all the bits
  1702. // set are contiguous. We return a boolean TRUE if the field checks out ok
  1703. BOOL CImageDisplay::CheckBitFields(const VIDEOINFO *pInput)
  1704. {
  1705. DWORD *pBitFields = (DWORD *) BITMASKS(pInput);
  1706. for (INT iColour = iRED;iColour <= iBLUE;iColour++) {
  1707. // First of all work out how many bits are set
  1708. DWORD SetBits = CountSetBits(pBitFields[iColour]);
  1709. if (SetBits > iMAXBITS || SetBits == 0) {
  1710. NOTE1("Bit fields for component %d invalid",iColour);
  1711. return FALSE;
  1712. }
  1713. // Next work out the number of zero bits prefix
  1714. DWORD PrefixBits = CountPrefixBits(pBitFields[iColour]);
  1715. // This is going to see if all the bits set are contiguous (as they
  1716. // should be). We know how much to shift them right by from the
  1717. // count of prefix bits. The number of bits set defines a mask, we
  1718. // invert this (ones complement) and AND it with the shifted bit
  1719. // fields. If the result is NON zero then there are bit(s) sticking
  1720. // out the left hand end which means they are not contiguous
  1721. DWORD TestField = pBitFields[iColour] >> PrefixBits;
  1722. DWORD Mask = ULONG_MAX << SetBits;
  1723. if (TestField & Mask) {
  1724. NOTE1("Bit fields for component %d not contiguous",iColour);
  1725. return FALSE;
  1726. }
  1727. }
  1728. return TRUE;
  1729. }
  1730. // This counts the number of bits set in the input field
  1731. DWORD CImageDisplay::CountSetBits(DWORD Field)
  1732. {
  1733. // This is a relatively well known bit counting algorithm
  1734. DWORD Count = 0;
  1735. DWORD init = Field;
  1736. // Until the input is exhausted, count the number of bits
  1737. while (init) {
  1738. init = init & (init - 1); // Turn off the bottommost bit
  1739. Count++;
  1740. }
  1741. return Count;
  1742. }
  1743. // This counts the number of zero bits upto the first one set NOTE the input
  1744. // field should have been previously checked to ensure there is at least one
  1745. // set although if we don't find one set we return the impossible value 32
  1746. DWORD CImageDisplay::CountPrefixBits(DWORD Field)
  1747. {
  1748. DWORD Mask = 1;
  1749. DWORD Count = 0;
  1750. while (TRUE) {
  1751. if (Field & Mask) {
  1752. return Count;
  1753. }
  1754. Count++;
  1755. ASSERT(Mask != 0x80000000);
  1756. if (Mask == 0x80000000) {
  1757. return Count;
  1758. }
  1759. Mask <<= 1;
  1760. }
  1761. }
  1762. // This is called to check the BITMAPINFOHEADER for the input type. There are
  1763. // many implicit dependancies between the fields in a header structure which
  1764. // if we validate now make for easier manipulation in subsequent handling. We
  1765. // also check that the BITMAPINFOHEADER matches it's specification such that
  1766. // fields likes the number of planes is one, that it's structure size is set
  1767. // correctly and that the bitmap dimensions have not been set as negative
  1768. BOOL CImageDisplay::CheckHeaderValidity(const VIDEOINFO *pInput)
  1769. {
  1770. // Check the bitmap width and height are not negative.
  1771. if (pInput->bmiHeader.biWidth <= 0 ||
  1772. pInput->bmiHeader.biHeight <= 0) {
  1773. NOTE("Invalid bitmap dimensions");
  1774. return FALSE;
  1775. }
  1776. // Check the compression is either BI_RGB or BI_BITFIELDS
  1777. if (pInput->bmiHeader.biCompression != BI_RGB) {
  1778. if (pInput->bmiHeader.biCompression != BI_BITFIELDS) {
  1779. NOTE("Invalid compression format");
  1780. return FALSE;
  1781. }
  1782. }
  1783. // If BI_BITFIELDS compression format check the colour depth
  1784. if (pInput->bmiHeader.biCompression == BI_BITFIELDS) {
  1785. if (pInput->bmiHeader.biBitCount != 16) {
  1786. if (pInput->bmiHeader.biBitCount != 32) {
  1787. NOTE("BI_BITFIELDS not 16/32 bit depth");
  1788. return FALSE;
  1789. }
  1790. }
  1791. }
  1792. // Check the assumptions about the layout of the bit fields
  1793. if (pInput->bmiHeader.biCompression == BI_BITFIELDS) {
  1794. if (CheckBitFields(pInput) == FALSE) {
  1795. NOTE("Bit fields are not valid");
  1796. return FALSE;
  1797. }
  1798. }
  1799. // Are the number of planes equal to one
  1800. if (pInput->bmiHeader.biPlanes != 1) {
  1801. NOTE("Number of planes not one");
  1802. return FALSE;
  1803. }
  1804. // Check the image size is consistent (it can be zero)
  1805. if (pInput->bmiHeader.biSizeImage != GetBitmapSize(&pInput->bmiHeader)) {
  1806. if (pInput->bmiHeader.biSizeImage) {
  1807. NOTE("Image size incorrectly set");
  1808. return FALSE;
  1809. }
  1810. }
  1811. // Check the size of the structure
  1812. if (pInput->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)) {
  1813. NOTE("Size of BITMAPINFOHEADER wrong");
  1814. return FALSE;
  1815. }
  1816. return CheckPaletteHeader(pInput);
  1817. }
  1818. // This runs a few simple tests against the palette fields in the input to
  1819. // see if it looks vaguely correct. The tests look at the number of palette
  1820. // colours present, the number considered important and the biCompression
  1821. // field which should always be BI_RGB as no other formats are meaningful
  1822. BOOL CImageDisplay::CheckPaletteHeader(const VIDEOINFO *pInput)
  1823. {
  1824. // The checks here are for palettised videos only
  1825. if (PALETTISED(pInput) == FALSE) {
  1826. if (pInput->bmiHeader.biClrUsed) {
  1827. NOTE("Invalid palette entries");
  1828. return FALSE;
  1829. }
  1830. return TRUE;
  1831. }
  1832. // Compression type of BI_BITFIELDS is meaningless for palette video
  1833. if (pInput->bmiHeader.biCompression != BI_RGB) {
  1834. NOTE("Palettised video must be BI_RGB");
  1835. return FALSE;
  1836. }
  1837. // Check the number of palette colours is correct
  1838. if (pInput->bmiHeader.biClrUsed > PALETTE_ENTRIES(pInput)) {
  1839. NOTE("Too many colours in palette");
  1840. return FALSE;
  1841. }
  1842. // The number of important colours shouldn't exceed the number used
  1843. if (pInput->bmiHeader.biClrImportant > pInput->bmiHeader.biClrUsed) {
  1844. NOTE("Too many important colours");
  1845. return FALSE;
  1846. }
  1847. return TRUE;
  1848. }
  1849. // Return the format of the video display
  1850. const VIDEOINFO *CImageDisplay::GetDisplayFormat()
  1851. {
  1852. return &m_Display;
  1853. }
  1854. // Return TRUE if the display uses a palette
  1855. BOOL CImageDisplay::IsPalettised()
  1856. {
  1857. return PALETTISED(&m_Display);
  1858. }
  1859. // Return the bit depth of the current display setting
  1860. WORD CImageDisplay::GetDisplayDepth()
  1861. {
  1862. return m_Display.bmiHeader.biBitCount;
  1863. }
  1864. // Initialise the optional fields in a VIDEOINFO. These are mainly to do with
  1865. // the source and destination rectangles and palette information such as the
  1866. // number of colours present. It simplifies our code just a little if we don't
  1867. // have to keep checking for all the different valid permutations in a header
  1868. // every time we want to do anything with it (an example would be creating a
  1869. // palette). We set the base class media type before calling this function so
  1870. // that the media types between the pins match after a connection is made
  1871. HRESULT CImageDisplay::UpdateFormat(VIDEOINFO *pVideoInfo)
  1872. {
  1873. ASSERT(pVideoInfo);
  1874. BITMAPINFOHEADER *pbmi = HEADER(pVideoInfo);
  1875. SetRectEmpty(&pVideoInfo->rcSource);
  1876. SetRectEmpty(&pVideoInfo->rcTarget);
  1877. // Set the number of colours explicitly
  1878. if (PALETTISED(pVideoInfo)) {
  1879. if (pVideoInfo->bmiHeader.biClrUsed == 0) {
  1880. pVideoInfo->bmiHeader.biClrUsed = PALETTE_ENTRIES(pVideoInfo);
  1881. }
  1882. }
  1883. // The number of important colours shouldn't exceed the number used, on
  1884. // some displays the number of important colours is not initialised when
  1885. // retrieving the display type so we set the colours used correctly
  1886. if (pVideoInfo->bmiHeader.biClrImportant > pVideoInfo->bmiHeader.biClrUsed) {
  1887. pVideoInfo->bmiHeader.biClrImportant = PALETTE_ENTRIES(pVideoInfo);
  1888. }
  1889. // Change the image size field to be explicit
  1890. if (pVideoInfo->bmiHeader.biSizeImage == 0) {
  1891. pVideoInfo->bmiHeader.biSizeImage = GetBitmapSize(&pVideoInfo->bmiHeader);
  1892. }
  1893. return NOERROR;
  1894. }
  1895. // Lots of video rendering filters want code to check proposed formats are ok
  1896. // This checks the VIDEOINFO we are passed as a media type. If the media type
  1897. // is a valid media type then we return NOERROR otherwise E_INVALIDARG. Note
  1898. // however we only accept formats that can be easily displayed in the display
  1899. // so if we are on a 16 bit device we will not accept 24 bit images. The one
  1900. // complexity is that most displays draw 8 bit palettised images efficiently
  1901. // Also if the input format is less colour bits per pixel then we also accept
  1902. HRESULT CImageDisplay::CheckVideoType(const VIDEOINFO *pInput)
  1903. {
  1904. // First of all check the VIDEOINFOHEADER looks correct
  1905. if (CheckHeaderValidity(pInput) == FALSE) {
  1906. return E_INVALIDARG;
  1907. }
  1908. // Virtually all devices support palettised images efficiently
  1909. if (m_Display.bmiHeader.biBitCount == pInput->bmiHeader.biBitCount) {
  1910. if (PALETTISED(pInput) == TRUE) {
  1911. ASSERT(PALETTISED(&m_Display) == TRUE);
  1912. NOTE("(Video) Type connection ACCEPTED");
  1913. return NOERROR;
  1914. }
  1915. }
  1916. // Is the display depth greater than the input format
  1917. if (m_Display.bmiHeader.biBitCount > pInput->bmiHeader.biBitCount) {
  1918. NOTE("(Video) Mismatch agreed");
  1919. return NOERROR;
  1920. }
  1921. // Is the display depth less than the input format
  1922. if (m_Display.bmiHeader.biBitCount < pInput->bmiHeader.biBitCount) {
  1923. NOTE("(Video) Format mismatch");
  1924. return E_INVALIDARG;
  1925. }
  1926. // Both input and display formats are either BI_RGB or BI_BITFIELDS
  1927. ASSERT(m_Display.bmiHeader.biBitCount == pInput->bmiHeader.biBitCount);
  1928. ASSERT(PALETTISED(pInput) == FALSE);
  1929. ASSERT(PALETTISED(&m_Display) == FALSE);
  1930. // BI_RGB 16 bit representation is implicitly RGB555, and likewise BI_RGB
  1931. // 24 bit representation is RGB888. So we initialise a pointer to the bit
  1932. // fields they really mean and check against the display device format
  1933. // This is only going to be called when both formats are equal bits pixel
  1934. const DWORD *pInputMask = GetBitMasks(pInput);
  1935. const DWORD *pDisplayMask = GetBitMasks((VIDEOINFO *)&m_Display);
  1936. if (pInputMask[iRED] != pDisplayMask[iRED] ||
  1937. pInputMask[iGREEN] != pDisplayMask[iGREEN] ||
  1938. pInputMask[iBLUE] != pDisplayMask[iBLUE]) {
  1939. NOTE("(Video) Bit field mismatch");
  1940. return E_INVALIDARG;
  1941. }
  1942. NOTE("(Video) Type connection ACCEPTED");
  1943. return NOERROR;
  1944. }
  1945. // Return the bit masks for the true colour VIDEOINFO provided
  1946. const DWORD *CImageDisplay::GetBitMasks(const VIDEOINFO *pVideoInfo)
  1947. {
  1948. static const DWORD FailMasks[] = {0,0,0};
  1949. if (pVideoInfo->bmiHeader.biCompression == BI_BITFIELDS) {
  1950. return BITMASKS(pVideoInfo);
  1951. }
  1952. ASSERT(pVideoInfo->bmiHeader.biCompression == BI_RGB);
  1953. switch (pVideoInfo->bmiHeader.biBitCount) {
  1954. case 16: return bits555;
  1955. case 24: return bits888;
  1956. case 32: return bits888;
  1957. default: return FailMasks;
  1958. }
  1959. }
  1960. // Check to see if we can support media type pmtIn as proposed by the output
  1961. // pin - We first check that the major media type is video and also identify
  1962. // the media sub type. Then we thoroughly check the VIDEOINFO type provided
  1963. // As well as the contained VIDEOINFO being correct the major type must be
  1964. // video, the subtype a recognised video format and the type GUID correct
  1965. HRESULT CImageDisplay::CheckMediaType(const CMediaType *pmtIn)
  1966. {
  1967. // Does this have a VIDEOINFOHEADER format block
  1968. const GUID *pFormatType = pmtIn->FormatType();
  1969. if (*pFormatType != FORMAT_VideoInfo) {
  1970. NOTE("Format GUID not a VIDEOINFOHEADER");
  1971. return E_INVALIDARG;
  1972. }
  1973. ASSERT(pmtIn->Format());
  1974. // Check the format looks reasonably ok
  1975. ULONG Length = pmtIn->FormatLength();
  1976. if (Length < SIZE_VIDEOHEADER) {
  1977. NOTE("Format smaller than a VIDEOHEADER");
  1978. return E_FAIL;
  1979. }
  1980. VIDEOINFO *pInput = (VIDEOINFO *) pmtIn->Format();
  1981. // Check the major type is MEDIATYPE_Video
  1982. const GUID *pMajorType = pmtIn->Type();
  1983. if (*pMajorType != MEDIATYPE_Video) {
  1984. NOTE("Major type not MEDIATYPE_Video");
  1985. return E_INVALIDARG;
  1986. }
  1987. // Check we can identify the media subtype
  1988. const GUID *pSubType = pmtIn->Subtype();
  1989. if (GetBitCount(pSubType) == USHRT_MAX) {
  1990. NOTE("Invalid video media subtype");
  1991. return E_INVALIDARG;
  1992. }
  1993. return CheckVideoType(pInput);
  1994. }
  1995. // Given a video format described by a VIDEOINFO structure we return the mask
  1996. // that is used to obtain the range of acceptable colours for this type, for
  1997. // example, the mask for a 24 bit true colour format is 0xFF in all cases. A
  1998. // 16 bit 5:6:5 display format uses 0xF8, 0xFC and 0xF8, therefore given any
  1999. // RGB triplets we can AND them with these fields to find one that is valid
  2000. BOOL CImageDisplay::GetColourMask(DWORD *pMaskRed,
  2001. DWORD *pMaskGreen,
  2002. DWORD *pMaskBlue)
  2003. {
  2004. CAutoLock cDisplayLock(this);
  2005. *pMaskRed = 0xFF;
  2006. *pMaskGreen = 0xFF;
  2007. *pMaskBlue = 0xFF;
  2008. // If this format is palettised then it doesn't have bit fields
  2009. if (m_Display.bmiHeader.biBitCount < 16) {
  2010. return FALSE;
  2011. }
  2012. // If this is a 24 bit true colour display then it can handle all the
  2013. // possible colour component ranges described by a byte. It is never
  2014. // allowed for a 24 bit colour depth image to have BI_BITFIELDS set
  2015. if (m_Display.bmiHeader.biBitCount == 24) {
  2016. ASSERT(m_Display.bmiHeader.biCompression == BI_RGB);
  2017. return TRUE;
  2018. }
  2019. // Calculate the mask based on the format's bit fields
  2020. const DWORD *pBitFields = (DWORD *) GetBitMasks((VIDEOINFO *)&m_Display);
  2021. DWORD *pOutputMask[] = { pMaskRed, pMaskGreen, pMaskBlue };
  2022. // We know from earlier testing that there are no more than iMAXBITS
  2023. // bits set in the mask and that they are all contiguous. All that
  2024. // therefore remains is to shift them into the correct position
  2025. for (INT iColour = iRED;iColour <= iBLUE;iColour++) {
  2026. // This works out how many bits there are and where they live
  2027. DWORD PrefixBits = CountPrefixBits(pBitFields[iColour]);
  2028. DWORD SetBits = CountSetBits(pBitFields[iColour]);
  2029. // The first shift moves the bit field so that it is right justified
  2030. // in the DWORD, after which we then shift it back left which then
  2031. // puts the leading bit in the bytes most significant bit position
  2032. *(pOutputMask[iColour]) = pBitFields[iColour] >> PrefixBits;
  2033. *(pOutputMask[iColour]) <<= (iMAXBITS - SetBits);
  2034. }
  2035. return TRUE;
  2036. }
  2037. /* Helper to convert to VIDEOINFOHEADER2
  2038. */
  2039. STDAPI ConvertVideoInfoToVideoInfo2(AM_MEDIA_TYPE *pmt)
  2040. {
  2041. ASSERT(pmt->formattype == FORMAT_VideoInfo);
  2042. VIDEOINFO *pVideoInfo = (VIDEOINFO *)pmt->pbFormat;
  2043. PVOID pvNew = CoTaskMemAlloc(pmt->cbFormat + sizeof(VIDEOINFOHEADER2) -
  2044. sizeof(VIDEOINFOHEADER));
  2045. if (pvNew == NULL) {
  2046. return E_OUTOFMEMORY;
  2047. }
  2048. CopyMemory(pvNew, pmt->pbFormat, FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader));
  2049. ZeroMemory((PBYTE)pvNew + FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader),
  2050. sizeof(VIDEOINFOHEADER2) - sizeof(VIDEOINFOHEADER));
  2051. CopyMemory((PBYTE)pvNew + FIELD_OFFSET(VIDEOINFOHEADER2, bmiHeader),
  2052. pmt->pbFormat + FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader),
  2053. pmt->cbFormat - FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader));
  2054. VIDEOINFOHEADER2 *pVideoInfo2 = (VIDEOINFOHEADER2 *)pvNew;
  2055. pVideoInfo2->dwPictAspectRatioX = (DWORD)pVideoInfo2->bmiHeader.biWidth;
  2056. pVideoInfo2->dwPictAspectRatioY = (DWORD)pVideoInfo2->bmiHeader.biHeight;
  2057. pmt->formattype = FORMAT_VideoInfo2;
  2058. CoTaskMemFree(pmt->pbFormat);
  2059. pmt->pbFormat = (PBYTE)pvNew;
  2060. pmt->cbFormat += sizeof(VIDEOINFOHEADER2) - sizeof(VIDEOINFOHEADER);
  2061. return S_OK;
  2062. }