Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

ffmpeg script outputs video with unexpected resolution and frame rate despite scaling and fps filtering

+2
−0

I'm having trouble with an ffmpeg script that's supposed to convert videos to a specific resolution and frame rate, but the output video has unexpected dimensions and frame rate. Here's my script and the issue:

#!/usr/bin/env bash

# Constants
MAX_RESOLUTION=540
MAX_FPS=15
MAX_BITRATE="500k"
CRF_VALUE=30
AUDIO_BITRATE="64k"

# Check if the directory argument is provided
if [ $# -eq 0 ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

TARGET_DIR="$1"

# Function to log messages
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# Function to handle errors
handle_error() {
    log "Error occurred: $1"
    exit 1
}

for FILE in $(find "$TARGET_DIR" -type f \( -iname "*.mp4" -o -iname "*.mkv" -o -iname "*.avi" -o -iname "*.mov" -o -iname "*.m4v" -o -iname "*.wmv" \)); do
    log "Processing: $FILE"
    
    # Get video dimensions and frame rate
    DIMENSIONS=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 "$FILE")
    WIDTH=$(echo $DIMENSIONS | cut -d'x' -f1)
    HEIGHT=$(echo $DIMENSIONS | cut -d'x' -f2)
    FPS=$(ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=r_frame_rate -of csv=p=0 "$FILE" | bc -l | awk '{printf("%d\n",$1 + 0.5)}')
    
    # Determine scaling only if necessary
    SCALING=""
    if [ $WIDTH -lt $HEIGHT ]; then
        SHORTER_SIDE=$WIDTH
        if [ $WIDTH -gt $MAX_RESOLUTION ]; then
            SCALING="-vf scale=$MAX_RESOLUTION:-2"
        fi
    else
        SHORTER_SIDE=$HEIGHT
        if [ $HEIGHT -gt $MAX_RESOLUTION ]; then
            SCALING="-vf scale=-2:$MAX_RESOLUTION"
        fi
    fi
    
    # Add fps filter only if necessary
    FPS_FILTER=""
    if [ $FPS -gt $MAX_FPS ]; then
        FPS_FILTER="-vf fps=$MAX_FPS"
    fi
    
    # Get codec info
    CODEC_INFO=$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 "$FILE")
    
    # Check if conversion is needed
    if [[ "$CODEC_INFO" != "hevc" && "$CODEC_INFO" != "h265" ]] || [ "$FPS" -gt "$MAX_FPS" ] || [ $SHORTER_SIDE -gt $MAX_RESOLUTION ]; then
        OUTPUT_FILE="${FILE%.*}.h265.mkv"
        
        # Combine scaling, FPS filtering, and codec selection
        ffmpeg_cmd=(
            "-i" "$FILE"
            $SCALING
            $FPS_FILTER
            "-c:v" "libx265"
            "-preset" "slow"
            "-crf" "$CRF_VALUE"
            "-c:a" "aac"
            "-b:a" "$AUDIO_BITRATE"
            "-movflags" "+faststart"
            "$OUTPUT_FILE"
        )
        
        log "Executing FFmpeg command: ${ffmpeg_cmd[*]}"
        ffmpeg "${ffmpeg_cmd[@]}" || handle_error "FFmpeg failed to encode $FILE"
        
        log "Conversion completed successfully."
    else
        log "No conversion needed for $FILE"
    fi
done

The problem is that the output video has a different resolution and frame rate than I expect:

Input #0
  Stream #0:0[0x1](und): Video: hevc (Main 10) (hvc1 / 0x31637668), yuv420p10le(tv, bt2020nc/bt2020/arib-std-b67), 3840x2160, 94843 kb/s, 59.98 fps, 60 tbr, 600 tbn (default)

Output #0
  Stream #0:0(und): Video: hevc, yuv420p10le(tv, bt2020nc/bt2020/arib-std-b67, progressive), 406x720, q=2-31, 1000 kb/s, 60 fps, 1k tbn (default)

❯ ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=r_frame_rate -of csv=p=0 "$FILE"
60/1,

❯ ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=r_frame_rate -of csv=p=0 "$FILE" | bc -l | awk '{printf("%d\n",$1 + 0.5)}'
(standard_in) 1: syntax error

The output is 406x720 instead of the expected 1080x720, and 60 fps instead of the desired 30 fps. How can I fix this issue?

Please help me understand why this is happening and how to achieve the desired output resolution and frame rate.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

2 answers

+1
−0

Your issue lies in the application of scaling and fps filtering. Both SCALING and FPS_FILTER are being set conditionally, and if both are needed, one will override the other since both are using -vf. Combine them in one -vf argument to avoid conflict:

if [ $WIDTH -lt $HEIGHT ]; then
    SHORTER_SIDE=$WIDTH
    if [ $WIDTH -gt $MAX_RESOLUTION ]; then
        SCALING="scale=$MAX_RESOLUTION:-2"
    fi
else
    SHORTER_SIDE=$HEIGHT
    if [ $HEIGHT -gt $MAX_RESOLUTION ]; then
        SCALING="scale=-2:$MAX_RESOLUTION"
    fi
fi

if [ $FPS -gt $MAX_FPS ]; then
    if [ -z "$SCALING" ]; then
        SCALING="fps=$MAX_FPS"
    else
        SCALING="$SCALING, fps=$MAX_FPS"
    fi
fi

Then apply the combined filter:

ffmpeg_cmd=(
    "-i" "$FILE"
    "-vf" "$SCALING"
    "-c:v" "libx265"
    "-preset" "slow"
    "-crf" "$CRF_VALUE"
    "-c:a" "aac"
    "-b:a" "$AUDIO_BITRATE"
    "-movflags" "+faststart"
    "$OUTPUT_FILE"
)

This ensures both scaling and frame rate adjustments are applied correctly.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

0 comment threads

+1
−0

This script applies filters dynamically based on the video's dimensions and frame rate. The audio handling is more sophisticated, checking and adjusting the bitrate separately. It's more flexible in codec selection, only converting when truly necessary. It uses glob patterns for file matching, potentially offering better efficiency.

#!/usr/bin/env bash

# Constants
MAX_RESOLUTION=540
MAX_FPS=15
MAX_BITRATE="500k"
CRF_VALUE=30
MAX_AUDIO_BITRATE="64k"

# Check if the directory argument is provided
if [ $# -eq 0 ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

TARGET_DIR="$1"

# Function to log messages
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# Function to handle errors
handle_error() {
    log "Error occurred: $1"
    exit 1
}

# Main conversion loop
for FILE in "$TARGET_DIR"/*.{mp4,mkv,avi,mov,m4v,wmv}; do
    [ -e "$FILE" ] || continue
    log "Processing: $FILE"
    
    # Get video dimensions and frame rate
    DIMENSIONS=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 "$FILE")
    WIDTH=$(echo $DIMENSIONS | cut -d'x' -f1)
    HEIGHT=$(echo $DIMENSIONS | cut -d'x' -f2)
    FPS=$(ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=r_frame_rate -of csv=p=0 "$FILE" | bc -l | awk '{printf("%d\n",$1 + 0.5)}')
    
    FILTERS=()

    if [ $WIDTH -lt $HEIGHT ]; then
        SHORTER_SIDE=$WIDTH
        if [ $WIDTH -gt $MAX_RESOLUTION ]; then
            FILTERS+=("scale=$MAX_RESOLUTION:-2")
        fi
    else
        SHORTER_SIDE=$HEIGHT
        if [ $HEIGHT -gt $MAX_RESOLUTION ]; then
            FILTERS+=("scale=-2:$MAX_RESOLUTION")
        fi
    fi
    
    if [ $FPS -gt $MAX_FPS ]; then
        FILTERS+=("fps=$MAX_FPS")
    fi

    # Combine filters if any exist
    if [ ${#FILTERS[@]} -gt 0 ]; then
        FILTER_OPTION="-vf $(IFS=,; echo "${FILTERS[*]}")"
    else
        FILTER_OPTION=""
    fi
    
    audio_bitrate=$(ffprobe -v error -select_streams a:0 -show_entries stream=bit_rate -of default=noprint_wrappers=1:nokey=1 "$FILE")
    audio_filter=""
    if [ "$audio_bitrate" -gt "$MAX_AUDIO_BITRATE" ]; then
        audio_filter="-b:a $MAX_AUDIO_BITRATE"
    fi

    # Get codec info
    CODEC_INFO=$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 "$FILE")
    
    # Check if conversion is needed
    if [[ "$CODEC_INFO" != "hevc" && "$CODEC_INFO" != "h265" ]] || [ "$FPS" -gt "$MAX_FPS" ] || [ $SHORTER_SIDE -gt $MAX_RESOLUTION ] || [ "$audio_bitrate" -gt "$MAX_AUDIO_BITRATE" ]; then
        OUTPUT_FILE="${FILE%.*}.h265.mkv"
        
        # Combine scaling, FPS filtering, and codec selection
        ffmpeg_cmd=(
            "-i" "$FILE"
            $FILTER_OPTION
            "-c:v" "libx265"
            "-preset" "slow"
            "-crf" "$CRF_VALUE"
            "-c:a" "aac"
            $audio_filter
            "-movflags" "+faststart"
            "$OUTPUT_FILE"
        )
        
        log "Executing FFmpeg command: ${ffmpeg_cmd[*]}"
        ffmpeg "${ffmpeg_cmd[@]}" || handle_error "FFmpeg failed to encode $FILE"
        
        log "Conversion completed successfully."
    else
        log "No conversion needed for $FILE"
    fi
done
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »