How do I use ffmpeg to get the video resolution?

I am trying to get resolution of the video with the following command:

ffmpeg -i filename.mp4

I get a long output, but I need just the width and height for my bash script. How should I filter out those parameters? Maybe there's a better way to do this.


Solution 1:

Use ffprobe

$ ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 input.mp4
  1280x720

Examples of other output formatting choices

See -of option documentation for more choices and options. Also see FFprobe Tips for other examples including duration and frame rate.

Default

With no [STREAM] wrapper:

$ ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of default=nw=1 input.mp4
  width=1280
  height=720

With no key:

$ ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of default=nw=1:nk=1 input.mp4
  1280
  720

CSV

$ ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 input.mp4
  1280,720

JSON

$ ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of json input.mp4
{
    "programs": [

    ],
    "streams": [
        {
            "width": 1280,
            "height": 720
        }
    ]
}

XML

$ ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of xml input.mp4
<?xml version="1.0" encoding="UTF-8"?>
<ffprobe>
    <programs>
    </programs>

    <streams>
        <stream width="1280" height="720"/>
    </streams>
</ffprobe>

Solution 2:

The following commands rely purely on ffmpeg (and grep and cut) to get you the height or width as required:

Height:

$ ffmpeg -i video.mp4 2>&1 | grep Video: | grep -Po '\d{3,5}x\d{3,5}' | cut -d'x' -f1

1280

Width:

$ ffmpeg -i video.mp4 2>&1 | grep Video: | grep -Po '\d{3,5}x\d{3,5}' | cut -d'x' -f2

720

The difference between the two is just the -f parameter to cut.

If you prefer the full resolution string, you don't need cut:

$ ffmpeg -i video.mp4 2>&1 | grep Video: | grep -Po '\d{3,5}x\d{3,5}'

1280x720

Here's what we're doing with these commands:

  1. Running ffmpeg -i to get the file info.
  2. Extracting the line which just contains Video: information.
  3. Extracting just a string that looks like digitsxdigits which are between 3 and 5 characters.
  4. For the first two, cutting out the text before or after the x.