- DirectShow Primer
- Adding a Control Panel to the GUI-Based Media Player's User Interface
- Creating a GUI-Based Media Player with an Integrated Video Renderer Window
- Conclusion
Adding a Control Panel to the GUI-Based Media Player's User Interface
Although the previous GUI-based mp1 application is more useful than the earlier command-line-based hdshow application, mp1 leaves much to be desired. Perhaps its biggest problem is the absence of a control panel for playing, pausing, and stopping media. Fortunately, it's not that difficult to extend mp1 with a control panel and other capabilities, as Figure 3 testifies.
The control panel lets you play media, and pause and stop playing media.
Figure 3 reveals an mp2 application's user interface, which is divided into a menu bar, a toolbar, a content area, and a status bar. Additionally, the title bar presents the path (including the name) of the currently loaded media file. Although cut off in this example, "- Media Player #2" follows the path on the title bar.
The menu bar presents a single File menu. This menu offers an Open menu item for choosing a media file via a dialog box. (You can enter an http:// URL, such as the displayed content's http://www.spacetelescope.org/static/archives/videos/medium_flash/astro_q.flv URL, in the dialog's File name field, if desired). It also offers an Exit menu item for terminating the media player.
You can choose a media file via the dialog box. Alternatively, you can drag a media file onto the media player window. The media player responds by updating its title bar and toolbar buttons, with the play button enabled and the pause and stop buttons disabled. You'll need to click the play button because the media doesn't start playing automatically.
While the media is playing, the pause and stop buttons are enabled, allowing you to pause or stop the media. Also, video content appears in the content area; this area is left blank if audio-only content is playing. And the status bar displays Running, along with the media's current position and its duration—it displays Paused or Stopped in response to clicking the pause or stop buttons.
Now that you know what mp2 does, Listing 5 shows you how mp2 works.
Listing 5 mp2.cpp
// mp2.cpp // Media Player #2 #include <control.h> #include <evcode.h> // EC_COMPLETE/EC_USERABORT/EC_ERRORABORT definitions #include <io.h> #include <iostream.h> #include <strmif.h> #include <uuids.h> #include <commctrl.h> // toolbar and status bar constants #include "mp2.h" #define DELAY 100 #define OAFALSE 0 #define OATRUE -1 #define TBSTYLE_FLAT 0x0800 #define WM_GRAPHNOTIFY WM_APP+1 #pragma resource "mp2.res" char g_szAppName [] = "mp2"; HWND g_hWndStatusBar; HWND g_hWndToolBar; IGraphBuilder *g_pGraph; IMediaControl *g_pControl; IMediaEventEx *g_pEvent; IMediaPosition *g_pPosition; IVideoWindow *g_pVidWin; void DSCleanup (void) { if (g_pControl != NULL) g_pControl->Stop (); if (g_pEvent != NULL) { g_pEvent->SetNotifyWindow (NULL, 0, 0); g_pEvent->Release (); g_pEvent = NULL; } if (g_pPosition != NULL) { g_pPosition->Release (); g_pPosition = NULL; } if (g_pVidWin != NULL) { g_pVidWin->put_Visible (OAFALSE); // Hide video renderer's window to // prevent momentary video image // flicker. g_pVidWin->put_Owner (NULL); g_pVidWin->Release (); g_pVidWin = NULL; } if (g_pControl != NULL) { g_pControl->Release (); g_pControl = NULL; } if (g_pGraph != NULL) { g_pGraph->Release (); g_pGraph = NULL; } } BOOL DSSetup (HWND hWnd, LPSTR szMediaPath) { HRESULT hr = CoCreateInstance (CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (LPVOID *) &g_pGraph); if (FAILED (hr)) { MessageBox (hWnd, "CoCreateInstance() failure", g_szAppName, MB_OK); return FALSE; } hr = g_pGraph->QueryInterface (IID_IMediaControl, (LPVOID *) &g_pControl); if (FAILED (hr)) { MessageBox (hWnd, "unable to obtain IMediaControl interface", g_szAppName, MB_OK); return FALSE; } hr = g_pGraph->QueryInterface (IID_IVideoWindow, (LPVOID *) &g_pVidWin); if (FAILED (hr)) { MessageBox (hWnd, "unable to obtain IVideoWindow interface", g_szAppName, MB_OK); return FALSE; } hr = g_pGraph->QueryInterface (IID_IMediaPosition, (LPVOID *) &g_pPosition); if (FAILED (hr)) { MessageBox (hWnd, "unable to obtain IMediaPosition interface", g_szAppName, MB_OK); return FALSE; } hr = g_pGraph->QueryInterface (IID_IMediaEventEx, (LPVOID *) &g_pEvent); if (FAILED (hr)) { MessageBox (hWnd, "unable to obtain IMediaEventEx interface", g_szAppName, MB_OK); return FALSE; } g_pEvent->SetNotifyWindow ((OAHWND) hWnd, WM_GRAPHNOTIFY, 0); WCHAR wPath [MAXPATH]; MultiByteToWideChar (CP_ACP, 0, szMediaPath, -1, wPath, MAXPATH); hr = g_pGraph->RenderFile (wPath, NULL); if (SUCCEEDED (hr)) { g_pVidWin->put_Owner ((OAHWND) hWnd); g_pVidWin->put_WindowStyle (WS_CHILD); g_pVidWin->put_Visible (OATRUE); RECT rcWin; GetClientRect (hWnd, &rcWin); WORD nWidth = rcWin.right-rcWin.left; WORD nHeight = rcWin.bottom-rcWin.top; SendMessage (hWnd, WM_SIZE, 0, MAKELONG (nWidth, nHeight)); } else { MessageBox (hWnd, "unable to render media", g_szAppName, MB_OK); return FALSE; } return TRUE; } void UpdateStatusBar (void) { REFTIME _seconds; if (FAILED (g_pPosition->get_CurrentPosition (&_seconds))) return; int seconds = (int) _seconds; int hours = seconds/3600; int minutes = (seconds-(hours*3600))/60; seconds = seconds-(hours*3600+minutes*60); char buffer [100]; wsprintf (buffer, " %02d:%02d:%02d", hours, minutes, seconds); SendMessage (g_hWndStatusBar, SB_SETTEXT, 1, (LPARAM) (LPSTR) buffer); if (FAILED (g_pPosition->get_Duration (&_seconds))) return; seconds = (int) _seconds; hours = seconds/3600; minutes = (seconds-(hours*3600))/60; seconds = seconds-(hours*3600+minutes*60); wsprintf (buffer, " %02d:%02d:%02d", hours, minutes, seconds); SendMessage (g_hWndStatusBar, SB_SETTEXT, 2, (LPARAM) (LPSTR) buffer); } LRESULT CALLBACK WndProc (HWND hWnd, int iMsg, WPARAM wParam, LPARAM lParam) { int aiPartWidths [3]; LPSTR lpstrFilter = "Media files (*.mpg, *.avi, *.wmv, *.mp3, *.wma)\0" "*.mpg;*.avi;*.wmv;*.mp3;*.wma\0" "All files (*.*)\0" "*.*\0" "\0"; switch (iMsg) { case WM_COMMAND: switch (LOWORD (wParam)) { case IDM_FILE_EXIT: SendMessage (hWnd, WM_CLOSE, 0, 0); return 0; case IDM_FILE_OPEN: char szFilename [MAXPATH]; if (lParam) lstrcpy (szFilename, (LPSTR) lParam); else { szFilename [0] = '\0'; OPENFILENAME ofn; ofn.lStructSize = sizeof (OPENFILENAME); ofn.hwndOwner = hWnd; ofn.hInstance = NULL; ofn.lpstrFilter = lpstrFilter; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = 1; ofn.lpstrFile = szFilename; ofn.nMaxFile = MAXPATH; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = MAXFILE+MAXEXT; ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = NULL; ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = NULL; ofn.lCustData = 0; ofn.lpfnHook = NULL; ofn.lpTemplateName = NULL; if (!GetOpenFileName (&ofn)) return 0; } DSCleanup (); SendMessage (g_hWndStatusBar, SB_SETTEXT, 1, (LPARAM) (LPSTR) " 00:00:00"); SendMessage (g_hWndStatusBar, SB_SETTEXT, 2, (LPARAM) (LPSTR) " 00:00:00"); // Disable Play, Pause, and Stop buttons. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PLAY, 0); SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PAUSE, 0); SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_STOP, 0); char szBuffer [MAXPATH*2]; if (DSSetup (hWnd, szFilename)) { // Enable Play button. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PLAY, MAKELONG (TBSTATE_ENABLED, 0)); wsprintf (szBuffer, "%s - Media Player #2", szFilename); } else { DSCleanup (); wsprintf (szBuffer, "Media Player #2", szFilename); } SendMessage (hWnd, WM_SETTEXT, 0, (LPARAM) (LPSTR) szBuffer); return 0; case IDM_PAUSE: // Disable Pause and Stop buttons. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PAUSE, 0); SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_STOP, 0); // Enable Play button. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PLAY, MAKELONG (TBSTATE_ENABLED, 0)); if (SUCCEEDED (g_pControl->Pause ())) SendMessage (g_hWndStatusBar, SB_SETTEXT, 0, (LPARAM) (LPSTR) " Paused"); return 0; case IDM_PLAY: // Disable Play button. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PLAY, 0); // Enable Pause and Stop buttons. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PAUSE, MAKELONG (TBSTATE_ENABLED, 0)); SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_STOP, MAKELONG (TBSTATE_ENABLED, 0)); if (SUCCEEDED (g_pControl->Run ())) SendMessage (g_hWndStatusBar, SB_SETTEXT, 0, (LPARAM) (LPSTR) " Running"); return 0; case IDM_STOP: // Disable Pause and Stop buttons. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PAUSE, 0); SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_STOP, 0); // Enable Play button. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PLAY, MAKELONG (TBSTATE_ENABLED, 0)); if (SUCCEEDED (g_pControl->Stop ())) { SendMessage (g_hWndStatusBar, SB_SETTEXT, 0, (LPARAM) (LPSTR) " Stopped"); g_pPosition->put_CurrentPosition (0); } return 0; } break; case WM_CREATE: { TBBUTTON tbb [3]; tbb [0].iBitmap = 0; tbb [0].idCommand = IDM_PLAY; tbb [0].fsState = 0; tbb [0].fsStyle = TBSTYLE_BUTTON; tbb [0].dwData = 0; tbb [0].iString = 0; tbb [1].iBitmap = 1; tbb [1].idCommand = IDM_PAUSE; tbb [1].fsState = 0; tbb [1].fsStyle = TBSTYLE_BUTTON; tbb [1].dwData = 0; tbb [1].iString = 0; tbb [2].iBitmap = 2; tbb [2].idCommand = IDM_STOP; tbb [2].fsState = 0; tbb [2].fsStyle = TBSTYLE_BUTTON; tbb [2].dwData = 0; tbb [2].iString = 0; g_hWndToolBar = CreateToolbarEx (hWnd, WS_CHILD | WS_VISIBLE | TBSTYLE_FLAT, 1, 3, ((LPCREATESTRUCT) lParam)->hInstance, 1, tbb, sizeof (tbb)/sizeof (TBBUTTON), 0, 0, 16, 16, sizeof (TBBUTTON)); g_hWndStatusBar = CreateStatusWindow (WS_CHILD | WS_VISIBLE | CCS_BOTTOM | SBARS_SIZEGRIP, "", hWnd, 2); DragAcceptFiles (hWnd, TRUE); return 0; } case WM_DESTROY: DragAcceptFiles (hWnd, FALSE); KillTimer (hWnd, 1); DSCleanup (); PostQuitMessage (0); return 0; case WM_DROPFILES: { char szFilespec [MAXPATH]; DragQueryFile ((HDROP) wParam, 0, szFilespec, sizeof (szFilespec)); SendMessage (hWnd, WM_COMMAND, IDM_FILE_OPEN, (LPARAM) szFilespec); DragFinish ((HDROP) wParam); return 0; } case WM_GRAPHNOTIFY: if (g_pEvent == NULL) return 0; // Get all the events long evCode; LONG_PTR param1, param2; HRESULT hr; while (SUCCEEDED (g_pEvent->GetEvent (&evCode, ¶m1, ¶m2, 0))) { g_pEvent->FreeEventParams (evCode, param1, param2); switch (evCode) { case EC_COMPLETE: // Fall through. case EC_USERABORT: // Fall through. case EC_ERRORABORT: g_pControl->Stop (); g_pPosition->put_CurrentPosition (0); // Disable Pause and Stop buttons. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PAUSE, 0); SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_STOP, 0); // Enable Play button. SendMessage (g_hWndToolBar, TB_SETSTATE, IDM_PLAY, MAKELONG (TBSTATE_ENABLED, 0)); SendMessage (g_hWndStatusBar, SB_SETTEXT, 0, (LPARAM) (LPSTR) ""); return 0; } } return 0; case WM_MOVE: if (g_pVidWin != NULL) g_pVidWin->NotifyOwnerMessage ((OAHWND) hWnd, iMsg, wParam, lParam); return 0; case WM_SIZE: { SendMessage (g_hWndToolBar, TB_AUTOSIZE, 0, 0); int cxParent = LOWORD (lParam); int cyParent = HIWORD (lParam); RECT rcSB; GetWindowRect (g_hWndStatusBar, &rcSB); int cy = rcSB.bottom-rcSB.top; int cx = cxParent; MoveWindow (g_hWndStatusBar, 0, cyParent-cy, cx, cy, TRUE); RECT rcTB; GetWindowRect (g_hWndToolBar, &rcTB); int cyTB = rcTB.bottom-rcTB.top; if (g_pVidWin != NULL) { RECT rc; GetClientRect (hWnd, &rc); g_pVidWin->SetWindowPosition (0, cyTB, rc.right, rc.bottom-cy- cyTB); } aiPartWidths [0] = 3*cxParent/4; aiPartWidths [1] = aiPartWidths [0]+cxParent/8-10; aiPartWidths [2] = aiPartWidths [1]+cxParent/8-10; SendMessage (g_hWndStatusBar, SB_SETPARTS, 3, (LPARAM) (LPINT) aiPartWidths); return 0; } case WM_TIMER: if (g_pPosition != NULL) UpdateStatusBar (); return 0; } return DefWindowProc (hWnd, iMsg, wParam, lParam); } #pragma argsused int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hInstancePrev, LPSTR lpszCmdLine, int iCmdShow) { if (FAILED (CoInitialize (NULL))) { cerr << "CoInitialize() failure\n"; return -1; } WNDCLASSEX wc; wc.cbSize = sizeof (WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC) WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon (NULL, IDI_APPLICATION); wc.hCursor = LoadCursor (NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH); wc.lpszMenuName = g_szAppName; wc.lpszClassName = g_szAppName; wc.hIconSm = LoadIcon (NULL, IDI_APPLICATION); RegisterClassEx (&wc); HWND hWnd = CreateWindowEx (0, g_szAppName, "Media Player #2", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); // Keep trying to obtain a timer until one is available. It's unlikely that // a timer will not be available the first time SetTimer() is called, but it // could happen. while (!SetTimer (hWnd, 1, DELAY, NULL)) if (IDCANCEL == MessageBox (hWnd, "no available timers", g_szAppName, MB_ICONEXCLAMATION | MB_RETRYCANCEL)) return -1; ShowWindow (hWnd, iCmdShow); UpdateWindow (hWnd); MSG msg; while (GetMessage (&msg, NULL, 0, 0 )) { TranslateMessage (&msg); DispatchMessage (&msg); } CoUninitialize (); return msg.wParam; }
For brevity, I'll ignore the timer-creation, drag-and-drop, toolbar, and status bar logic. (You'll find the topics of timers, drag-and-drop, toolbars, and status bars amply discussed elsewhere in books and on the Internet.) Instead, I want to focus on the additional DirectShow capabilities that are made available via DirectShow's IMediaEventEx and IMediaPosition interfaces.
The IMediaEventEx interface makes it possible to receive notifications of when media stops playing because it's finished, because the user interrupted playback (perhaps by closing the video renderer's window), or because of an error condition. These conditions are respectively described by the EC_COMPLETE, EC_USERABORT, and EC_ERRORABORT constants.
For the application to receive these notifications via its window procedure, the application must choose an appropriate window message (ranging from WM_APP through 0xBFFF) and register both this message and the application's window with the filter graph manager, by invoking IMediaEventEx's HRESULT SetNotifyWindow(OAHWND hwnd, long lMsg, LONG_PTR lInstanceData) method.
The application performs this registration in the DSSetup() function via g_pEvent->SetNotifyWindow ((OAHWND) hWnd, WM_GRAPHNOTIFY, 0); after storing a pointer to the IMediaEventEx interface in g_pEvent. Because it's important to cancel event notification before releasing the filter graph, the application executes g_pEvent->SetNotifyWindow (NULL, 0, 0); in DSCleanup().
After receiving a WM_GRAPHNOTIFY message, this message's handler first checks whether g_pEvent contains NULL—this could happen if the window procedure receives the event notification after releasing (and nullifying) g_pEvent in DSCleanup(). This safety check avoids access violations.
The handler then enters a loop (after declaring some variables) to retrieve event notifications that the filter graph manager has placed in an event queue. The loop is needed because multiple notifications might be stored in the queue by the time the application responds. This is due to event notification and the application's message loop functioning in an asynchronous fashion.
Each notification is retrieved by invoking IMediaEventEx's HRESULT GetEvent(long *lEventCode, LONG_PTR *lParam1, LONG_PTR *lParam2, long msTimeout) method. The application passes 0 to msTimeout (the number of milliseconds to block until a notification arrives in the queue) because there's always a notification in the queue when the filter graph manager sends WM_GRAPHNOTIFY.
Within the loop, HRESULT FreeEventParams(long lEventCode, LONG_PTR lParam1, LONG_PTR lParam2) is invoked to free any resources associated with the event notification's parameters. If the notification is one of EC_COMPLETE, EC_USERABORT, or EC_ERRORABORT, the filter graph is stopped (it isn't implicitly stopped when EC_COMPLETE arrives), toolbar button states are changed, and the loop ends.
The IMediaPosition interface lets the application determine the media stream's current position relative to the total duration via the HRESULT get_CurrentPosition(REFTIME *pllTime) method, obtain the stream's duration via HRESULT get_Duration(REFTIME *plength), and reset the current position to 0 (after the media stops) via HRESULT put_CurrentPosition(REFTIME llTime).
I omitted the WS_CLIPSIBLINGS style from the video renderer's window, the toolbar, and the status bar because I found these windows to be well behaved (they didn't try to draw in each other's window). Once again, I included WS_CLIPCHILDREN in the main window to avoid screen flicker, by preventing this parent window from painting behind the toolbar, status bar, and video content.
Listing 6 shows the contents of the mp2.h header file.
Listing 6 mp2.h
// mp2.h #define IDM_FILE_EXIT 100 #define IDM_FILE_OPEN 101 #define IDM_PLAY 200 #define IDM_PAUSE 201 #define IDM_STOP 202
Listing 7 presents the mp2.rc source for mp2's compiled resources—the controls.bmp file (in this article's resources) contains the images that appear on the play, pause, and stop buttons.
Listing 7 mp2.rc
// mp2.rc #include "mp2.h" 1 BITMAP "controls.bmp" mp2 MENU { POPUP "&File" { MENUITEM "&Open...", IDM_FILE_OPEN MENUITEM "E&xit", IDM_FILE_EXIT } }
Invoke the following command lines to create mp2.res followed by mp2.exe: (Once again, I assume that you've installed Borland C++ 5.5.1 and set up your environment as discussed earlier.)
brc32 -r mp2.rc bcc32 -tW -I..\..\include -L..\..\lib mp2.cpp