Media Foundation : Looping video unstable on 6th run - loops

Took current media foundation sample from github (MF_ProtectedPlayback, but could have been one of the others).
Added the following so it loops when it gets to the end :
CPlayer::HandleEvent()
{
case MEEndOfPresentation:
CHECK_HR(hr = OnPresentationEnded(pEvent));
// ADV_SW: Loop.
{
static DWORD dbg_count = 0;
dbg_count++;
char title[100];
sprintf_s(title, "Loop: %d", dbg_count);
SetWindowTextA(m_hwndEvent, title);
}
Play();
break;
}
Also, in CPlayer::StartPlayback
... modified so second play starts from beginning
// Start from beginning
PROPVARIANT varStart = { 0 };
InitPropVariantFromInt64(0, &varStart);
hr = m_pSession->Start(&GUID_NULL, &varStart);
When I play example file http://advance-software.com/misc/ad.mp4 (download & run locally)
It works fine for first 5 loops, then starts breaking up on the 6th.
Anyone know what's up ?
Thanks in advance,
Steve.

Seems you must call
m_pSession->Stop();
before the Start() when looping to ensure stability.
Surprised this doesn't occur internally if a requirement to ensure API robustness but such are the dark arts of Media Foundation :)

Related

Want to create an alert/Expert Advisor or Indicator in MT5 if any pending order get executed

Can someone help me to create an indicator in which if client make Limit orders like Buy Limit, Sell Limit, Buy Stop or Sell Stop and if orders get executed then i should have an alert with some sound or without sound, if any pop up will come that is also fine for me.
I am looking for it from last so many days.
For the reference you can check MQL PDF.
"https://www.mql5.com/files/pdf/mql5.pdf".
Regards,
Abhishek
AFAIK only EAs can do that.
You can start with the following code:
void OnTradeTransaction (const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result ) {
switch(trans.type) {
case TRADE_TRANSACTION_DEAL_ADD:
if(HistoryDealSelect(trans.deal)) {
entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(trans.deal, DEAL_ENTRY);
if(entry == DEAL_ENTRY_IN)
onDeal(trans); // An order was opened
}
break;
}
}
void onDeal(const MqlTradeTransaction &trans) {
// Your code goes here, e.x. Sound
PlaySound("news.wav")
}

How do I correctly create a copy of an array in C or set a reference to one?

so, I'm very new to C, coming from a Java/C# background and I can't quite wrap my head around it so far.
What I'm trying to do is program a microcontroller (Adafruit Feather running an atmega32u4 in this case) to pose as a USB-coupled controller for Nintendo Switch and run automated commands.
The project I'm trying to expand upon is using a struct array of commands like this:
typedef struct {
Buttons_t button;
uint16_t duration; // 1 equals 0.025s on ATmega32u4 => 1s = 40
} command;
static const command loop[] = {
// do stuff
{ NOTHING, 150 },
{ TRIGGERS, 15 }, { NOTHING, 150 },
{ TRIGGERS, 15 }, { NOTHING, 150 },
{ A, 5 }, { NOTHING, 250 }
};
Now initially this was all there was to it, the program would loop through the commands, send a button to the console and "hold" it for the defined period of time. When the program ran to the end of the array, it would simply reset the index and start anew.
Now I'm trying to send different commands to the console, based on a few easy if..else queries. Specifically, the program will start with a day, month and year variable (the date the Switch console is currently set to) and roll days forward individually to get to a set date in the future. To this end, I want to check at every 'step' if the date +1 day is valid as described in this tutorial and based on the result either roll one day, one day and one month or one day, one month and one year forward. Then I want it to end after a set amount of days.
I wrote several arrays of commands to represent the different steps needed for setting up the controller, moving to where it's supposed to loop, rolling a day, a month or a year like this:
static const command setupController[] = {
// Setup controller
...
};
static const command moveToLoop[] = {
// Go into date settings
...
};
static const command rollDay[] = {
//roll to next day
...
};
static const command rollMonth[] = {
//roll to next month
...
};
static const command rollYear[] = {
//roll to next year
...
};
And another array I want to copy those to like this:
#define COMMANDMAXSIZE 100
static command activeCommand[COMMANDMAXSIZE];
I know this is (extremely) wasteful of memory, but I'm definitely not good enough at C to come up with fancier, more conservative solutions yet.
Then I go into my program, which looks like this:
int main(void) {
SetupHardware(); //Irrelevant, because it is exactly like I downloaded it and it works even with the bumbling changes I've made
GlobalInterruptEnable(); //Ditto
RunOnce(setupController);
RunOnce(moveToLoop);
while (daysSkipped != stopDay)
{
if (datevalid((dayOfMonth + 1), month, year)) {
dayOfMonth++;
RunOnce(rollDay);
}
else if (datevalid(1, (month + 1), year)) {
dayOfMonth = 1;
month++;
RunOnce(rollMonth);
}
else if (datevalid(1, 1, (year + 1))) {
dayOfMonth = 1;
month = 1;
year++;
RunOnce(rollYear);
}
daysSkipped++;
}
}
and finally (I swear I'll be done soon), the start of RunOnce looks like this
void RunOnce(command stepsToRun[]) {
memcpy(activeCommand, stepsToRun, sizeof(activeCommand)); //set the setup commands to be active
activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]);
...
Later in the program, the task that translates commands into button presses for the console actually runs one fixed array, so I figured I'd just "mark" the commands to run as active, and only ever run the active array. Only, it doesn't work as expected:
The program runs, sets up the controller, moves to the date settings and indeed starts to roll a date, but then, regardless if the next day is valid or not, it rolls forward a month, then a year and then it gets stuck moving the simulated analog stick upwards and pressing A indefinitely.
I figure the problem lies in my memcpy to overwrite the active array with the steps I want to run next, but I can't think of a way to solve it. I tried writing a function that was supposed to overwrite the active array element by element using a for loop, but this way the controller wouldn't even set itself up correctly and effectively nothing happened. Usually with any kind of output capabilities I'd try to fit in prints at points of interest, but I have virtually no way of getting feedback on my microcontroller.
Any help would be greatly appreciated.
Ignoring that doing a hard copy of the data is incredibly slow and wasteful, it is also incorrect indeed.
memcpy(activeCommand, stepsToRun, sizeof(activeCommand));
Here you need to copy the size of the data you pass on, not the size of the target buffer! Right now you end up copying more data than you have, because all of these declarations static const command rollDay[] etc get a variable size depending on the number of items in the initializer list.
The quick & dirty fix to your immediate problem would be to pass along the size:
void RunOnce(size_t size, command stepsToRun[size])
{
memcpy(activeCommand, stepsToRun, size);
and then call this function with RunOnce(sizeof rollDay, rollDay); etc.
The activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]); part is also incorrect but not the immediate reason for the bug. See How to find the 'sizeof' (a pointer pointing to an array)? and What is array to pointer decay? etc.
When you pass array to function it decays to a pointer.
RunOnce(rollYear);
Thus
void RunOnce(command stepsToRun[]) {
memcpy(activeCommand, stepsToRun, sizeof(activeCommand)); //set the setup commands to be active
activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]);
}
sizeof(stepsToRun) doesn't yield the correct result as you expected, since it is now sizeof(pointer) in function.
You will have to pass the size of the array as an extra argument to RunOnce function.

Monitor flashing when running a Windows SendInput API

Well, I certainly should go to python since I did several functions of this type, keyboard event and mouse event, but decide to try to learn the windows api.
My goal is to know when button 1 of the mouse is pressed.
I created this file in a very beginner way, it returns in mouseData only 0.
The curious thing is that whenever I run it, it flashes my monitor at short intervals in blinks, but between 1 second with it off. Very strange that, execution is not viable.
Could someone help me understand and try to execute to see if it is only here.
Code:
int main()
{
DWORD mouseData = 0;
MOUSEINPUT tagMouse;
tagMouse.dx = 0;
tagMouse.dy = 0;
tagMouse.mouseData = mouseData;
tagMouse.dwFlags = MOUSEEVENTF_XDOWN;
tagMouse.dwExtraInfo = 0;
INPUT tagInput;
tagInput.type = INPUT_MOUSE;
tagInput.mi = tagMouse;
while (true) {
if (GetAsyncKeyState(VK_DELETE)) break;
SendInput(1, &tagInput, sizeof(INPUT));
printf("KEYWORD: %d\n", mouseData);
Sleep(500);
}
system("pause");
return 0;
}
I can reproduce your reported 'symptoms' - and the effect is really brutal!
Now, while I cannot offer a full explanation, I can offer a fix! You have an uninitialized field in your tagMouse structure (the time member, which is a time-stamp used by the system). Setting this to zero (which tells the system to generate its own time-stamp) fixes the problem. So, just add this line to your other initializer statements:
//...
tagMouse.dwExtraInfo = 0;
tagMouse.time = 0; // Adding this line fixes it!
//...
Note: I, too, would appreciate a fuller explanation; however, an uninitialized field, to me, smells like undefined behaviour! I have tried a variety of other values (i.e. not zero) for the time field but haven't yet found one that works.
The discussion here on devblogs may help. This quote seems relevant:
And who knows what sort of havoc that will create if a program checks
the timestamps and notices that they are either from the future or
have traveled back in time.

qt the best way to sync files with a sqlite db

I'm looking for the best way to sync files in some directories with a sqlite db.
First of all I use a thread that recursively look for files filtered by extension and add they do my db.
Next I use QFileSystemWatcher to watch if files change and it's work well.
The problem is that each time I run the app I don't know if the files are changed so I need to run the thread and it take 100% of cpu of one core during the execution (about 1 minute)
So how can I do to improve this algorithm?
Thanks
Regards
A993
edit:
The code is a recursive function, similar to this function that I use to count files in a directory (also this function take 100% of cpu)
int MediaScan_Thread::recursiveCount(QDir &dir)
{
int i=dir.entryInfoList(_filters,QDir::Files).count();
foreach(QFileInfo info, dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
{
QDir subdir(info.absoluteFilePath());
i += recursiveCount(subdir);
}
return i;
}
I'm working on linux but I would develop a multiplatform app.
I would iterate over one entryList() list, recursing the directories and checking the file filter on the files. There isn't an easy way to recursively search for file listings over multiple threads. But once you get the file listing, parallel processing on it should be easy.
I combined the calls for count and for the file listings to one hit on the I/O because there shouldn't be any reason to do this twice. This version will keep track of a QStringList of the query so more processing can be done later.
Using foreach on a recursive function can be problematic as a copy of the list is made so I switched to using a for-loop with iterators.
The special addition is mimicing the QDir nameFilters functionality since entryList() takes a fileFilters parameter that it uses for both directories and files (not what we want).
A feature that I omitted is a recursion depth limit to avoid searching forever.
This code sample was compiled but not tested
// declare in MediaScan_Thread and set them in constructor or wherever it needs to be:
QVector<QRegExp> _nameRegExps;
QStringList _filters;
QDir::Filters _dirFilters;
// ....
void MediaScan_Thread::initFilterRegExp()
{
_nameRegExps.clear();
for (int i = 0; i < _filters.size(); ++i)
{
_nameRegExps.append( QRegExp(_filters.at(i), (_dirFilters & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive, QRegExp::Wildcard) );
}
}
int MediaScan_Thread::recursiveCountAndMatchedFiles(QDir &dir, QStringList& matchedFiles )
{
int i = 0;
QFileInfoList lst = dir.entryInfoList( QStringList() , QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot );
for ( auto itr = lst.begin(); itr != lst.end(); itr++ )
{
QFileInfo &info = (*itr);
if (info.isDir())
i += recursiveCountAndMatchedFiles( info.absoluteDir(), matchedFiles );
else
{
QString fileName = info.absoluteFilePath();
for (auto iter = _nameRegExps.constBegin(), end = _nameRegExps.constEnd();
iter != end; ++iter)
{
if (iter->exactMatch(fileName)) {
i++;
matchedFiles << fileName;
break;
}
}
}
}
return i;
}

SDL: how to stop audio - not resume, which SDL_PauseAudio(1) does actually?

Developing iOS application which uses CoreAudio framework, I am dealing with IMHO nonsense behavior of SDL reg. playing audio. SDL plays audio in loop, and only way how to trigger playback is to call SDL_PauseAudio(0), and the only way how to stop it (without other side effects, which I won't talk about here) is to call SDL_PauseAudio(1). As far as I know.
What is the problem for me in SDL here? Simply - next call to SDL_PauseAudio(1) actually RESUMES the playback, causing the framework to play some mess *before asking for new sound data*. This is because of the way how SDL_CoreAudio.c implements the playback loop.
It means, that SDL does not implement STOP, it implements just PAUSE/RESUME and incorrectly manages audio processing. It means, that if you play sampleA, and want to play sampleB later on, you will hear also fragments of sampleA while expecting just to hear playback of sampleB.
If am wrong, please correct me.
If not, here's my diff, that I used to implement also STOP behavior: as soon as I finish playing sampleA, I call SDL_PauseAudio(2) so that playback loop quits and next call to SDL_PauseAudio(0) starts it again, this time by playing no mess from sampleA, but correctly playing just data from smapleB.
Index: src/audio/coreaudio/SDL_coreaudio.c
===================================================================
--- src/audio/coreaudio/SDL_coreaudio.c
+++ src/audio/coreaudio/SDL_coreaudio.c
## -250,6 +250,12 ##
abuf = &ioData->mBuffers[i];
SDL_memset(abuf->mData, this->spec.silence, abuf->mDataByteSize);
}
+ if (2 == this->paused)
+ {
+ // this changes 'pause' behavior to 'stop' behavior - next
+ // plyaing starts from beginning, i.e. it won't resume
+ this->hidden->bufferOffset = this->hidden->bufferSize;
+ }
return 0;
}
I am shamed that I edited SDL code, but I have no connection to authors and haven't found any help around. Well, it is strange for me, that no one seems to need STOP behavior in SDL?
A way around your issue is for instance to better manage your audio device with SDL. Here is what I suggest :
void myAudioCallback(void *userdata, Uint8 *stream, int len) { ... }
SDL_AudioDeviceID audioDevice;
void startAudio()
{
// prepare the device
static SDL_AudioSpec audioSpec;
SDL_zero(audioSpec);
audioSpec.channels = 2;
audioSpec.freq = 44100;
audioSpec.format = AUDIO_S16SYS;
audioSpec.userdata = (void*)myDataLocation;
audioSpec.callback = myAudioCallback;
audioDevice = SDL_OpenAudioDevice(NULL, 0, &audioSpec, &audioSpec, 0);
// actually start playback
SDL_PauseAudioDevice(audioDevice, 0);
}
void stopAudio()
{
SDL_CloseAudioDevice(audioDevice);
}
This works for me, the callback is not called after stopAudio() and no garbage is sent to the speaker either.

Resources