How to protect yourself if your boss prefers your colleague who underperforms and gives your work to your colleague so he can take the credit for it in front of others, and your boss blames his mistakes and your colleagues on you
I'm not sure there is much you can do to protect yourself in the situation you describe.
Make sure, however, that your perception that your colleague underperforms is an accurate one. It sounds as if the boss thinks that it YOU who is underperforming. See if you can get some honest, unbiased feedback about how you are performing.
Even if you are not performing up to a level of excellence, giving your work to someone else in front of everyone else is not a good management action, so it would seem that it is time for you to move on.