This is definitely usually done by the hardware. If not, it makes more sense to do it on the operating system/graphics driver level.
If you insist on doing it at the application level, mesh deformation/distortion would probably be able to do what you want. I'd approach it by pasting the entire viewport to a (flat) drawing canvas, then distort the drawing canvas to achieve the desired keystone effect.
No idea about the details though.