You're correct that they're not doing live transcoding when a video is played. That's way too expensive in every regard. There are still ways to embed ads dynamically into the video without requiring live transcoding. They likely have 5-10 qualities they encode to, and segment the video into 10s segments, so a 5 minute video would be cut into 30 segments, and then each of those files encoded to multiple qualities upon upload.
That way when playing, if your Internet gets slow, the player can seamlessly downgrade to another quality. These small files concatenated together appear like one long video. Adding some ads served from the same servers as the content could be done dynamically for each request and be difficult to block without impacting the video content delivery, since you can't have uBlock Origin block the domain hosting the content.
Realistically, they probably don't do this approach because you don't know if the ad was loaded because of buffering, but never viewed, so the ad network gets less metrics and therefore the ads are less valuable. Also, I would bet the content upload and distribution team are completely separate from the ad team, so that cross collaboration is more difficult to implement.