A nonabelian trace formula