xbmc/xbmc — pull request #2065 by sandsmark (2013-01-12 15:46:29+00:00)
Title: Drop played parts of video files from the fs cache.

Patch by Steinar H. Gunderson:

This patch fixes a persistent problem I've been seing on my Linux HTPC
in that if I adjust the volume from the XBMC Android remote, the video
glitches for a few (4–5) frames. Seemingly this is because loading the
video file has caused the graphics for the volume control to be swapped
out (it does not happen if I recently used the volume control).

One could argue that the right fix for this would be to reduce
/proc/sys/vm/swappiness, but it might not seem reasonable to expect
end-users to fiddle with VM parameters (and the user might not even have
root access). I view this fix as complimentary in nature.

What we do is to use posix_fadvise() to tell the kernel that previously
read parts of the video file will no longer be used, causing it to drop
those from its buffer cache. This makes other things, like in my case,
the volume control graphics, stay cached. This is, of course, assuming
you don't have other processes that trash your cache, but as long as
XBMC is running relatively undisturbed, this shouldn't be a big problem.

The patch is conservative:
* We only drop data after we've read 16MB past it. (This counter is
reset on seeks.)
* We never drop data from the first 16MB of a file (this makes sure we
don't drop _anything_ from files <32MB, ie. graphics, configuration
files, etc.).
* In order to avoid making tons of extra syscalls, we only drop in 1MB
chunks.

Unfortunately Linux as of 3.1.0 has no way of just _hinting_ that we
will no longer need these parts -- when we issue posix_fadvise(), the
data is immediately and unconditionally dropped from the buffer cache.
(If you read the manpage, it might seem otherwise, until you come to the
point where it tells how these flags are actually interpreted by the
kernel.) Future kernels might remedy this.

I've tested in practice and the results are excellent; I don't see any loss of performance in playing or seeking, and I no longer have the volume control glitch problem.