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).
is '1' a typo? looks like it shall be '-1' (EOF). if it's -1, make if ch < 0.