If your PBX writes every call as an uncompressed WAV file and the recordings directory is eating the disk, this is the setup I use: a small watcher that re-encodes each recording a few seconds after the PBX finishes writing it, keeps the same .wav filename so nothing that references the file breaks, and leaves ownership, permissions and timestamps exactly as they were. A second command backfills the recordings you already have.

If you came here from a search for one of these errors, they are both covered below:

Copied!
Unable to choose an output format for '<recording>.wav.temp'; use a standard extension for the filename or specify the format manually.
Copied!
Enter command: <target>|all <time>|-1 <command>[ <argument>]
Parse error, at least 3 arguments were expected, only 1 given in string '<part of a path>'

The first is FFmpeg refusing to guess a format from a .temp extension. The second is FFmpeg reading your list of filenames from standard input as keyboard commands. The guide assumes a Linux server, root or sudo on it, and basic shell. You do not need to know anything about audio codecs yet.

Last verified: December 2026. Versions used: FFmpeg 6.1.1 with LAME 3.100 (Ubuntu 24.04 packages), inotifywait options as documented from inotify-tools 3.22.6.0 (Debian 12, Ubuntu 24.04) through 4.26 (upstream, now rewritten in Rust; the options used here did not change), rsync 3.1.0 or newer, systemd.

What Happened

The PBX at work writes one WAV file per recorded call into a directory per extension. The filenames carry the agent and the caller, so I can’t show you real ones. Storage was growing fast enough that I wanted every new recording shrunk as soon as it landed, and the existing ones shrunk once.

One constraint shaped everything: the files had to keep their .wav names, because other things look them up by that exact path. So the plan was to put compressed audio inside a file that is still called recording.wav. My first attempts used Opus. I switched to MP3, and asked for 128 kbit/s.

The first version of the watcher was inotifywait -m -r -e close_write --format '%w%f' piped into a loop that waited three seconds, ran FFmpeg into recording.wav.temp, and moved the result over the original. To test it, I moved ten recordings out of the tree and copied them back in so they would look new. Four things broke, in this order:

  1. FFmpeg could not pick an output format for recording.wav.temp. The fix was -f wav, which writes a WAV container holding MP3 audio.
  2. FFmpeg got Permission denied creating the temp file in the PBX’s directory. My fix at the time was to write the temp file to /tmp and run the service as root. The steps below avoid both, and explain why.
  3. The backfill script failed with the Parse error above, and a later version of it stalled at FFmpeg’s Enter command: prompt. The fix was -nostdin.
  4. Under systemd the service logged inotifywait: command not found and then Deactivated successfully. inotify-tools was not installed on that server.

Later I had to move about 262 GB of recordings from a backup server back to the phone server. That part is Step 8.

How It Works

Pipeline: the PBX closes a WAV file, inotifywait reports close_write or moved_to, the script checks the file is PCM and not open, FFmpeg encodes to a temp file in the same directory, mode, owner and mtime are copied, and mv atomically replaces the original. A backfill path using find and xargs feeds the same per-file step. Both the live watcher and the backfill feed the same per-file step, so a file is handled the same way no matter how it was found.

inotify events. inotify is the Linux kernel interface that tells a program when something happens to a file or directory. The man page defines IN_CLOSE_WRITE as “File opened for writing was closed.” That is the moment a recorder is done with a file. IN_CREATE fires when the name first appears, before any audio is written, so a watcher that acts on create converts a file that is still being recorded. Checked with the raw kernel API, writing a file directly produces CREATE, then MODIFY events, then CLOSE_WRITE. A program that writes a temp file and renames it into place produces CLOSE_WRITE on the temp name and only MOVED_TO on the final name. That is why the watcher below listens for both close_write and moved_to.

inotifywait. inotifywait from inotify-tools prints events as text. -m keeps it running instead of exiting after one event, -r watches subdirectories, -e picks the events, and --format '%w%f' prints the watched directory plus the filename, so each line is a full path. Its limits matter for a long-running service:

  • inotify itself is not recursive. -r adds one watch per directory, and each user has a ceiling in /proc/sys/fs/inotify/max_user_watches. Older kernels default to 8192; newer ones scale the default with RAM. On large trees, setting up the watches takes time, and events during that time are not reported.
  • The man page lists race conditions in the recursive code: events right after a new directory is created can be missed.
  • The kernel event queue can overflow, and then events are lost.
  • inotify does not see changes made by other machines on network filesystems.

On a server that runs for months, assume events will go missing. The per-file step is idempotent (running it twice does nothing the second time), and a nightly sweep picks up whatever the watcher missed.

The container trick. A WAV file is a container. Its header has a format tag that says what the audio inside is. Tag 1 is plain PCM (uncompressed samples). Tag 0x55 is MP3. FFmpeg guesses the output container from the extension, and .temp is not one it knows, hence the first error. -f wav forces the WAV container, and -codec:a libmp3lame puts MP3 inside it. The result is a legal WAV file that many programs will not play, because almost every WAV file in the world is PCM. MDN’s container table shows Firefox playing only PCM inside WAVE. file and ffprobe read the header and tell you what is really there. The extension tells you nothing. FFmpeg also refuses to put Opus in a WAV container (Codec opus not supported in WAVE format), so if the name must stay .wav, MP3 is the practical choice.

Telephone audio and bitrate. Telephone calls are usually narrowband: 8000 samples per second, one channel. Uncompressed 16-bit PCM at that rate is 8000 x 16 x 1 = 128 kbit/s. G.711 (µ-law or A-law, 8 bits per sample) is 64 kbit/s. Asking for a 128 kbit/s MP3 of a 128 kbit/s source saves nothing, and at 8 kHz you cannot get it anyway: LAME’s man page limits MPEG-2.5 (8, 11.025 and 12 kHz) to 8 through 64 kbit/s. Asked for -b:a 128k -ar 8000 on a test machine, FFmpeg 6.1.1 silently produced 64 kbit/s audio, while the WAV header still claimed 128 kbit/s, so ffprobe reported a 60-second test file as 30 seconds. Pick the bitrate on purpose and listen to the result. For speech at 8 kHz I would start at 32k.

Replacing files safely. mv within one filesystem is a rename(2) call, and rename replaces the target atomically: no reader ever finds the name missing or half-written. Across filesystems (from /tmp to the recordings disk, for example) rename fails with EXDEV and mv falls back to copy-then-delete, which is not atomic. So the temp file goes in the same directory as the original. A new file belongs to whoever created it and gets the creator’s umask, so the script copies mode and owner from the original with chmod --reference and chown --reference, and copies the modification time with touch -r so date-sorted listings and retention jobs still see the call’s real time.

Files still open. close_write means some writer closed the file, not that every writer is done. The script waits a few seconds and then asks fuser whether any process still has the file open. If one does, it skips the file. If that process is a writer, its eventual close fires another close_write. If it is only reading (a player, a backup job), no new event comes, and the nightly sweep in Step 6 picks the file up. fuser can only see processes it is allowed to inspect, which is one more reason to run the service as the PBX’s own user.

Prerequisites

  • A Linux server with a PBX that writes WAV recordings to a local filesystem.
  • ffmpeg built with libmp3lame, inotify-tools, and psmisc (for fuser). On Debian and Ubuntu: sudo apt install ffmpeg inotify-tools psmisc. Package names differ on other distributions.
  • The recordings directory, for example /var/lib/pbx/recordings. This guide writes it as <RECORDINGS_DIR>.
  • The user and group that own the recordings, written as <PBX_USER> and <PBX_GROUP>. Find them with stat -c '%U:%G' <RECORDINGS_DIR>/<some recording>.wav.
  • A backup of the recordings, or the willingness to lose them. Conversion is lossy and replaces the original.
  • For Step 8 only: rsync 3.1.0 or newer on both ends, and root on the receiving server.

Step 1: Inspect the Existing Recordings

You need to know what the PBX writes before choosing a bitrate. Pick one recording and ask ffprobe:

Copied!
ffprobe -v error -show_entries stream=codec_name,sample_rate,channels,bits_per_sample,bit_rate \
  -of default=nw=1 "<RECORDINGS_DIR>/<some recording>.wav"
Copied!
codec_name=pcm_s16le
sample_rate=8000
channels=1
bits_per_sample=16
bit_rate=128000

pcm_s16le is 16-bit PCM. pcm_mulaw or pcm_alaw means G.711. If you see 16000 Hz, the PBX records wideband audio, and you should set SAMPLE_RATE=16000 later instead of throwing half of it away. If you see two channels, check whether each party is on its own channel before you downmix with -ac 1. Then measure what you have:

Copied!
du -sh <RECORDINGS_DIR>
find <RECORDINGS_DIR> -type f -name '*.wav' | wc -l

Step 2: Test a Conversion and Listen

Work on copies. FFmpeg can also generate a one-minute 8 kHz test tone:

Copied!
mkdir -p ~/rec-test && cd ~/rec-test
ffmpeg -hide_banner -loglevel error -f lavfi -i "sine=frequency=440:sample_rate=8000:duration=60" \
  -ac 1 -c:a pcm_s16le sample.wav

Then convert it (or a copied real recording) the way the script will:

Copied!
ffmpeg -nostdin -hide_banner -loglevel error -i sample.wav \
  -map 0:a:0 -ac 1 -ar 8000 -codec:a libmp3lame -b:a 32k -f wav sample-32k.wav
file sample.wav sample-32k.wav
ls -l sample.wav sample-32k.wav
Copied!
sample.wav:     RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 8000 Hz
sample-32k.wav: RIFF (little-endian) data, WAVE audio, MPEG Layer 3, mono 8000 Hz
-rw-r--r-- 1 you you 240872 Dec  2 17:00 sample-32k.wav
-rw-r--r-- 1 you you 960078 Dec  2 17:00 sample.wav

Both are “WAVE audio”; only the codec changed. -map 0:a:0 takes the first audio stream, -ac 1 and -ar 8000 set mono at 8 kHz, -b:a 32k sets the MP3 bitrate, and -f wav keeps the WAV container. On a test tone the size came out at almost exactly 32/128 of the original, which matches the arithmetic.

Now listen to a converted real call, start to finish, in whatever people actually use: the PBX’s web interface, your own playback page, a desktop player. This step tells you whether a .wav-named MP3 will work for you at all. Try 16k and 24k too, and keep the lowest bitrate where speech is still clear.

Step 3: Estimate the Savings on Your Own Files

I am not going to give you a percentage, because it depends entirely on what your PBX writes and what bitrate you choose. Here is the arithmetic for common sources, size after conversion as a share of the original:

Source recording PCM bitrate MP3 at 32 kbit/s MP3 at 16 kbit/s
8 kHz, 16-bit, mono 128 kbit/s 25% 12.5%
8 kHz G.711, mono 64 kbit/s 50% 25%
16 kHz, 16-bit, mono 256 kbit/s 12.5% 6.25%
44.1 kHz, 16-bit, stereo 1411.2 kbit/s 2.3% 1.1%

That is arithmetic only, ignoring a few hundred bytes of header per file. To measure on real recordings, this script copies a random sample to a scratch directory, converts the copies with the script from Step 4, and compares du before and after. The originals are not touched:

Copied!
#!/usr/bin/env bash
# measure-savings: copy a random sample of recordings to a scratch directory,
# convert the copies, and report the size change. Originals are not touched.
#   measure-savings <recordings_dir> [sample_size]
set -eu

src=${1:?usage: measure-savings <recordings_dir> [sample_size]}
n=${2:-20}
scratch=$(mktemp -d)

find "$src" -type f -name '*.wav' -print0 | shuf -z -n "$n" | xargs -0 -r cp -p -t "$scratch" --
before=$(du -sb "$scratch" | cut -f1)
find "$scratch" -type f -name '*.wav' -exec /usr/local/bin/recompress-recordings file {} + >/dev/null || true
after=$(du -sb "$scratch" | cut -f1)

awk -v b="$before" -v a="$after" 'BEGIN {
    printf "before: %d bytes\nafter:  %d bytes\nsmaller by %.1f%%\n", b, a, 100 * (1 - a / b) }'
echo "converted copies are in $scratch (listen to a few, then delete it)"

Save it as /usr/local/bin/measure-savings, sudo chmod 755 it, and run it once Step 4 is installed, as a user that can read the recordings: sudo -u <PBX_USER> /usr/local/bin/measure-savings <RECORDINGS_DIR> 50 (the full path matters on distributions whose sudo secure_path leaves out /usr/local/bin). Recordings with the same name in different directories overwrite each other in the scratch directory, which only makes the sample a little smaller.

Step 4: Write the Watcher Script

One script does both jobs. watch runs inotifywait and converts files as they finish. file converts the paths you give it, which is what the backfill and the nightly sweep use. Create it (in vim, press i to insert, Esc then :wq to save and quit):

Copied!
sudo vim /usr/local/bin/recompress-recordings
Copied!
#!/usr/bin/env bash
# recompress-recordings: re-encode finished PBX WAV recordings as MP3,
# keeping the original .wav filename, ownership, mode and timestamps.
#
#   recompress-recordings watch            watch $WATCH_DIR and convert files as they finish
#   recompress-recordings file <path>...   convert the given files (used for backfill)
#
# Safe to run on the same file twice: anything that is not PCM is skipped.
set -u

WATCH_DIR=${WATCH_DIR:-}
BITRATE=${BITRATE:-32k}
SAMPLE_RATE=${SAMPLE_RATE:-8000}
SETTLE=${SETTLE:-3}

log() { printf '%s %s\n' "$(date '+%F %T')" "$*"; }

is_pcm() {
    local codec
    codec=$(ffprobe -v error -select_streams a:0 -show_entries stream=codec_name \
        -of csv=p=0 "file:$1" 2>/dev/null) || return 1
    [[ $codec == pcm_* ]]
}

recompress() {
    local src=$1 dir base tmp stamp
    [[ -f $src ]] || return 0                 # deleted or renamed before we got here
    is_pcm "$src" || return 0                 # already converted, or not PCM audio
    if fuser -s "$src" 2>/dev/null; then      # still open: a writer's close fires
        log "still open, skipped: $src"       # close_write again; else the sweep
        return 0
    fi

    dir=$(dirname -- "$src")
    base=$(basename -- "$src")
    stamp=$(stat -c '%s %Y' -- "$src")
    # Temp file in the SAME directory so the final mv is an atomic rename(2).
    # The name does not end in .wav, so the watcher ignores it.
    tmp=$(mktemp -p "$dir" ".${base}.XXXXXX") || { log "ERROR mktemp failed in $dir"; return 1; }

    if ! ffmpeg -nostdin -hide_banner -loglevel error -y -i "file:$src" \
            -map 0:a:0 -ac 1 -ar "$SAMPLE_RATE" -codec:a libmp3lame -b:a "$BITRATE" \
            -f wav "file:$tmp"; then
        log "ERROR ffmpeg failed: $src"
        rm -f -- "$tmp"
        return 1
    fi

    if [[ $(stat -c '%s %Y' -- "$src" 2>/dev/null) != "$stamp" ]]; then
        log "changed during encode, left alone: $src"
        rm -f -- "$tmp"
        return 0
    fi

    chmod --reference="$src" -- "$tmp"
    chown --reference="$src" -- "$tmp" 2>/dev/null || log "WARN could not copy owner: $src"
    touch -r "$src" -- "$tmp"

    local before after
    before=${stamp%% *}
    after=$(stat -c %s -- "$tmp")
    if mv -f -- "$tmp" "$src"; then
        log "compressed $before -> $after bytes: $src"
    else
        log "ERROR mv failed: $src"
        rm -f -- "$tmp"
        return 1
    fi
}

watch_dir() {
    [[ -d $WATCH_DIR ]] || { log "ERROR WATCH_DIR is not a directory: '$WATCH_DIR'"; exit 1; }
    command -v inotifywait >/dev/null || { log "ERROR inotifywait not found (install inotify-tools)"; exit 1; }
    log "watching $WATCH_DIR (bitrate $BITRATE, rate $SAMPLE_RATE)"

    inotifywait -m -r -q -e close_write -e moved_to --format '%w%f' "$WATCH_DIR" |
    while IFS= read -r path; do
        case $path in
            *.wav|*.WAV) ;;
            *) continue ;;
        esac
        sleep "$SETTLE"
        recompress "$path" </dev/null
    done

    log "inotifywait exited; stopping so systemd can restart us"
    exit 1
}

case ${1:-} in
    watch) watch_dir ;;
    file)
        shift
        rc=0
        for f in "$@"; do recompress "$f" || rc=1; done
        exit "$rc"
        ;;
    *)
        echo "usage: $0 watch | file <path>..." >&2
        exit 2
        ;;
esac
Copied!
sudo chmod 755 /usr/local/bin/recompress-recordings
bash -n /usr/local/bin/recompress-recordings && echo syntax ok

The details that matter:

  • -nostdin and </dev/null. FFmpeg reads standard input for keyboard commands while it encodes. Inside a while read loop, standard input is your list of filenames, so FFmpeg eats part of the next path. A c in that path opens the Enter command: prompt, and the rest of the line fails to parse. Reproduced with a path containing /c/, this gives exactly the error from the top of this article, and the loop quits early because its input is gone. If the list is NUL-separated (find -print0 with read -d ''), there is no line end for FFmpeg to stop at, and it sits at the prompt forever.
  • IFS= read -r and quoting. Recording names have spaces, commas, brackets and parentheses. IFS= keeps leading and trailing spaces, -r keeps backslashes, and every expansion is quoted. Names containing a newline would still break a line-based loop. Newer inotify-tools releases offer %0 (a NUL byte) in --format if you need that; check man inotifywait for your version.
  • file: prefix. FFmpeg treats something: at the start of a name as a protocol. A relative name with a colon fails with Protocol not found. Absolute paths are safe, but the prefix costs nothing.
  • The PCM check. It makes the script idempotent. That matters even in normal operation: the script’s own final mv fires a moved_to on the .wav name, and the second pass finds MP3 and does nothing. My original version grepped file output for WAVE audio, Microsoft PCM; asking ffprobe for the codec name does the same job and also matches G.711 (pcm_mulaw, pcm_alaw).
  • The stat check. If the size or modification time changed while FFmpeg was working, something else is still writing, so the script keeps the original.
  • Logging to stdout. It lands in the journal, so the service needs no write access to /var/log.

Step 5: Run It as a systemd Service

Run the service as the PBX’s user. Then the temp file can be created in the PBX’s directories, chown --reference is a harmless no-op, and fuser can see the PBX’s processes. Running it as root, as I first did, also works, but then a bug in a shell script that parses filenames controlled by callers runs with full control of the machine.

Copied!
sudo vim /etc/systemd/system/recompress-recordings.service
Copied!
[Unit]
Description=Recompress PBX call recordings as they are written
After=local-fs.target

[Service]
Type=exec
User=<PBX_USER>
Group=<PBX_GROUP>
Environment=WATCH_DIR=<RECORDINGS_DIR>
Environment=BITRATE=32k
Environment=SAMPLE_RATE=8000
ExecStart=/usr/local/bin/recompress-recordings watch
Restart=always
RestartSec=5
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7

[Install]
WantedBy=multi-user.target

Restart=always restarts the service however it exits, and the script exits non-zero if inotifywait dies. Type=exec makes systemctl start report a missing binary or a bad User= instead of pretending to succeed. Nice= and the I/O priority keep conversions behind the PBX. If the recordings path contains spaces, quote the whole assignment: Environment="WATCH_DIR=/path with spaces".

Copied!
sudo systemctl daemon-reload
sudo systemctl enable --now recompress-recordings.service
systemctl status recompress-recordings.service --no-pager

Step 6: Add a Nightly Sweep for Missed Events

This covers the inotify limits from How It Works: queue overflows, the new-directory race, and anything written while the service was stopped. It converts any PCM recording older than ten minutes.

Copied!
sudo vim /etc/systemd/system/recompress-recordings-sweep.service
Copied!
[Unit]
Description=Recompress any PCM recordings the watcher missed

[Service]
Type=oneshot
User=<PBX_USER>
Group=<PBX_GROUP>
Environment=BITRATE=32k
Environment=SAMPLE_RATE=8000
Nice=19
IOSchedulingClass=idle
ExecStart=/bin/sh -c 'find <RECORDINGS_DIR> -type f -name "*.wav" -mmin +10 -print0 | xargs -0 -r -n 50 /usr/local/bin/recompress-recordings file'
Copied!
sudo vim /etc/systemd/system/recompress-recordings-sweep.timer
Copied!
[Unit]
Description=Nightly sweep for recordings the watcher missed

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target

Keep $ out of that ExecStart= line: systemd expands $NAME itself before sh ever sees it. Persistent=true runs a missed sweep at the next boot.

Copied!
sudo systemd-analyze verify /etc/systemd/system/recompress-recordings*.service /etc/systemd/system/recompress-recordings-sweep.timer
sudo systemctl daemon-reload
sudo systemctl enable --now recompress-recordings-sweep.timer

systemd-analyze verify prints nothing when the units are clean.

Step 7: Backfill the Existing Recordings

Same per-file step, fed by find, two files at a time, at the lowest CPU and I/O priority, as the PBX’s user. tee keeps a log you can total afterwards.

Copied!
sudo -u <PBX_USER> bash -c 'find "$1" -type f -name "*.wav" -mmin +10 -print0 |
  nice -n 19 ionice -c 3 xargs -0 -r -n 50 -P 2 /usr/local/bin/recompress-recordings file' _ <RECORDINGS_DIR> \
  | tee ~/backfill.log

The idle I/O class (-c 3) only gets disk time when nobody else wants it, but it depends on the block device’s I/O scheduler honoring priorities. BFQ and mq-deadline do, none and kyber do not; check yours with cat /sys/block/<disk>/queue/scheduler. Raise -P if the machine has idle cores. Because the step is idempotent, you can stop this with Ctrl+C and start it again later.

When it finishes, total the log:

Copied!
awk '$3 == "compressed" { n++; b += $4; a += $6 }
     END { if (n) printf "%d files, %.2f GB -> %.2f GB, %.1f%% smaller\n", n, b/1e9, a/1e9, 100*(1-a/b) }' ~/backfill.log

The same awk works on the service’s journal: journalctl -u recompress-recordings -o cat > ~/watch.log, then run it on that file. Compare with du -sh <RECORDINGS_DIR> from Step 1.

Step 8: Move Recordings Between Servers with rsync

When I had to bring about 262 GB of recordings back from a backup server, the requirements were: delete nothing at the destination, end up with every file owned by the PBX’s user, and survive my SSH session closing. --chown=USER:GROUP sets owner and group on the receiving side. It arrived in rsync 3.1.0 and is implemented with --usermap and --groupmap, so the receiving rsync must run as root to change owners. Leaving out --delete means nothing at the destination is removed.

I tested --chown on two test machines first, including files deliberately created as root, and did a dry run before the real thing. Stop the watcher during a bulk restore. By default rsync builds each file under a temporary name and moves it into place when it is complete, so moved_to fires for every file that lands and the watcher would be converting while rsync copies. If a transfer is interrupted, --partial keeps the partial file, and you do not want that converted. The sweep and Step 7 handle anything PCM afterwards.

Run this on the PBX server as root, pulling from the backup server. Root’s SSH key, or one you pass with -e "ssh -i <KEY_FILE>", must be authorized for a user that can read the backup copy.

Copied!
sudo systemctl stop recompress-recordings.service
sudo -i
rsync -avP --dry-run --chown=<PBX_USER>:<PBX_GROUP> \
  <BACKUP_USER>@<BACKUP_HOST>:<BACKUP_PATH>/recordings/ <RECORDINGS_DIR>/ | less

The trailing slash on the source copies the directory’s contents rather than creating recordings/recordings. When the dry-run file list looks right, start the real copy detached from your terminal, with a timestamped log:

Copied!
nohup rsync -avP --chown=<PBX_USER>:<PBX_GROUP> \
  <BACKUP_USER>@<BACKUP_HOST>:<BACKUP_PATH>/recordings/ <RECORDINGS_DIR>/ \
  > /var/log/recordings_rsync_$(date +%Y%m%d_%H%M%S).log 2>&1 &
tail -f /var/log/recordings_rsync_*.log

-a keeps permissions and modification times, -v lists files, and -P is --partial --progress. I ran mine the other way round, pushing from the backup server; pulling as shown means the PBX never has to accept a privileged SSH login for this. The summary line counts from the side that ran the command, so mine reported 262,393,434,025 bytes sent at about 80 MB/s (on a pull, the big number is under “received”), and speedup is 1.00, which means nothing was already there to skip. Then check that no file has the wrong owner. The command should print nothing:

Copied!
find <RECORDINGS_DIR> \( ! -user <PBX_USER> -o ! -group <PBX_GROUP> \) -print | head
exit
sudo systemctl start recompress-recordings.service

Verify

With the service running, copy a PCM recording into the tree as the PBX’s user and watch the journal:

Copied!
sudo install -o <PBX_USER> -g <PBX_GROUP> -m 0640 ~/rec-test/sample.wav "<RECORDINGS_DIR>/verify test.wav"
journalctl -u recompress-recordings -f -o cat

About SETTLE seconds later you should see:

Copied!
2026-12-02 17:05:12 compressed 960078 -> 240872 bytes: <RECORDINGS_DIR>/verify test.wav

Then confirm the file kept its name, owner, mode and timestamp, and now holds MP3:

Copied!
ls -l "<RECORDINGS_DIR>/verify test.wav"
ffprobe -v error -show_entries stream=codec_name,codec_tag_string -of default=nw=1 "<RECORDINGS_DIR>/verify test.wav"
Copied!
codec_name=mp3
codec_tag_string=U[0][0][0]

U[0][0][0] is the format tag 0x55 printed as text. Run sudo -u <PBX_USER> /usr/local/bin/recompress-recordings file "<RECORDINGS_DIR>/verify test.wav" and it should print nothing, because the file is no longer PCM. Delete the test file when you are done. Finally, place a real call, let it record, and play it back in the PBX’s own interface.

How this write-up was tested: on an Ubuntu 24.04 test machine, not the production PBX. inotify-tools was not installable there, so the event loop was driven by a stub that read the raw inotify API and printed paths the way inotifywait does. Every FFmpeg, ffprobe and systemd-analyze command shown was run.

Troubleshooting

Unable to choose an output format for '...wav.temp': FFmpeg picks the container from the extension and does not know .temp. Add -f wav before the output name, as the script does.

FFmpeg prints Enter command: <target>|all <time>|-1 <command>[ <argument>], or Parse error, at least 3 arguments were expected, or a later file fails with a path missing its first characters: FFmpeg is reading your loop’s input as keyboard commands. Add -nostdin, and redirect the loop body’s input from /dev/null.

Permission denied creating the temp file: The service user cannot write in the recording’s directory. Run the service as the PBX’s user (Step 5). Moving the temp file to /tmp makes the error go away but turns the final mv into a non-atomic copy across filesystems.

Service log says inotifywait: command not found, then Deactivated successfully: inotify-tools is not installed. sudo apt install inotify-tools, then restart the service.

inotifywait exits at startup with an error about the inotify watch limit: -r needs one watch per directory and the user hit max_user_watches. Count your directories with find <RECORDINGS_DIR> -type d | wc -l, then raise the limit persistently:

Copied!
cat /proc/sys/fs/inotify/max_user_watches
echo 'fs.inotify.max_user_watches=524288' | sudo tee /etc/sysctl.d/90-inotify.conf
sudo sysctl --system

Pick a value above both the current one and your directory count: on kernels that scale the default with RAM, it can already be higher than 524288, and setting 524288 would lower it. Each watch costs kernel memory, so do not set it far beyond what you need.

Converted recordings are short, garbled or silent at the start: The file was converted while still being written. Use close_write, never create, raise SETTLE, and make sure fuser is installed so the open-file check runs.

The PBX web player, a browser or a desktop player will not play converted files: The player expects PCM inside a WAV container. Check what the file holds with ffprobe; the extension does not tell you. If you control the playback page, serve the bytes as MP3: remuxing to a plain MP3 stream is a container change only, with no re-encode, and takes milliseconds:

Copied!
ffmpeg -nostdin -loglevel error -i "recording.wav" -c:a copy -f mp3 -

If you cannot change the player, rename the files to .mp3 and update whatever references them. If neither is possible, this approach is wrong for that PBX, which is why Step 2 comes before the backfill.

Players show half the real duration: You asked for more than 64 kbit/s at 8 kHz. LAME capped the audio, but the WAV header records the bitrate you asked for, and duration is computed from it. Set BITRATE to 64k or below for new files. Existing files can be fixed without re-encoding by passing the audio through a raw MP3 stream, which rebuilds the header from the real bitrate:

Copied!
ffmpeg -nostdin -loglevel error -i recording.wav -c:a copy -f mp3 - |
  ffmpeg -nostdin -loglevel error -f mp3 -i - -c:a copy -f wav recording-fixed.wav

Decoding the whole file, as in ffmpeg -i recording.wav -f null -, shows the real length.

Before You Automate

Inspect your files, convert a handful, play them in the real player and measure before automating anything. Check what bitrates your sample rate actually allows before you pick one; 128k at 8 kHz silently becomes 64k. Put the temp file next to the original and run the service as the PBX’s user from day one.

Sources and further reading