Refactor searching for the SOI marker of inline JPEG image streams

This patch refactors the approach used in PR #5286 to be more generic (and also let us remove one `TODO` from the codebase).