It went off as he was fumbling with it trying to get it back in his pocket. He pulled the trigger. He dropped it after he shot himself.
Cops usually carry their firearm in a holster, not loose in their pocket like he had it. And (hopefully) they train on how to put it back in the holster without it firing--things like keeping your thumb on the hammer and your finger nowhere near the trigger get drilled into anyone who carries a gun in a holster. Or at least, it should.
This guy has his gun loose in his pocket, pulls it out while looking for something else, and then shoots himself fumbling with it trying to get it back in his pocket -- damned good thing he didn't shoot the bystander!