@pitaj it's all about efficiency. I have two options. The first is replacing the uri before markdown parsing. The second one is working with resulting HTML when I need to replace the whole a>img subtree with a>picture>[source, source, img] keeping all its attributes, CSS-classes and so on.
Keep in mind, we are inside parse.post hook. It basically runs every time each post is rendered (leaving caching aside). I believe, building of DOM subtree will be too wasteful in terms of CPU time. Regex for HTML-code will be more complex and less reliable as well. It can be done easily with client-side script, but it's a bit undesirable to me.
Any suggestions for altering the HTML are welcome, though.