Batch MP4 Conversion: A Safe CLI and Automation Workflow

November 08, 2026 · MP4.now Editorial · MP4 Essentials

Design a repeatable MP4 batch process with canaries, logs, validation and rollback.

Batch MP4 Conversion: A Safe CLI and Automation Workflow

This page covers a repeatable, production-oriented workflow for converting source video files into MP4 (ISO Base Media File Format) using command-line tools. It assumes you need to process many files, detect failures early, validate outputs against the MP4 specification, and recover from errors without data loss. This is a blueprint for batch automation with canary files, structured logs, and rollback capability.

The Core Automation Pattern: Canary, Convert, Validate, Rollback

A safe batch process requires four distinct phases executed sequentially. Each phase produces artifacts—logs, checksums, validation reports—that allow you to halt or reverse the operation if a threshold is breached.

Phase 1: Canary Run

Before touching your source files, run a single conversion on a representative sample (the canary). The canary should match the average duration, resolution, and codec of your source set. If the canary fails or produces an output with unexpected properties—wrong codec, duration drift, missing metadata—stop immediately and diagnose the toolchain. Do not proceed to batch.

Phase 2: Conversion with Structured Logging

Use a script that records per-file exit codes, stderr output, elapsed time, and output file size. Logs must be append-only and timestamped. Write to a separate output directory; never overwrite source files.

Phase 3: Validation Against the MP4 Specification

Validate each output file for structural integrity. The MP4 format (ISO 14496-12, see Library of Congress FDD000155) requires a valid ftyp box at offset 0, correct box hierarchy, and proper moov box placement. Use tools that check box structure, not just file extension.

Phase 4: Rollback on Failure

If any validation step fails, the batch must not commit. Move the entire output directory to a quarantine folder, preserve the log, and restore the previous good output set. Never delete source files during conversion.

Tool Selection and Safe Defaults

For batch MP4 conversion, ffmpeg is the de facto standard. The following command structure enforces safe defaults for batch work:

ffmpeg -i input.mkv -c:v libx264 -preset slow -crf 23 -c:a aac -b:a 128k \
  -movflags +faststart -map_metadata 0 -map 0 -y output.mp4 2>> batch.log

Key parameters for batch safety:

  • -movflags +faststart: Moves the moov atom to the beginning of the file. This is required for streaming and progressive download. Without it, many players will fail to start playback until the entire file is downloaded. The Library of Congress notes that the moov box location is critical for web delivery (FDD000155, "MP4 File Structure").
  • -map_metadata 0 -map 0: Preserves all input streams and metadata. Do not use -map 0:v or -map 0:a unless you explicitly want to discard subtitle or data streams.
  • -c:v libx264: Uses the H.264 codec, which has the widest compatibility among MP4 players. Do not use libx265 (HEVC) for batch unless you have verified that all downstream systems support it.
  • -crf 23: Constant Rate Factor for H.264. Lower values produce larger files with higher quality. Values above 28 introduce visible artifacts in most source material.

Do not use -c copy in batch workflows unless you are certain that the source container and codec are already MP4-compatible. Remuxing without re-encoding can produce files that violate the MP4 specification if the source uses non-standard codecs—such as VP9 or AV1—or container features like embedded chapters in Matroska.

Failure Detection and Logging Strategy

A well-structured log is your only record of what happened. The following shell fragment generates a parseable log that separates success, warning, and error lines:

#!/bin/bash
INPUT_DIR="./source"
OUTPUT_DIR="./output"
LOG_FILE="./batch_$(date +%Y%m%d_%H%M%S).log"
ERROR_DIR="./quarantine"

mkdir -p "$OUTPUT_DIR" "$ERROR_DIR"

for file in "$INPUT_DIR"/*.mkv; do
    base=$(basename "$file" .mkv)
    out="$OUTPUT_DIR/${base}.mp4"
    start=$(date +%s)

    ffmpeg -i "$file" -c:v libx264 -preset slow -crf 23 \
        -c:a aac -b:a 128k -movflags +faststart \
        -map_metadata 0 -map 0 -y "$out" 2>> "$LOG_FILE"

    exit_code=$?
    end=$(date +%s)
    duration=$((end - start))

    if [ $exit_code -eq 0 ]; then
        echo "SUCCESS | $base | duration=${duration}s | size=$(stat -c%s "$out")" >> "$LOG_FILE"
    else
        echo "FAIL    | $base | exit_code=${exit_code} | duration=${duration}s" >> "$LOG_FILE"
        mv "$out" "$ERROR_DIR/" 2>/dev/null
    fi
done

After the batch completes, scan the log for lines starting with FAIL. If any exist, do not delete the source files. The quarantine directory preserves the failed outputs for analysis.

Validation: Box Structure and Duration Check

Validation must go beyond checking file extension or MD5. Use ffprobe and mediainfo to confirm three properties:

  1. Valid ftyp box: The file must start with a recognizable file type box—typically isom, mp42, or avc1. This confirms it is a genuine MP4, not a renamed container.
  2. moov box presence and position: The moov box must be present. If +faststart was used, the moov box should appear before any mdat box. If not, the file will fail on streaming players.
  3. Duration consistency: The output duration must match the input duration within 0.5 seconds. Codec drift or dropped frames can cause duration mismatches.
ffprobe -v error -show_entries format=duration \
  -of default=noprint_wrappers=1:nokey=1 input.mkv
ffprobe -v error -show_entries format=duration \
  -of default=noprint_wrappers=1:nokey=1 output.mp4

Compare the two values. If the difference exceeds 0.5 seconds, flag the file as suspect. The Library of Congress specification (FDD000155) notes that the mdat box may contain multiple interleaved tracks, and any desynchronization in duration suggests a structural problem.

Rollback Procedure

Rollback is a three-step process:

  1. Halt further conversions: Stop the batch script immediately. Do not continue processing remaining files.
  2. Move failed outputs to quarantine: The script above already does this. If the validation phase discovers structural failures, move the entire output directory to a timestamped quarantine folder.
  3. Restore the previous good set: If you maintain a versioned output directory—for example, output_20250321/—copy the last known good set back into the working output directory. If no previous good set exists, do not delete source files.

Never delete source files as part of a rollback. The source directory is your safety net.

Hard Limits of the Batch Workflow

This workflow cannot recover from:

  • Source files that are already corrupted: If the source file has a damaged moov box, no conversion will produce a valid MP4. The canary run will catch this.
  • Codec incompatibility at the decoder level: If ffmpeg cannot decode the source codec—for example, lossless intermediate codecs like ProRes or DNxHD—the conversion will fail with a decoder error. The log will show exit code 1 or 2.
  • Files exceeding 4 GB in a single mdat box: The MP4 format uses 32-bit offsets by default. Files larger than 4 GB require -movflags +faststart and may need -movflags +frag_keyframe to enable fragmented MP4. If you do not enable fragmentation, the conversion will fail silently or produce a file that players cannot seek.

For source files over 4 GB, add -movflags +frag_keyframe to the ffmpeg command. This creates a fragmented MP4 where moof boxes allow random access without loading the entire file into memory. The Library of Congress notes that fragmented MP4—also called fMP4—is a valid variant under ISO 14496-12, but some legacy players do not support it (FDD000155, "Variants").