mciSendString doesn't pause sound played from a thread - c++

Recently I already asked for a solution similar to this questions:
Is there a way to pause/stop a mp3 file playing with mcisendstring with the "wait" option?
I want to implement a function in my audio player which allows people to have sound playing continuosly, while a slider moves according to the current second the track is running in, and also with the functionality to go to the next track after the current track is over
After (as you can read in the link) trying to do it with
mciSendString("play mp3 wait", NULL, 0, NULL);
which failed due to the problem that the track can't be paused or stopped until it is finished, I am now trying to implement it another way. Currently, when I start to play the track, I also start another thread, which is starting a counter. The counter is getting the length of the track in seconds, and is counting down the time, also offering a mutex for pausing/resuming the counter. In order to stop my MusicCycle from simply looping uncontrolled, I am joining the thread, therefore waiting for its termination.
void Music::MusicCycle(std::wstring trackPath)
{
while (true)
{
OpenMP3(trackPath);
mciSendString("play mp3", NULL, 0, NULL);
m_counterThread = boost::thread(boost::bind(&Counter::StartCount, m_counter, <length of track in seconds>));
m_counterThread.join();
//... Get new track here
}
}
Note that this whole method is created in a thread as well:
m_cycleThread = boost::thread(boost::bind(&Music::MusicCycle, this, trackPath));
The thread started by the MusicCycle function is looking like this:
void Counter::StartCount(int seconds)
{
boost::mutex::scoped_lock lock(m_mutex);
for (int i = 0; i < seconds; i++)
{
while (m_counterLock)
{
m_condVar.wait(lock);
}
boost::this_thread::sleep(boost::posix_time::seconds(1));
}
}
Also, I added another functionality to lock/unlock the mutex here with my Pause/Resume methods, which also call the corresponding mciSendString functions
mciSendString("resume mp3", NULL, 0, NULL);
mciSendString("pause mp3", NULL, 0, NULL);
When I would call pause now, mciSendString would pause the track, and also lock the counter so it won't keep on counting down.
However, the problem is that it still doesn't work. The pause simply doesn't affect the playing of music, despite my efforts to think up a solution without using the wait option in the mciSendString
Any advice?
EDIT: Turns out this is actually happening due to threading. I've been doing some C# for a good amount of time and you could use Invokes to work around thread problems. Maybe this is possible here as well?
EDIT2: I read up a bit and it seems like there is an option to Post a method in the message queue of another thread via PostMessage WinAPI call. Is this a possiblity here? If yes, could anyone provide a good example? I read up a bit but I don't really understand alot so far
Is there something like this in C++ as well?

EDIT: Turns out this is actually happening due to threading. I've been doing some C# for a good amount of time and you could use Invokes to work around thread problems.
Yes. Ifff you need a user-land thread for the asynchronous events then a queued message is your course of action (like C#'s (or Java's etc.) invoke-on-UI-thread). That's hard work.
EDIT2: I read up a bit and it seems like there is an option to Post a method in the message queue of another thread via PostMessage WinAPI call. Is this a possiblity here? If yes, could anyone provide a good example? I read up a bit but I don't really understand alot so far
Is there something like this in C++ as well?
What you're referring to is just the general message-pump/event-loop that underlies almost¹ all UI frameworks. C++ doesn't "have" GUI natively, but certainly libraries exist that have similar facilities.
Boost Asio was one mentionable. If you already have a GUI framework, it'll have it's own event loop (Qt, MFC etc. have it).
Regardless of what is used, all Win32 GUI applications end up using the message pump you referred to which does indeed allow messages to be posted.
This is almost always the wrong level of abstraction, unless you're actively developing your GUI framework².
You can always build your own. Just have some kind of (priority) queue to receive messages and have a main loop processing these. Call them events and pronto: event-driven design.
¹ there's a wave back at the moment with new-fangled back-to-basics like https://github.com/ocornut/imgui
² the fact that this question exists tells me you are not doing that

Related

How to properly use the asynchronous libusb?

I worked on the synchronous libusb in my Qt project with good results and now I need the asynchronous features of this library. I understood reading here, here and here that, after I've registered my callback function using the libusb_fill_control_transfer and submitted a transfer with libusb_submit_transfer , I need to "keep live" the libusb_handle_events_completed inside a while loop to get the transfer related events since the libusb doesn't have its own thread. for example you can read a code like this
libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
libusb_submit_transfer(transfer);
while (!completed) {
libusb_handle_events_completed(ctx, &completed);
}
Now if I want read a packet that I don't know when it occurs, I think that goes against the asynchronous nature submit a read and wait in the while with libusb_handle_events_completed until the event is triggered.
Then, do I need to create a separate thread within the libusb_handle_events_completed in an infinite while loop?
Can anyone, with experience in the asynchronous features of libusb library, give some suggestions on the right approach to handle the transfer events?

Creating an update method with custom rate processing in c++

If you've ever used XNA game studio 4 you are familiar with the update method. By default the code within is processed at 60 times per second. I have been struggling to recreate such an effect in c++.
I would like to create a method where it will only process the code x amount of times per second. Every way I've tried it processes all at once, as loops do. I've tried for loops, while, goto, and everything processes all at once.
If anyone could please tell me how and if I can achieve such a thing in c++ it would be much appreciated.
With your current level of knowledge this is as specific as I can get:
You can't do what you want with loops, fors, ifs and gotos, because we are no longer in the MS-DOS era.
You also can't have code running at precisely 60 frames per second.
On Windows a system application runs within something called an "event loop".
Typically, from within the event loop, most GUI frameworks call the "onIdle" event, which happens when an application is doing nothing.
You call update from within the onIdle event.
Your onIdle() function will look like this:
void onIdle(){
currentFrameTime = getCurrentFrameTime();
if ((currentFrameTime - lastFrameTime) < minUpdateDelay){
sleepForSmallAmountOfTime();//using Sleep or anything.
//Delay should be much smaller than minUPdateDelay.
//Doing this will reduce CPU load.
return;
}
update(currentFrameTime - lastFrameTime);
lastFrameTime = currentFrameTime;
}
You will need to write your own update function, your update function should take amount of time passed since last frame, and you need to write a getFrameTime() function using either GetTickCount, QueryPerformanceCounter, or some similar function.
Alternatively you could use system timers, but that is a bad idea compared to onIdle() event - if your app runs too slowly.
In short, there's a long road ahead of you.
You need to learn some (preferably cross-platform) GUI framework, learn how to create a window, the concept of an event loop (can't do anything without it today), and then write your own "update()" and get a basic idea of multithreading programming and system events.
Good luck.
As you are familiar with XNA then i assume you also are familiar with "input" and "draw". What you could do is assign independant threads to these 3 functions and have a timer to see if its time to run a thread.
Eg the input would probably trigger draw, and both draw and input would trigger the update method.
-Another way to handle this is my messages events. If youre using Windows then look into Windows messages loop. This will make your input, update and draw event easier by executing on events triggered by the OS.

Use of QMathGL to paint realtime data?

Got really stuck, need some advise or real examples.
1) I have boost::thread vector producer thread (data arrives fast ~ 100 samples per second)
2) I want QMathGL to paint data as it arrives
3) I don't want my Qt gui freeze
I tried to move QMathGL::update() to separate thread - Qt argues that QPixmap not allowed in separate thread.
What should i try, Without modifying QMathGL?
Only thing comes in mind to repaint on timer (fps?), but i don't like this solution, please tell me if i am wrong.
I would strongly advise to go with a timer. Repaint operations are costly and I would assume that no user could realistically process more then 10 printed vectors a second. So I can't see a real benefit for the end user, apart from maybe that the display is updated more "smoothly" and entry for entry. But you could achieve these effects far easier with animations ;)
When repainting with every data change, you get the annoying behaviour you describe. Working around that is (imho) not worth the trouble.
I´ve also come along a similar problem sometimes.
The usual resolution i used is to buffer the data and repainting on a timer. This goes along the line of this (Pseudo Code) :
void Widget::OnNewData(void *dataSample)
{
this->threadSafebuffer->appendData(dataSample);
}
void Widget::OnTimeout()
{
DataBuffer renderBatch = this->threadSafebuffer->interlockedExchange();
/* Do UI updates according to renderBatch */
}
This assumes that OnNewData is called on a background thread. The OnTimeout is called from a QTimer on the UI-EventLoop. To prevent contention it justs does an interlocked exchange of the current buffer pointer with a second buffer. So no heavy synchronization (e.g. Mutext/Semaphore) is needed.
This will only work if the amount of work to do for rendering a renderBatch is less than the timeout.

Possible to stop cin from waiting input?

In a graphical application I execute debug commands using the console input. When the console is created a new thread is also created to gather the user commands that handles all that input, the graphical application continues running parallel. I use boost::thread library.
It works good so far, however I haven't found a nice solution to stop the execution of this thread. The thread is always waiting for a user input:
while(appRunning)
{
std::cin>>theUserCommand;
// ...do stuff
}
Then when the graphical application ends, it will stop all console functions, in which I include the thread:
appRunning = false;
// do some more related clean up
myListeningThread->join();
As you can see the std::cin will be waiting for user input, after the join has being called.
One of the solutions I tried is to create events "synthetizing keystrokes", the std::cin will get whatever value you send with an ENTER, the thread will end nicely, this solutions is horrible and I don't want to keep it.
Besides, it did work in one of the environments the tool is executed, but fails when I tried using it along with a UI API. Could you guys guide me how can I fix this in a correct way? Can't really say for sure if in the C++ documentation there is a function to stop std::cin waiting for user input, and just and continue the program execution, is it even possible?
EDIT: Fine I find that keybd_event is a bit misleading for some environments, explicitly specifying the input handler with the WriteConsoleInput works good.
I am not much of a Windows programmer, I know a whole lot more about Unix. And I am totally unfamiliar with boost::thread. That said, based on the advice at the bottom of this MSDN page, here is my recommendation:
Create an event object before you create the console-reading thread.
When you want to shut down, call SetEvent on the event object immediately before calling the thread's ->join method.
Change the main loop in your console-reading thread to block in WaitForMultipleObjects rather than istream::operator>>, something like this:
for (;;) {
HANDLE h[2];
h[0] = GetStdHandle(STD_INPUT_HANDLE);
h[1] = that_event_object_I_mentioned;
DWORD which = WaitForMultipleObjects(2, h, FALSE, INFINITE);
if (which == WAIT_OBJECT_0)
processConsoleCommand();
else if (which == WAIT_OBJECT_0 + 1)
break;
else
abort();
}
This thread must take care not to do any blocking operation other than the WaitForMultipleObjects call. Per the discussion in the comments below, that means processConsoleCommand can't use cin at all. You will need to use the low-level console input functions instead, notably GetNumberOfConsoleInputEvents and ReadConsoleInput, to ensure that you do not block; you will need to accumulate characters across many calls to processConsoleCommand until you read a carriage return; and you will also need to do your own echoing.

Is there a way to communicate data between computers without while loops? C++

I have been struggling to try and find my answer for this on google, as I dont know the exact terms I am looking to search for.
If someone were to build an msn messenger-like program, is it possible to have always-open connections and no while(true) loop? If so, could someone point me in the direction of how this is achieved?
Using boost::asio library for socket handling, i think it is possible to define callbacks upon data reception.
The one single magic word your looking for is asynchronous I/O. This can be achieved either through using asynchronous APIs (functions such as ReadThis() that return immediately and signal on success/failure -- like but not limited by boost::asio) or by deferring blocking calls to different threads. Picking either method requires careful weighing of both the underlying implementation and the scale of your operations.
You want to use ACE. It has a Reactor pattern which will notify you when data is available to be use.
Reactor Pattern
You could have:
while(1) {
sleep(100); // 100 ms
// check if there is a message
// process message
//...
}
This is ok, but there is an overhead on servers running 10000s of threads since threads come out of sleep and check for a message, causing context-switching. Instead, operating systems provide functions like select and epoll on Linux, which allow a thread to wait on an event.
while(1) {
// wait for message
// process message
//...
}
Using wait, the thread is not "woken up" unless a message is received.
You can only hide your while loop (or some kind of loop) somewhere buried in some library or restart the waiting for next IO in an event callback, but you aren't going to be able to completely avoid it.
That's a great question. Like nj said, you want to use asynchronous I/O. Too many programs use a polling strategy. It is not uncommon to have 1000 threads running on a system. If all of them were polling, you would have a slow system. Use asynchronous I/O whenever possible.
what about udp protocol communication ? you dont have to wait in while loop for every clients
just open one connection on specified port and call receive method