If it seems like R. Kelly is on the verge of coming unhinged that's because he is -- and his music might be the only thing standing between him and a full mental breakdown.

Sources close to the embattled singer tell TMZ ... Kelly has been focusing on producing new music. We're told he sees the writing process as a form of therapy, but maybe more importantly for him at this point ... it's a distraction from his mounting legal battles.

TMZ.com

As you know ... R. Kelly was released Saturday from Cook County Jail after finally coughing up his unpaid child support. Actually, he didn't even pay ... he says a "benefactor" covered the tab.

He's still facing 10 counts of aggravated sexual abuse in Chicago, new sexual conduct allegations in Detroit and multiple federal investigations -- and we're told it's all wearing on him.

CBS

After the CBS interview aired last week -- showing Kelly ranting and crying -- many viewers thought he was faking it, or having a very real breakdown.

We're told people close to Kelly think that's exactly what will happen if he stops working on music.

BTW, the new content isn't for public consumption -- we're told he doesn't have any plans to release the music. Besides, he doesn't have a distributor since his longtime label Sony/RCA recently kicked him to the curb.

Kelly's not even recording in a proper studio -- remember, he got booted out of his infamous Chicago recording studio, so he's doing it from his Trump Tower apartment.

Point is ... the walls are closing, and we're told Kelly's on the edge.