This decision is made by the official scorer, as described in Section 10 of the Official Baseball Rules.
The official scorer's role is to make unbiased decision about how each play should be recorded. They typically sit in the press box so that they can review plays from a variety of angles and in slow motion.