'ffmpeg audio encoding based on codec and not on stream identifier

I have an RTSP Stream with one video stream and three audio streams as the source. Two of the audio streams are encoded with .mp2 and one is encoded with .ac-3. I want to convert the .mp2 streams to AAC. This would be easy if the .mp2streams would have the same stream identifier every time I start ffmpeg, but unfortunately the stream identifiers change. This means sometimes the two .mp2 streams are 0:a:0 and 0:a:1 and the next time they are 0:a:1 and 0:a:2.

Is there an option to re-encode only the .mp2 streams and keep the .ac-3 stream untouched?
I should probably also mention that this encoding is used for live TV so it is not an option to produce intermediate files or have several ffmpeg commands.



Solution 1:[1]

Try

ffprobe -show_entries stream_tags -select_streams a INPUT_URL

and see if there are any stream tags (metadata) that distinguishes mp2 streams. Then you can use the metadata stream specifier to selectively set re-encoding:

ffmpeg ... -c copy -c:a:m:{name}:{value} ac3 ...

where {name} and {value} are the name and value of the tag, respectively.

Reference on stream specifier: https://ffmpeg.org/ffmpeg.html#Stream-specifiers-1

If there isn't any usable tag, your only solution likely is to run ffprobe first to identify the stream # before running ffmpeg.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1