A large part of BDSM lifestyle is the "SM" part - namely, a desire by two sides of a couple, to inflict pain on another, or have pain inflicted on them (if done right, obviously in a consensual mannerobviously in a consensual manner, duh). Often, this is done in ways that would - outside the context of BDSM relationship - be classified as a crime (assault, battery, etc...). Clearly, this produces a sizeable legal risk.
As such, is there a way for a "S" partner in a relationship (the one inflicting pain), to protect themselves legally in a reasonable way in either the case of third-party exposure (e.g. some nosy person calls the cops on the couple); or worse yet, the relationship breaking down and the "M" partner of the relationship filing charges over what they supposedly consented to previously? Just to re-iterate, the scope of the question is activity that is (at the time it happens) fully consensual.
In general societal context, obviously there is a way to engage in consensual violence without being charged - for example, a boxer or martial artist would never be charged for participating in a martial arts competition or training, which involves acts that - outside of them - would be criminally penalized.
Is there a way to do that in a BDSM relationship context - that would actually stand up in a judicial setting? In other words, anyone can sign any "BDSM contract" (probably the only thematically accurate BDSM related topic in the otherwise deplorable "50 shades" series); but did any such contract ever stand up in court when one of the partner was charged with perpetrating violence on another?
I'm mostly interested in an answer related to criminal justice system; but an answer covering civil charges from one partner on another also would be welcome, if the two answers differ. Jurisdiction is USA, if more precision is needed let's say New York City where BDSM is common enough that things like this probably actually made it to court.