Ad system like facebook & yt without 3rd party

Can someone lead me in the right direction on how I can learn how to build my own in depth ad system within my app without a 3rd party. I basically want to build a ad system on the level of Facebook & YouTube, so I can make it even better & build apps that can compete with mega apps like Facebook & YouTube.