A general theory for the dynamics of social populations: Within-group density dependence and between-group processes