Converting Visual C++ Media Foundation Capture application to C++ Builder - c++

I am trying to convert the Microsoft "CaptureEngine video capture sample" code from Visual C++ to Embarcadero C++ Builder.
https://code.msdn.microsoft.com/windowsdesktop/Media-Foundation-Capture-78504c83
The code runs fine with Visual C++, but I need to include in a C++ Builder application. I basically have the code working, but there are a couple of issues I need help with.
I can select the video source, preview the video source and even start capture to file. However the video capture file just contains the one frame repeated for the length of the video, even though Audio is correctly recorded.
I am wondering if this is due to events not being handled properly.
The events from the media foundation capture engine are passed to the main thread using windows messaging which then calls the media engine event handler. However I have noticed the event handler to stop the recording and to stop the preview uses wait for result
void WaitForResult()
{
WaitForSingleObject(m_hEvent, INFINITE);
}
HRESULT CaptureManager::StopPreview()
{
HRESULT hr = S_OK;
if (m_pEngine == NULL)
{
return MF_E_NOT_INITIALIZED;
}
if (!m_bPreviewing)
{
return S_OK;
}
hr = m_pEngine->StopPreview();
if (FAILED(hr))
{
goto done;
}
WaitForResult();
if (m_fPowerRequestSet && m_hpwrRequest != INVALID_HANDLE_VALUE)
{
PowerClearRequest(m_hpwrRequest, PowerRequestExecutionRequired);
m_fPowerRequestSet = false;
}
done:
return hr;
}
The trouble is, this m_hEvent is triggered from the C++ Builder event handler which is part of the same main thread which is waiting for the event to be handled, so I get a thread lock when trying to stop the video recording. If I comment out the line, I don't lock but I also don't get valid recorded video file.
I am not sure how the Visual C++ separates the events from the Capture engine code, any suggestion as to how I can do this for C++ Builder?

Capture engine event callback is called on a worker thread and it is not "a part of same main thread".
// Callback method to receive events from the capture engine.
STDMETHODIMP CaptureManager::CaptureEngineCB::OnEvent( _In_ IMFMediaEvent* pEvent)
{
...
if (guidType == MF_CAPTURE_ENGINE_PREVIEW_STOPPED)
{
m_pManager->OnPreviewStopped(hrStatus);
SetEvent(m_pManager->m_hEvent);
This essentially changes the behavior of the application. The controlling thread stops preview and blocks until worker thread delivers a notification which sets the event as I quoted above. From there controlling thread wakes up from wait operation and continues with preview stopped.
If this is not what you are seeing in your application I would suggest setting a breakpoint at the first line of callback function to make sure you receive the notification. If you receive, you can step the code and make sure you reach the event setting line. If you don't receive, something else is blocking and you will have to figure that out, such as for example, by breaking in and examining thread states of the application.

I have found the cause of my issue. The OnEvent routine in the Capture engine example is definitely in its own thread. The problem is that it then posts a message to the main application thread, rather than handling it itself. This means that the main thread is frozen as it waiting on the mutex.
// Callback method to receive events from the capture engine.
STDMETHODIMP CaptureManager::CaptureEngineCB::OnEvent( _In_ IMFMediaEvent* pEvent)
{
// Post a message to the application window, so the event is handled
// on the application's main thread.
if (m_fSleeping && m_pManager != NULL)
{
// We're about to fall asleep, that means we've just asked the CE to stop the preview
// and record. We need to handle it here since our message pump may be gone.
GUID guidType;
HRESULT hrStatus;
HRESULT hr = pEvent->GetStatus(&hrStatus);
if (FAILED(hr))
{
hrStatus = hr;
}
hr = pEvent->GetExtendedType(&guidType);
if (SUCCEEDED(hr))
{
if (guidType == MF_CAPTURE_ENGINE_PREVIEW_STOPPED)
{
m_pManager->OnPreviewStopped(hrStatus);
SetEvent(m_pManager->m_hEvent);
}
else if (guidType == MF_CAPTURE_ENGINE_RECORD_STOPPED)
{
m_pManager->OnRecordStopped(hrStatus);
SetEvent(m_pManager->m_hEvent);
}
else
{
// This is an event we don't know about, we don't really care and there's
// no clean way to report the error so just set the event and fall through.
SetEvent(m_pManager->m_hEvent);
}
}
return S_OK;
}
else
{
pEvent->AddRef(); // The application will release the pointer when it handles the message.
PostMessage(m_hwnd, WM_APP_CAPTURE_EVENT, (WPARAM)pEvent, 0L);
}
return S_OK;
}

Related

Hotplug event does not work libubs 1.0

I'm trying to implement device attach/detach events in my libusb-1.0 code from this example.
Here is how I'm using it:
void registerCallBack() {
int rc;
libusb_init(NULL);
rc = libusb_hotplug_register_callback(NULL, (libusb_hotplug_event) (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), LIBUSB_HOTPLUG_ENUMERATE,
0x2047, LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL,
&handle);
if (LIBUSB_SUCCESS != rc) {
printf("Error creating a hotplug callback\n");
libusb_exit(NULL);
return;
}
printf("Success registering callback\n");
}
Callback function itself:
int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev,
libusb_hotplug_event event, void *user_data) {
printf("EVENT! %d\n", event);
callJava(); // call java method when event fires
return 0;
}
If I run this code and device had attached - fires event, because LIBUSB_HOTPLUG_ENUMERATE set. But if I try to attach/detach device while program running nothing happens. If I'm setting flag to 0 (not LIBUSB_HOTPLUG_ENUMERATE) then no events happens.
I have Ubuntu Linux 13.10 and libusb-1.0.16-3. Callback is registered successfully.
P.S. I use libusb in C++ library for Java program.
Thanks!
I had the same problem, and from a bit of debugging, I found that the hotplug event itself was happening and getting pushed to the event pipe. However, from looking at the libusb source, I didn't see any dedicated thread which would poll for these events. The event polling (and callback invocations) seem to be done as part of the generic transaction request handling. So I suspect (have not tested this myself though) that you have to be making control or data requests to see the hotplug callbacks.
You might try spawning a thread to call libusb_handle_events_timeout_completed() with a NULL timeout parameter, maybe once a second. That might give you what you want.
If this is correct, I wish libusb would have a flag on libusb_init() to create a thread specifically for hotplug events, without depending on control/data request calls.

Why message loop doesn't block the GUI in windows app but does in Qt?

I'm working on a program using Qt, and some of my code is based on Windows samples. The problem I'm having, and something I don't quite understand is how the same code will block my Qt GUI while it will work totally fine in a windows app.
Here's an example. I have a program which gets some data from the camera, does some processing on it, then displays it on the screen. In Windows sample there's something like this:
// Create an event with these self-explanatory parameters
// This event signals when the next frame is ready to process
HANDLE frameEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr)
// Now run a while loop which magically doesn't block
HANDLE hEvents[1];
while (WM_QUIT != msg.message)
{
hEvents[0] = frameEvent;
DWORD dwEvent = MsgWaitForMultipleObjects(1, hEvents, FALSE, INFINITE, QS_ALLINPUT);
// If we have our event run some processing
if (WAIT_OBJECT_0 == dwEvent)
{
update();
}
// Else handle input or whatever
}
The update function looks something like this:
if (WAIT_OBJECT_0 = WaitForSingleObject(frameEvent, 0)
{
getTheFrame();
processTheFrame();
drawTheFrame();
}
If I try to implement it the same way in Qt everything will freeze and the while loop will just run forever. The solution I've got is to run the loop in separate thread (QThread) and emit a signal when new frame is ready, like this:
void Worker::run()
{
running_ = true;
while (running_)
{
if (WaitForSingleObject(frameEvent, 0) == WAIT_OBJECT_0)
{
emit signalFrame();
}
// This is necessary or it will still freeze!
usleep(15);
}
}
The signal is then connected to a slot which does similar job to the Update() method from the windows sample.
Now, this works fine, but only as long as processing a single frame can be done before the next frame is available.
As my processing went more complex and is slower then camera framerate, the program just stops responding. The exact same code in the windows sample still works fine, the framerate just drops, but everything is drawn and the GUI remains responsive.
Could someone explain what is going on, and what may be a possible solution?
The Win32 version calls MsgWaitForMultipleObjects. As its name should imply, it waits for either the specified objects to be signaled or for a window message (and since it's called with QS_ALLINPUT, any window message). Presumably the code also dispatches the window message afterward.
Your version calls WaitForSingleObject. As its name should imply, it waits on only the specified object. It won't unblock itself on window messages.

unresolved problems with C++ EDITTEXT and DIRECTSHOW PAUSE()

i have a simple winform that writes to an EDITTEXT , as the program goes on the printing process executing perfectly . but once i click the STOP BUTTON which firstly calls the PAUSE()
function my program gets stuck inside the
SetWindowText(m_hWatermarksEditBox, &m_watermarkLog[0]);
all values are initialized and proper data gets in.
my guess is that i have to declare a METHOD WORKER , like in C#.NET but i dont know how.
STDMETHODIMP CNaveFilter::Pause()
{
ATLTRACE(L"(%0.5d)CNaveFilter::Pause() (this:0x%.8x)\r\n", GetCurrentThreadId(), (DWORD)this);
HRESULT hr = S_OK;
CAutoLock __lock(&m_cs);
hr = CBaseFilter::Pause();
return hr;
}
STDMETHODIMP CNaveFilter::Stop()
{
ATLTRACE(L"(%0.5d)CNaveFilter::Stop() (this:0x%.8x)\r\n", GetCurrentThreadId(), (DWORD)this);
HRESULT hr = S_OK;
CAutoLock __lock(&m_cs);
hr = CBaseFilter::Stop();
ATLASSERT(SUCCEEDED(hr));
return hr;
}
You don't show where you are doing SetWindowText but as you have the custom filter the most likely problem is that with this call you block your streaming/worker thread execution and the involved threads lock dead.
SetWindowText is only safe to be called from your UI thread (well, technically not only it, but definitely not a streaming thread). So if you want to update the control text or send any message to it, you have to do it in a different way, so that your caller thread could keep running.
Typically, you would store some relevant information in member variable (don't forget critical section lock) then PostMessage, receive the message on your window/control and handle it there in the right thread, calling SetWindowText there.
See controlling frame/rate and exposure time through sampleCB. It covers a bit different topic, but useful in terms of sending/posting messages in a DirectShow filter.

I need a message pump that doesn't mess up my open window

My application (the bootstrap application for an installer that I'm working on needs to launch some other applications (my installer and third party installers for my installer's prerequisites) and wait for them to complete. In order to allow the GUI to do screen updates while waiting for an app to complete, I put a message pump in the wait loop using the 'MFC-compatible' example in the Visual Studio documentation on idle loop processing as a guideline. My code (which is in a member function of a CWinApp-derived class) is as follows:
if (::CreateProcess(lpAppName, szCmdLineBuffer, NULL, NULL, TRUE, 0, NULL, NULL,
&StartupInfo, &ProcessInfo))
{
::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
if (bWait)
while (dwExitCode == STILL_ACTIVE)
{
// In order to allow updates of the GUI to happen while we're waiting for
// the application to finish, we must run a mini message pump here to
// allow messages to go through and get processed. This message pump
// performs much like MFC's main message pump found in CWinThread::Run().
MSG msg;
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!PumpMessage())
{
// a termination message (e.g. WM_DESTROY)
// was processed, so we need to stop waiting
dwExitCode = ERROR_CANT_WAIT;
::PostQuitMessage(0);
break;
}
}
// let MFC do its idle processing
LONG nIdle = 0;
while (OnIdle(nIdle++))
;
if (dwExitCode == STILL_ACTIVE) // was a termination message processed?
{
// no; wait for .1 second to see if the application is finished
::WaitForSingleObject(ProcessInfo.hProcess, 100);
::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
}
}
::CloseHandle(ProcessInfo.hProcess);
::CloseHandle(ProcessInfo.hThread);
}
else
dwExitCode = ::GetLastError();
The problem that I'm having is that, at some point, this message pump seems to free up window and menu handles on the window that I have open at the time this code is run. I did a walk through in the debugger, and at no time did it ever get into the body of the if (!PumpMessage()) statement, so I don't know what's going on here to cause the window and menu handles to go south. If I don't have the message pump, everything works fine, except that the GUI can't update itself while the wait loop is running.
Does anyone have any ideas as to how to make this work? Alternatively, I'd like to launch a worker thread to launch the second app if bWait is TRUE, but I've never done anything with threads before, so I'll need some advice on how to do it without introducing synchronization issues, etc. (Code examples would be greatly appreciated in either case.)
I've also posted this question on the Microsoft forums, and thanks to the help of one Doug Harris at Microsoft, I found out my problem with my HWND and HMENU values was, indeed due to stale CWwnd* and CMenu* pointers (obtained using GetMenu() and GetDialogItem() calls. Getting the pointers again after launching the second app solved that problem. Also, he pointed me to a web site* that showed a better way of doing my loop using MsgWaitForMultipleObjects() to control it that doesn't involve the busy work of waiting a set amount of time and polling the process for an exit code.
My loop now looks like this:
if (bWait)
{
// In order to allow updates of the GUI to happen while we're
// waiting for the application to finish, we must run a message
// pump here to allow messages to go through and get processed.
LONG nIdleCount = 0;
for (;;)
{
MSG msg;
if (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
PumpMessage();
else //if (!OnIdle(nIdleCount++))
{
nIdleCount = 0;
if (!PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
DWORD nRes = ::MsgWaitForMultipleObjects(1, &ProcessInfo.hProcess,
FALSE, INFINITE, QS_ALLEVENTS);
if (nRes == WAIT_OBJECT_0)
break;
}
}
}
}
::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
*That Web site, if you're curious, is: http://members.cox.net/doug_web/threads.htm
I think your problem is in WaitForSingleObject
Looking in MSDN you see this
Use caution when calling the wait functions and code that directly or indirectly creates windows. If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. A thread that uses a wait function with no time-out interval may cause the system to become deadlocked. Two examples of code that indirectly creates windows are DDE and the CoInitialize function. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than WaitForSingleObject.
In my code in the message pump use use MsgWaitForMultipleObjects (doc).
With a call this call.
MsgWaitForMultipleObjects(1, &ProcessInfo.hProcess, FALSE, 100, QS_ALLEVENTS);
This should stop your problem with the resources dissapearing.
When you say that window and menu handles seem to be being freed, do you mean that you've got actual HWND and HMENU values that no longer seem to work, or have you got MFC CWnd* and CMenu* variables that fail?
If the latter, the problem is most likely that you're getting the CWnd* pointers by calling CWnd::FromHandle() (or CMenu::FromHandle()) somewhere (or calling something that calls them), and OnIdle() is discarding them.
The underlying reason is that MFC maintains a map from window (or menu, etc.) handles to CWnd* objects in the system. When CWnd::FromHandle() is called, it looks for a match in the map: if one is found, it's returned. If not, a new, temporary CWnd is created, added to the map, and returned. The idea behind OnIdle() is that when it's called all message processing is done, so OnIdle() discards any of these temporary CWnd objects that still exist. That's why the CWnd::FromHandle() documentation warns that the returned pointer may be temporary.
The "correct" solution to this is to not hang onto the CWnd* pointers returned from CWnd::FromHandle(). Given the simplicity of your application, it might be easier to just remove the call OnIdle(): this shouldn't have any negative effects on an installer.
Of course, this is all something of a guess, but it sounds plausible...
There is a Windows function called DisableProcessWindowsGhosting (see http://msdn.microsoft.com/en-us/library/ms648415(v=vs.85).aspx) that prevents Windows from 'ghosting' your window, and continue updating the window (your animation).

Assertion in VS2008 but not in VS2005

After switching from VS2005 to VS2008 SP1, I found an issue that I can't explain.
A program works fine under VS2005 in both release and debug mode. Under VS2008, when entering the debugger an assert is raised.
If I let the program run (in debug or release mode), no assertion at all.
I spent almost two days on this and I don't understand what I do wrong.
Description of the program:
I have a MFC dialog based program that creates a user thread (CWinThread) that creates the main dialog of the application.
A worker thread loops infinitely and posts each second a message to the dialog. The message is processed in the gui thread.
Some parts of my code:
The InitInstance of the gui thread:
BOOL CGraphicalThread::InitInstance()
{
CGUIThreadDlg* pDlg = new CGUIThreadDlg();
pDlg->Create(CGUIThreadDlg::IDD);
m_pMainWnd = pDlg;
AfxGetApp()->m_pMainWnd = pDlg;
return TRUE;
}
The worker thread:
UINT ThreadProc(LPVOID pVoid)
{
do
{
AfxGetApp()->m_pMainWnd->PostMessage(WM_APP+1, (WPARAM)new CString("Hello"), NULL);
Sleep(1000);
}
while(!bStopThread);
return 0;
}
The dialog message handler is like this:
LRESULT CGUIThreadDlg::OnMsg(WPARAM wp, LPARAM lp)
{
CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST1);
CString* ps = (CString*)wp;
pList->InsertString(-1, *ps);
delete ps;
return 1L;
}
This works perfectly fine with VS2005.
But with VS2008, but as soon as a put a breakpoint and enter the debugging mode, I have an assertion raised ???
wincore.cpp line 906
CObject* p=NULL;
if(pMap)
{
ASSERT( (p = pMap->LookupPermanent(m_hWnd)) != NULL ||
(p = pMap->LookupTemporary(m_hWnd)) != NULL);
}
ASSERT((CWnd*)p == this); // must be us
// Note: if either of the above asserts fire and you are
// writing a multithreaded application, it is likely that
// you have passed a C++ object from one thread to another
// and have used that object in a way that was not intended.
// (only simple inline wrapper functions should be used)
//
// In general, CWnd objects should be passed by HWND from
// one thread to another. The receiving thread can wrap
// the HWND with a CWnd object by using CWnd::FromHandle.
//
// It is dangerous to pass C++ objects from one thread to
// another, unless the objects are designed to be used in
// such a manner.
If I remove the GUI thread and create the dialog into the CWinApp thread, the problem doesn't occur anymore.
Does anybody have any idea?
Am I doing something wrong?
Thank you
// Note: if either of the above asserts fire and you are
// writing a multithreaded application, it is likely that
// you have passed a C++ object from one thread to another
// and have used that object in a way that was not intended.
// (only simple inline wrapper functions should be used)
//
// In general, CWnd objects should be passed by HWND from
// one thread to another. The receiving thread can wrap
// the HWND with a CWnd object by using CWnd::FromHandle.
//
// It is dangerous to pass C++ objects from one thread to
// another, unless the objects are designed to be used in
// such a manner.
#Ismael: I had already tried that the assert is still fired. The only way I found to remove the assert is to create the dialog into the CWinApp thread.
But this doesn't explain what happens since there's still the worker thread that post to the dialog every second.
Anyway , thanks.
#daanish.rumani: I've checked the wincore.cpp and the CWnd::AssertValid() is exactly the same (but there's of lot of differences in the rest of the files).
I would accept that a piece of code works with VS2005 and not VS2008, but
I can't see what I do wrong.
If I do something wrong, what is the correct way to proceed?
Why the assert is only fired when a breakpoint is hit and I step over the Sleep call?
I can run the program fine, even when its compiled in debug mode, as long as I don't enter the debugger.
Could it be a bug in the debugger?