Issue title: [Android] Simultaneous button presses don't produce the expected behavior
 Issue body: Tested with:
TMNT3 (Nestopia)
TMNT4 (Snes9x)
SFIII3 (FBA)

on:
NVIDIA Shield Portable (built-in controller)
NVIDIA Shield Portable (8bitdo NES30 Pro)
NVIDIA Shield Console (nvidia controller)
Google Nexus 7 2013 (DS3)

Expected behavior:
pressing B + Y in SFIII3 or TMNT4 should cause a GRAB or the Special Move respectively, pressing B + A in TMNT3 should produce the special move but it only works one time out of 20 or so.

Tested on windows too and it works just fine there, also tested some native android games with controller support and it worked fine too.

 Comments: 
 Comment 0: Heh, I've noticed this too but had always just passed it off as my own incompetence and / or the controllers in question being very finicky about simultaneous button presses.  Glad to know it's probably not just me! :p
 Comment 1: I'm having the same problem on my Retroarch android.
I was playing the PS version of tekken 3 and I've noticed that grab didn't work.
Went into the practice mode and I was able to find that simultaneous button press just doesn't work.
(In practice mode you can see what buttons you've pressed)
It only works about one out of twenty times. It seems that the input window for the simultaneous press is very short.
When using epsxe to play tekken 3 the grab works fine. So it seems to be a problem of retroarch input.
This is the hardware I'm using.

LG Vu III (F300)
Dual Shock 3
 Comment 2: Are you using a real gamepad or just touch?
 Comment 3: I'm using a real gamepad. The sony dual shock 3. The opener of this thread also seems to be using real gamepads.
 Comment 4: I recommend using the PS1 version of Tekken 3 for testing.
You can check your input in the practice mode.

 Comment 5: Same problem here, trying Final Burn Alpha with controller plugged into USB. Can't grab, overhead, taunt, or do EX moves in Street Fighter III: Third Strike, and can't roll, blowback, max, etc in King of Fighters.
 Comment 6: Could this be related to this commit?
0ba45d457ef62e82f79e97d2be76e3cc56b47fea
 Comment 7: not likely it started way later than 2012
 Comment 8: Also suffering from this problem. Using Xiaomi Bluetooth game controller on my M8S Android box. No problem using the same controller in Windows or Linux version of retroarch, or other native Android apps.
 Comment 9: I confirm this issue using Nvidia Shield Portable with Kitkat. The bug is present in all cores and makes most emulators pretty much unusable on Android, especially with fighting games. The bug prevents the system from recognizing two button presses at the "same time," Golden Axe Genesis A+B is a good test. I can certainly hold jump and then press attack and that gives the expected "slash while jumping" action, but the overhead slash that happens on simultaneous down press of A and B does not work.

Maybe the Android polling code has a slight delay between recognizing button 1 and button 2 "down" action, maybe there is one frame lag or something. 

The code is here:
https://github.com/libretro/RetroArc...ndroid_input.c

I think the bug is probably in the functions
android_input_poll_event_type_key,
android_input_poll,
or
android_input_poll_input 
(sic)

But I cannot see anything wrong immediately, unless it is a matter of delay caused by the processing of all the different types of events. In the older versions, only input events where processed in the pollAll loop, now it is a bunch of events with different types.
 Comment 10: In my opinion this is the most important bug on RA android, I tried to look at it but I don't really know how to fix it.
The only people that really know their way around the android driver are @ToadKing and @Themaister I think. Would be great to have this fixed for 1.3.2
 Comment 11: I have this issue with most cores, but simultaneous inputs work on mGBA, FCEUmm, Nestopia, and Gambatte. I tested with 8bitdo Zero and a logitech keyboard on a Samsung Galaxy Core Pro. 

TMNT III behavior is actually correct. Despite what the manual says, just pressing A+B doesn't do the move. The move is done by pressing jump while attacking and then pressing A+B. I was also confused by TMNT II until I tried the cart on my toaster NES. The A+B slash only works after attacking or landing from a jump. The odd thing is that the JP version of TMNT The Arcade Game has the input as just A+B. Final Fight GBA is a similar oddity. Unlike every other version of Final Fight, the special move can only be done by holding one button and pressing the other.  

I tested Double Dragon II, River City Ransom, and Mighty Final Fight and they all recognize simultaneous button presses. I also tried the GB Double Dragon, King of Fighters EX2 GBA, and River City Ransom EX GBA. I was able to do the jump in Double Dragon and RCR and summon strikers in KoF EX2. 

I also noticed that simultaneous inputs don't work with some of the overlays, though they work with most of the flat overlays.  

 Comment 12: it's arelady defined, it's a RetroArch issue not a core issue so the point stands.
The only reason some games might recognize them is that the window to register both presses might be longer, but that's it
 Comment 13: Anyway, my point is that some cores do recognize simultaneous button presses and that TMNT III works fine in Retroarch. 
 Comment 14: No, it's not core mooreamy@example.org.
 Comment 15: I'm not trying to argue about it being core related. I just thought it would be helpful to mention that some cores do recognize simultaneous inputs. I want this issue to be solved too, especially with the Genesis Plus EX core, which seems to be the only emulator on Android that properly emulates Sega CD. 

 Comment 16: I'm not saying you are either. It's not that the core is recognizing simultaneous inputs, it's that the game itself has a longer window for the action to be triggered. I have tested this extensively over a fair ammount of cores and devices.

Example 1: mighty final fight (nestopia)
I saw you video on twitter and yeah it looks like you can reproduce it everytime.
I tried with my NVidia Shield Portable builtin controller and with my 8bitdo NES30 Pro. If I try really hard to press both buttons at the exact same time about 70% of the time it ends up throwing a jumping kick.

Now, If I instead press B and then A but really quickly the special always works.
This means that the game allows a window of more than "exactly the same time" to trigger the special move, not that simultaneous button presses are being registered correctly

On PC it "just works" using the trick, or trying to press both exactly at the same time.

Example 2: tmnt III (nestopia)
this move is really tricky, if you press both at the same you're most likely gonna end up throwing a punch, but if you press A and then B quickly (before the character actually jumps) it works 100% of the time.
On PC the same applies, this move actually needs a little bit of jump before triggering correctly it seems

Example 2: tmnt iv (snes9x)

Apparently this game requires the inputs to be triggered exactly at the same time, I tried my best on android and I only managed to trigger the move 1 out of 20 times.
On PC it just works

Example 3: sfa3 (fba)

Fighting games usually have far strickter input requirements
On PC it just works (XY for throws)
On android... I dare you, pull out throws consistently
 Comment 17: Thanks for the info. I also had the same problems with FBA and SNES 9x. I had to do the hold and press method for Final Fight and only got Batman's cape swipe 1 out of 10 tries (or something along those lines) in Batman Returns SNES. Couldn't do the backwards slash in GA1 Genesis or arcade or the backwards jump attack in Golden Axe II using the Genesis Plus GX core for the Genesis games either. Thanks for the input for TMNTIII too. It's much easier pulling that move off now and the instruction manual doesn't make it clear how to do it. 
 Comment 18: I noticed something really odd when playing Tekken 2 PSX in practice mode on RetroArch. When buttons are pressed simultaneously, it registers another button before registering the buttons pressed.  

 Comment 19: playing on android? another button instead of the correct one?
or is it something like triangle -> triangle + circle
 Comment 20: On android. It's like the latter. 
 Comment 21: Looks like the input issue is still there as of the April 7th nightly. Still not able to do simultaneous button presses in Golden Axe. I noticed that some outside emulators like classicboy and MAME4droid lack the button press issue. 

I know it's not the cores causing the issue, but I'm still under the impression that some cores are affected differently. I'm able to do simultaneous button presses consistently in some NES, GBC, and GBA cores and input response seemed better than some outside emulators. 
 Comment 22: Has anyone tried changing the joypad driver to hid? Or messing with the input settings too see if it makes any difference? Man this bug is major I want to use retroarch on Android as my only app for emulators but I am forced to use standalone android emus because of this bug.
 Comment 23: The controller doesn't work at all in Retroarch when I switch to hid. I get the same behavior with Moga Hero Power and 8bitdo Zero. The former is definitely a hid controller. 

I read on the forums that simultaneous inputs work on overlays, but that is not my experience. I only got them working with the in between presses on the flat overlays, but simulateous presses still don't work with the buttons themselves. My Android does support multitouch. It's limited, but I was still able to to simultaenous presses with two buttons in other emulators.

 Comment 24: Apparently only external controllers have this issue, touch input works perfectly for some reason. Sucks for users with tablets with builtin controllers like me.

 Comment 25: [quote]
Apparently only external controllers have this issue, touch input works perfectly for some reason. Sucks for users with tablets with builtin controllers like me.[/quote]
I just said touch input isn't working for me, so I don't understand why I'm being told the opposite of what I said. I tested multiple times in Retroarch. 

 Comment 26: The issue is as follows:

On every frame the input state is cleared, so if the inputs aren't performed exactly at the same frame it won't register (unless the game has a longer windows for multiple inputs)

The only reason it works on some overlays is that some overlays have combo buttons.
Most of the comments here are wild theories and misinformation, the issue is well known and documented, but noone has really looked for a fix.
 Comment 27: Really? Because I have tested almost all gamepad overlays on retroarch 1.3.2 and the simultaneous presses work perfectly without using the combo buttons, a lot of people have reported the same in the forums: http://libretro.com/forums/showthread.php?t=5116&page=2
I am surprised noone has looked for a fix for such a major bug that affects all external controllers, it makes a lot of games unplayable.
 Comment 28: I'm sorry if I came off the wrong way, but that was a bit harsh to mention "wild theories and misinformation". Some of my posts were in reply to what was said on the Retroarch forum, which I would be replying to if I got a confirmation email. The first post in this topic didn't make it clear that you knew the input of TMNT III wasn't just A+B or that the cause of the problem was known. Posts on the forum do make it clear some devices are affected differently. One poster said the problem was fixed when he switched to a different android UI (forgot exactly what it was called). 

 Comment 29: Use a gmail account to register, outlook and others do not work.
 Comment 30: Will do. Thanks. 

 Comment 31: How would you push them frame perfect even on a console?

 Comment 32: @Brianvgplayer didn't mean to be harsh either sorry, but yeah there are some wild theories, and more precisely, this issue is about physical gamepads.
Anyway, I hope I can get maister to look at this the next time he shows up, he had some theory.
 Comment 33: Hoping maister can find a solution. Does anyone know what version of retroarch doesn't have this bug?

 Comment 34: Both Mame4droid and MD.emu use passive input handling in java with onKey() or onKeyDown() and onKeyUp(),where as retroarch polls an event queue.

[Mame input code](https://sourceforge.net/p/mame4droid/code/HEAD/tree/Reloaded/trunk/android/src/com/seleuco/mame4droid/input/InputHandler.java)
[MD.emu input code](https://github.com/Rakashazi/emu-ex-plus-alpha/blob/6c27891bb6e3cafbdc3b7dd2c0bf66656c50d0ea/imagine/src/base/android/java/sdk-9/imagine/MOGAHelper.java)

Did retroarch ever do this(possibly before the android ui was replaced with glui),because if it did that is probably the last version that worked.

I looked at the input code for retroarch and it is reading from an event queue and alot of work is being done for every keypress,if that work takes 3/4 of a frame if you push 2 keys at the same time they will be put in the queue at the same time but it takes 3/4 of a frame for each so one will be registered on the next frame unless you push them half way through a frame.

This explains why some devices aren't affected(there faster) or why kernel parameters(as stated in the forum) would affect it.

 Comment 35: That is good info, so why would the simultaneous button input work using the gamepad overlays? Does retroarch handle that input differently?
 Comment 36: I don't know why but most likely it is because the overlay code is triggered after all the events are processed.Compared to the button input that |= the button in as soon as it gets the event.(I haven't looked at the overlay handler that much so don't hold me to this.)

So with the the button input the game could read the pressed buttons before all the events are finished but the touch input updates all the buttons at once and is dependent on there being no events in the queue(to have the newest touch data).

My advice is to log all the changes by the events and apply them all at once when the queue is empty since the very nature of a queue is that 2 things cant have the same spot even if they happened at the same time.

Also here are some optimizations to the key input.

   while (AInputQueue_hasEvents(android_app->inputQueue))   //the second performs both functions
   {
      while (AInputQueue_getEvent(android_app->inputQueue, &event) >= 0)
      {
        ...
      }
   }

In android_input_poll_event_type_key() the volume keys will act as volume keys even when mapped and if they cant be mapped you should check before putting them in the keymap.
 Comment 37: I don't really understand the input code but as far as I understand the whole button handling happens at L986 of android_input.c, which leads to 

android_input_poll_event_type_key
There is a comment in that function:

`/* some controllers send both the up and down events at once
    * when the button is released for "special" buttons, like menu buttons
    * work around that by only using down events for meta keys (which get
    * cleared every poll anyway)
    */`

The keypress or release is set here:

```
   switch (action)
   {
      case AKEY_EVENT_ACTION_UP:
         BIT_CLEAR(buf, keycode);
         break;
      case AKEY_EVENT_ACTION_DOWN:
         BIT_SET(buf, keycode);
         break;
   }
```

But my guess is that the buffer is empty every time.
Sadly debugging on android is a PITA, it should be easy enough to print the values that android_keyboard_state_get(port) returns.

 Comment 38: debugged a bit but I don't really understand what's going on.
if I hold a button, for example B

BIT_SET(buf, keycode_for_b); is called endlessly, shouldn't be the case, that event should have been handled by then and it shouldn't keep setting that bit.

If I then press and hold another button, for example... Y then it calls BIT_SET(buf, keycode_for_y) once, and stops spamming BIT_SET(buf, keycode_for_b).

If I press both buttons once at the same time it would seem it sets the two bits on a single frame but I'm not sure of it I didn't log the frame number. I think it may be the case, maybe some variable is resetting on every call or something.
 Comment 39: The constant repeating is probably because you need to call finishEvent regardless of predispatched status.


         if (!predispatched) //this if should be removed
            AInputQueue_finishEvent(android_app->inputQueue, event,handled);

You can remove the predispatching altogether,all it does is send the keys to the active ime(that retroarch doesn't even use).
 Comment 40: I thought so too, and I added the finish event line, that's the first thing
I tried, but it caused segfaults so I reverted that

On Mon, Apr 25, 2016 at 10:56 AM, meepingsnesroms <mooreamy@example.org>
wrote:

> The constant repeating is probably because you need to call finishEvent
> regardless of predispatched status.
>
>      if (!predispatched) //this if should be removed
>         AInputQueue_finishEvent(android_app->inputQueue, event,handled);
>
> You can remove the predispatching altogether,all it does is send the keys
> to the active ime(that retroarch doesn't even use).
>
> —
> You are receiving this because you commented.
> Reply to this email directly or view it on GitHub
> <https://github.com/libretro/RetroArch/issues/2043#issuecomment-214414824>
>

 Comment 41: Can you give me the details on the segfaults.(I am trying to compile the source myself to try to work on it but haven't gotten it compiling yet.(I don't need help,just time))
 Comment 42: actually we have a staging branch that you can toy with to test stuff, just send a PR to that branch, I can merge and a few minutes (or several minutes depending on the buildbot workload) a build will be uploaded.
IIRC this was the build with the segfault
http://bot.libretro.com/nightly/android/2016-04-24-RetroArch_devel.apk
 Comment 43: I installed that build and the issue is not fixed but there where no segfaults.(tested with golden axe for genesis)
 Comment 44: maybe it wasn't that one then idk, I don't keep builds per-commit so it could have been overwritten
 Comment 45: (I originally posted this in another thread, so apologies if I repeat what some of you already mention earlier)

I think the problem occurs because multiple buttons need to be registered within a single frame. When looking at runlook_iterate in runloop.c, I'm guessing that button presses are registered by comparing changes to the input states in the current frame compared to the input state in the previous frame (cmd.state[0] and cmd.state[1]). So in order to register multiple buttons pressed at once, they would have to both have changed state during that single frame.

I think the problem might occur because input events are handled faster on Android so they don't have time to queue up and be handled as a bundle but are instead handled individually in separate frames.

I tried experimenting with timers in android_input_poll in android_input.c to try to force input events to only process them every 100ms or so, so there would be time for them to queue up before they are handled, but it didn't work out the way I had hoped.

Any thoughts on this?

 Comment 46: That sounds like how it should be. As long as the runloop checks the button state every frame and does not skip a frame. It would help to log the button bits together with the current frame number once every frame to check the exact timing.

I think fr500 must be onto something though because he mentioned the inconsistent spamming of the bit_set function that does not happen when two buttons are pressed simultaneously.
 Comment 47: Well, if the runloop checks for button presses by comparing the button state changes between frames, wouldn't you have to press both buttons within the time of one frame change in order to have it register as a simultaneous button press?

Eg. at 60 fps, you would have to press both buttons within 17ms for both of them to register in the same loop?

 Comment 48: Actually on average I think it'd have to be within 8 ms of each other (half a frame) even, since, in the worst case possible case, you can have one button press just before the poll loop and one just after (i.e., <<1 ms of each other) and be registered by RA as occurring on separate frames instead.  AFAIK, none of this explains why this is only an Android issue though - don't all the input cores work in pretty much the same manner?
 Comment 49: I've found it difficult to get a good overview of the input drivers, but from what I can tell, the Android input driver is implemented mainly as a universal keyboard driver and doesn't really follow the structure of the other drivers.

This also made it tricky when I was extending the Android driver with keyboard functionality, because the normal keyboard structures were already in use but had been twisted into handling gamepads.

For example:
- the gamepad polling should be placed in android_joypad.c
- gamepad button states should be maintained in android_joypad.c but right now they are maintained in keyboard_event_android.c in a variable that would normally be used for keeping track of keyboard state, but which has now been changed into an array of 8 keyboard states to keep track of gamepad states instead

And I can go on :)

The right step would probably be to do a complete overhaul of the Android input driver so that it respects the same structure that the other input drivers do. I worked a bit on doing this when I was implementing the keyboard functionality, but it would be such a large change that I was worried I might break a lot of stuff so I dropped it.

TLDR:
The Android input driver is very different from the other input drivers.

 Comment 50: Yeah @twinaphex has mentioned that there's a need to rewrite that driver (actually several) but as you said it's... well difficult.

Actually there is one thing on the android input driver that I like better than in any other driver, and that is that gamepads are bound on a button press.

Example, connect DS4, does nothing, press X, it gets bound to port 1, connect another, does nothing, press TRIANGLE, gets bound to port 2.

Sadly as you said, it's a big project. Remember there wasn't native gamepad support on android till relatively recently, and any changes we do should be tested on a broad variety of devices of all ages, sizes and running different android versions...

And on top of that, you have to go through JNI... It's really a pita.

I think @Googer's reasoning could be accurate, I think all JNI code is called in another thread? (I might be wrong), maybe the eventqueue is filling/emptying faster than we're polling?

Anyway

 Comment 51: I successfully removed all predispatch code but the bug was not fixed.
(the segfault was likely a use after free because the event was freed then the ime used the old pointer given by the predispatch)
I got everything compiling so now i can try to fix it.
 Comment 52: If I remember correctly there was a problem with keyboard input being registered twice when I didn't check for !predispatch. You can check for this by starting a game in ScummVM that uses keyboard input, eg. the original version of Kings Quest 1.

Could you check if this bug has been reintroduced after you removed the predispatch code?

 Comment 53: I did not see it,I tested it with dosbox dos terminal and usb otg keyboard.

 Comment 54: I've implemented a proof of concept solution/workaround in my fork:
https://github.com/diablodiab/RetroArch/commit/769c12717449da4d0308237fe340851ec0b89048

You can download a compiled .apk here:
https://www.dropbox.com/s/41t3lbjfmk2onfo/retroarch-release.apk?dl=0

The basic idea is this:
Button input is registered into a temporary input state which is flushed to the normal input state every ~67ms. This provides a small window for pressing more than one button which are then sent together to the normal input state within a single frame.

I've tested it in Golden Axe and it does seem to work.

I'm sure it can be implemented in a better way, so I'm referring to it as a proof of concept of the thoughts i had on queueing inputs and flushing them to the input state at a certain frequency rather than immediately.

What do you think of this approach?

 Comment 55: I was just working on doing this!
It is perfectly fine,we might just be polling too fast for android to keep up.
 Comment 56: Can you test what happens if you flush every 15 m instead, to get at least one update per frame? Although it is great progress to find something that solves this problem, the 67ms delay is too long to be a viable solution. Many retro games depend on updating the input every frame. Street Fighter 2 comes to mind.

If 15ms doesn't work, can you test the smallest possible delay that does work?
 Comment 57: I initially lowered the flushing delay to 25 ms but it became increasingly difficult to hit two buttons simultaneously within that window of time. I think I managed to do it once every 9-10 times I tried.

In the commit description, I referred to some articles discussing controller input delays and the reasoning behind choosing 67ms as a starting point.

The problem occurs when input is updated once per frame as that window is simply too small to be able to hit two mooreamy@example.org. My guess it that the input delay in the other drivers is higher than we expect which is why it is easier to do button combinations in those drivers.

You should try the compiled version and see for yourself if you can tell the difference.


 Comment 58: Conceptually isn't this the same as if RA only polled the controller input queue once every ~67 ms (i.e., once for every 4 frames of emulation on a 60 fps emulated core) instead of every one?  I haven't tried this yet but I could see this being a bit annoying from a responsiveness point-of-view to the user, since sometimes a button press will respond nearly instantly (if pressed right before a flush); other times it'll be close to the full buffer length (i.e., 67 ms)

Also on average this'll add another ~33 ms / 2 frames of input delay on average on top of whatever internal buffering the emulated game likely already has and intrinsic delay from the display being used. So it may work but it's definitely not optimal. :p
 Comment 59: Actually the stock input lag on android (at least on the shield) is commendable. So yeah I'm affraid this would break that.

Anyway cool you got something working I'll check whenever I have time
 Comment 60: Having actually tested this now, I can say it basically works but the large buffer actually causes another problem as well that's probably worse in a way - if you press and release a button quickly, the press can be missed altogether.  This is because both the press and release can be registered in the same buffer, so the button press is never propagated to the emulated mooreamy@example.org. ;)
 Comment 61: Could we flush the buffer exactly on frame updates(because most games probably don't check more than once per frame) then there would be no waiting.(It could be every 2 or three frames if needed)

With pushing it quick enough not doing anything,this applies to consoles too if you press and release the button before the game checks controller register.(Unless that specific console has an interrupt on button press)

 Comment 62: Correct, the only way to completely avoid that issue altogether would be to use an interrupt-driven system.  And as you say, this even applies to games being run on physical consoles. :laughing:
 Comment 63: So why does this work on other Android emulators, e.g. .emu programs, and even in Retroarch on other platforms? For example, I know it is possible in some Mame shmups to shoot 30 times a second, e.g. every second frame. But with this workaround it would be impossible to do so. Clearly there is an underlying issue that needs to be fixed and this workaround of "slow polling" bypasses that issue. In Windows I am using a controller that has a refresh polling rate of 120 Hz, and I have no problem pushing multiple buttons in any emulator. 
 Comment 64: Because they don't poll,they use a soft interrupt(onKeyDown,onKeyUp,onKey) in java that then calls C.

This is the only emulator that uses the NativeActivity,and its unoptimized because almost no one uses it or cares.
 Comment 65: Are you saying that a single poll takes longer than one frame? If that is the case, then yes, this will never work correctly.

Otherwise, if an input poll can be completed once per frame, I don't think it should matter whether we use interrupts or polling, as long as we update once per frame. 

Here's why: If we would react using interrupts, then the button bits will ideally be set as soon as they are pressed/released. However, the emulated game will only react to these button bits once per frame. So effectively from the games perspective, the key bits are updated once per frame.

If we poll fast enough (once per frame), then the same thing should happen.

That is why I think that there's an underlying issue. For example, if you look at Broglia's Java code, he is just reacting to the input events by doing:

void EmuSystem38d1:d2b4:3d06:83e8:96a5:8c2:893d:aba5handleInputAction(uint state, uint emuKey)
{
	uint player = emuKey >> 30; // player is encoded in upper 2 bits of input code
	assert(player <= 4);
	uint16 &padData = input.pad[playerIdxMap[player]];
	if(state == Input38d1:d2b4:3d06:83e8:96a5:8c2:893d:aba5PUSHED)
		setBits(padData, emuKey);
	else
		unsetBits(padData, emuKey);
}

In retroarch, the same thing is happening (but somewhere there is clearly a bug).

The only difference is that Broglia's code reacts to an interrupt, while Retroarch actively polls. We just have to ensure that the polling is fast enough.
 Comment 66: The error is probably not in retroarch,but in the nativeactivity library side of the queue.
Android might only push one keyevent to the queue per frame,but with the interrupt it just calls it for every event at the same time.

Since this is the only thing different between working and not working is interrupts vs polling,and no one else uses this library,it is most likely an os bug.

udev for Linux polls an event queue and it works too,so all that's left is that android does not provide events fast enough when you don't use the interrupt.
 Comment 67: `This is the only emulator that uses the NativeActivity,and its unoptimized because almost no one uses it or cares.`

Are you sure of this? Or do you mean this is the only emulator that uses the NativeActivity for this purpose
 Comment 68: not sure if I'm reading this correctly but it seems he reads the whole gamepad state in one call per-frame?
https://github.com/Rakashazi/emu-ex-plus-alpha/blob/6c27891bb6e3cafbdc3b7dd2c0bf66656c50d0ea/EmuFramework/src/EmuInputView.cc#L112
const KeyMapping38d1:d2b4:3d06:83e8:96a5:8c2:893d:aba5tionGroup &actionMap = keyMapping.inputDevActionTablePtr[e.device->idx][e.button];

Then he iterates over the inputs in this state
https://github.com/Rakashazi/emu-ex-plus-alpha/blob/6c27891bb6e3cafbdc3b7dd2c0bf66656c50d0ea/EmuFramework/src/EmuInputView.cc#L258
EmuSystem38d1:d2b4:3d06:83e8:96a5:8c2:893d:aba5handleInputAction(e.state, sysAction);

Ist this correct?
 Comment 69: Do any of you have an idea of the typical delay one can expect when trying to hit two gamepad mooreamy@example.org. The human factor. I'm guessing it will be very rarely that you hit them exactly at the same time.

So how much time between the two button presses would you think there would be?
 Comment 70: The game/emu in question will have already solved this problem. All retroarch needs to ensure is that the button state is polled and updated once every frame. I suspect that there is some crazy lag/delay somewhere in the polling routine that prevents this update from happening fast enough. For example ifthe polling itself takes multiple frames, then the simultaneous key presses will most often appear as two separate presses several frames apart. A simple logging of button presses together with an integer frame count number would help debug this. The logging should only turn on on a certain button press and simply output button bits and framenumber on every frame as long as some other key is held down.

 Comment 71: I'm still curious about this question.

Polling the input every frame at 60 fps will require you to press two buttons within a maximum of ~17ms - sometimes even less in order for it to be registered as a simultanous button press. I'm interested in knowing if that is what we are actually doing in those other emulators. Pressing both buttons within that timeframe - or if there is some sort of queue and flushing going on there as well to allow for button presses to stack up before they are checked (and over a time period that is longer than a single frame).

 Comment 72: If the polling routine itself is taking longer than one frame, then the buffering routine i tried to implement should fix this when I set the delay to 0.

Then the polling routine would spend a few frames going through input events and updating the temporary state which is then finally flushed. The flushing is done within one frame otherwise the hack i did would not solve the problem.

I think meepingsnesroms has the right idea when he says that "Android might only push one keyevent to the queue per frame". At least with the current way that keyevents are placed into the inputqueue.

 Comment 73: I will use "polling" here to refer to the process of "queueing up events followed by processing events".  Let's say you are pressing two keys almost simultaneously, however the first key is captured by the polling, but the second key came slightly too late when the polling already started. Now this polling takes several frames because it is slow. After the polling, the game will see a single button pressed. Only on the next polling the other simultaneous key will also be registered. To the game/emu this will look like

first key pressed
several frames delay
first and second key pressed

even though you pressed the keys simultaneously, maybe even on the same frame, this is not reflected due to the lag in polling.

The fact that Android has horrendous input lag ~100ms on most devices makes me wonder if the polling is just way too slow. The logging I described should reveal that.

 Comment 74: > diablodiab: "Polling the input every frame at 60 fps will require you to press two buttons within a maximum of ~17ms - sometimes even less in order for it to be registered as a simultanous button press."

This is simply not true. It only means that the emu/game in question receives input updates at the maximum frequency. It is up to the game/emu to decide how to deal with those inputs. The coders of the original games will already have ensured how they want to queue/handle these inputs. Original consoles used interrupts, e.g. they received input changes every frame, but this didn't mean the user had to press the buttons in the same frame. The game code will deal with this on a game-by-game basis.

 Comment 75: It would be interesting to see the results of the logging you mentioned, could you please look into this and provide the results?
 Comment 76: RSN8887's polling is the way to go. Print a high resolution timestamp when an event is processed, and the keymask each frame. Speculation is baseless without that data
 Comment 77: I've done some performance measurements of the polling function in android_input.c and it's executing much faster than one frame, so that's not the bottleneck.

However, I did find an interesting thing in the polling function:
It turns out that if you change the ALooper_pollAll call in the polling function from a non blocking call into a 1ms waiting call then the inputQueue will be filled up with more input events and it actually seems to solve the problem with hitting more than one button simultaneously.

This is the change to the code:
https://github.com/diablodiab/RetroArch/commit/58c5cc6f46ce07581e221c6e2213a76701bf19e6

Here is a binary for testing:
https://www.dropbox.com/s/41t3lbjfmk2onfo/retroarch-release.apk?dl=0

I've tested it with a bunch of games, and so far I've only noticed one side effect of this. On Nvidia Shield TV you would normally press the Nvidia button on the game controller to go into the menu. Normally this would send a keycode 84 to the input buffer, but since this is a special button that switches keycode when you hold it down it actually ends up doing both a key down and key up event during the 1ms wait. So instead one would have to use keycode 203 for that button, which is what it turns into when you hold it down.

I'm assuming that input is handled in its own thread and that the 1ms waiting in the input pulling does not have en effect on the general performance, but I would be interested to hear your thoughts on this.

Please try out the binary and let us hear.

 Comment 78: @diablodiab can you send a PR to the staging branch so all of us can test?
the buildbot builds have an automatic version code and it's impossible to move back and forth from manual builds

Thanks
 Comment 79: Done :)
 Comment 80: Awesome work I think this might be the fix we have been waiting for. Thanks diablodiab for the prompt investigation of the polling loop performance. I stand corrected.
 Comment 81: Wow so diablodiab managed to fix single-handedly the major bug everyone else failed at. You are freaking awesome man!
 Comment 82: so it's building, should be on the buildbot after a few mins.

On Thu, Apr 28, 2016 at 7:22 PM, blackman91 <mooreamy@example.org>
wrote:

> Wow so diablodiab managed to fix single-handedly the major bug everyone
> else failed at. You are freaking awesome man!
>
> —
> You are receiving this because you commented.
> Reply to this email directly or view it on GitHub
> <https://github.com/libretro/RetroArch/issues/2043#issuecomment-215600257>
>

 Comment 83: Works perfectly without the side effects of the buffering method.  I approve. :smile: 
 Comment 84: Thanks a lot @diablodiab this issue was number 1 in my list
Fixed by https://github.com/libretro/RetroArch/pull/2919/commits/58c5cc6f46ce07581e221c6e2213a76701bf19e6
{'source': 'GithubIssues', 'repo_name_with_owner': 'libretro/RetroArch', 'issue_id': 101299818, 'repo_stars': 7522.0}