Thirty thousand on a $4M listing is high but not unheard of, and yes, in most cases it's the listing agent's money going out first.
Here's roughly where it goes. Photography and film for a large home commonly lands somewhere between $3,000 and $10,000 depending on how much video is involved. Staging a vacant luxury house is usually quoted as a setup fee plus monthly rental, and $8,000 to $15,000 for three months is an ordinary quote at that price point. Then there's print and digital placement, a printed brochure, and often an event for other agents. Some brokerages have a marketing budget or will co-fund, and some will advance the cost and recover it from the commission at closing. That varies brokerage to brokerage, so it's a question to ask before you sign with one.
On the last part of your question: if the house doesn't sell, that money is usually gone. The commission only exists if there's a closing.
The part that catches people out is the listing agreement itself. Some include a clause letting the agent recover documented marketing spend if the seller withdraws the property or refuses to sell at an agreed price. Whether that clause is enforceable and how it's worded varies by state, and it's the kind of thing to have a real estate attorney read rather than guess at. Ask any brokerage you're talking to how many of their luxury listings expired unsold last year. That number tells you how often the thirty thousand comes back.