Why am I more "musically" creative in the last 30 seconds before falling asleep? I am a music producer and often my "best" pieces always came to my mind shortly before I fell asleep. Sometimes I actually grab a recorder, hum the melody and finish the idea on the very next day.

My question is now: how can this be possible? In a state where my brain is supposed to shut down (and pretty much does) it is literally exploding out of ideas. I also feel a huge increase in euphoria in these very moments but I can't really tell whether this happens before or after I get the idea for a certain sound/melody.

Might it be that my creativity is "blocked" all day until my brain finally drops all obstacles which then makes way for my creative flow? Or is it that no new input needs to be processed as I lay in total darkness and silence and therefore new "material" to process isn't coming in which leads my brain to "invent" something?

This doesn't happen every time but most often when I am very tired and don't need longer than 15 minutes to fall asleep - usually this is a matter of hours for me, hours in which I am not productive at all.
This is quite a well documented phenomenon - stereotypically these moments of creative insight occur in the shower. A google for 'psychology aha moment' or 'neuroscience creative aha' will give you some articles, in Psychology Today for instance, talking about this.

One characterisation of thought is that links between neurons are created and by travelling down the intricate pathway, you have the thought. A lot of conscious thought is driven by "picking" the "quickest" path and travelling down that, as it is economical in terms of energy use.
One understanding of creativity is that it is combining of existing ideas in novel patterns. When you enter a more relaxed state, or even just a more distracted state such as showering or exercising, your brain is free to try novel combinations as you are not consciously driving it down specific well-worn pathways (the "easy" paths).

Mark Beeman has done research on this, which he calls it insight. For more information, see the article he co-wrote "The Aha! Moment: the Neural Basis of Solving Problems with Insight".

For another explanation, Alice Flaherty has done research linking these moments to dopamine release, which is more abundant in our brains when we relax. For more information see the publication "Frontotemporal and dopaminergic control of idea generation and creative drive".