Log in

View Full Version : Conditional resampling with FFmpeg?


zambelli
7th December 2021, 04:54
I'm writing a batch processing script for a workflow which requires all audio sources to be converted to 48 kHz stereo before transcoding, with one caveat: if the source sample rate is < 48 kHz, I don't want to upsample it to 48 kHz, I'd like to pass it through at its native sample rate.

So if the source sample rate is > 48000 Hz, I'd like the command line to be something like this:
ffmpeg -i "%sourcefile%" -af "aresample=resampler=soxr:precision=33:osr=48000:osf=flt:ocl=stereo:matrix_encoding=dplii" -acodec pcm_f32le -f wav
but if the source sample rate is <= 48000 Hz, I'd like the command line to be something like this:
ffmpeg -i "%sourcefile%" -af "aresample=resampler=soxr:precision=33:osf=flt:ocl=stereo:matrix_encoding=dplii" -acodec pcm_f32le -f wav

Is there a way to do this with just a single FFmpeg command line that conditionally inserts osr=48000 into the filter parameters based on the source sample rate? I think I'm looking for a solution analogous to using in_w and in_h constants in video scaler filter, but as far as I can tell there is no in_sample_rate equivalent I could use with the aresample filter.

therube
16th December 2021, 19:40
Can't you check the sample rate ahead of time & branch in your script to the wanted ffmpeg line based on its' response?

ffprobe -loglevel error -select_streams a -show_entries stream=sample_rate -of default=noprint_wrappers=1:nokey=1 myfile.mp3 (https://stackoverflow.com/questions/44692145/using-ffmpeg-in-a-script-to-detect-and-fix-mp3-with-sample-rate-44-1k)

In my case, on my test, it returned "44100".

From there, depending on OS, or tools used, compare the returned result to your threshold (48000) & branch based on that.

pseudo code:

set answer = `ffmpeg...`
if %answer .lt. 48000 goto leaveasis: else goto osr48000:

Reino
2nd January 2022, 02:29
I don't know if this can be done with an FFmpeg command, but you can always do this with FFprobe in Batch:
FOR %A IN (*.wav) DO @(
FOR /F %B IN ('ffprobe -v 0 -show_entries stream^=sample_rate -of default^=nk^=1:nw^=1 "%A"') DO @(
IF %B GTR 48000 (
ffmpeg -i "%A" -af "aresample=resampler=soxr:precision=33:osr=48000:osf=flt:ocl=stereo:matrix_encoding=dplii" -acodec pcm_f32le -f wav [...]
) ELSE (
ffmpeg -i "%A" -af "aresample=resampler=soxr:precision=33:osf=flt:ocl=stereo:matrix_encoding=dplii" -acodec pcm_f32le -f wav [...]
)
)
)

zambelli
3rd January 2022, 21:48
I ended up going with exactly this kind of solution: use FFprobe to dump stream metadata, parse it, pass the right sample rate value to the FFmpeg command line.
It's a pity there's no easier way to do that, given how much flexibility is built into other FFmpeg filters like video scale.