Crop Video

This article explains how you can crop a 16:9 video to a 4:3 video.

Source Video

For a source video we use the MP4 file from the TED talk video What’s the next window into our universe? by Andrew Connolly. The original video format is Wide 480p or 16:9, 854 x 480.

Sample Code

This code takes an MP4 file with 16:9 480p (854x480) video and AAC audio, and crops the video to 4:3 640x480. The audio stream is copied from the source as is. The input and output file paths are hardcoded in the source code, no command line parsing is used.

The snippets in this section are from the simple_video_crop macOS sample.

Linux and Windows samples are also available:

Initialize AVBlocks

The first step in any AVBlocks application is to initialize the library. This must be done before using any other AVBlocks functionality. The TLibrary constructor initializes the library and loads the necessary codecs. The TLibrary destructor shuts the library down and releases any allocated memory, so the library is terminated when the TLibrary object goes out of scope at the end of main.

int main()
{
    TLibrary library;

    const char* inputFile  = "AndrewConnolly_2014.mp4";
    const char* outputFile = "AndrewConnolly_2014_cropped.mp4";

    // transcoder will fail if output exists (by design)
    std::remove(outputFile);

Configure Transcoder and Crop

We probe the input file with a TMediaInfo object, and create an input socket from it. The output socket is created by cloning the input socket, so it starts out with an identical configuration, and then we set the output file path on it. The transcoder is the core component that performs the actual cropping - it takes the 854x480 video from the input and crops it to 640x480.

Probe Input and Create Sockets

First, we probe the input file and create the input socket. Then we clone it to create the output socket and set the output file path.

auto input = TMediaSocket(TMediaInfo().file(inputFile).open());

Configure Output Video Settings

Next, we get the output video stream info and configure the frame dimensions and display ratio. We set the new frame size to 640x480 and change the display ratio from 16:9 to 4:3.

input.clone()
    .file(outputFile)
    .videoInfoRef(0, [](TVideoStreamInfo& video) {
        // Set the new frame width and height to 640 x 480 and the display ratio to 4:3
        video.frameWidth(640).frameHeight(480)
             .displayRatioWidth(4).displayRatioHeight(3);
    })

Apply Crop Parameters

To crop the video, we need to calculate how many pixels to remove from each side. Since the input is 854x480 and we want 640x480, we cut (854 - 640) / 2 = 107 pixels from the left and right.

input.clone()
    .file(outputFile)
    .videoInfoRef(0, [](TVideoStreamInfo& video) {
        // Set the new frame width and height to 640 x 480 and the display ratio to 4:3
        video.frameWidth(640).frameHeight(480)
             .displayRatioWidth(4).displayRatioHeight(3);
    })
    .pinRef(0, [](TMediaPin& pin) {
        // The input video is 854x480.
        // To make it 640x480 we have to cut (854 - 640) / 2 pixels from each side.
        pin.addParam(Param::Video::Crop::Left,  (854 - 640) / 2)
           .addParam(Param::Video::Crop::Right, (854 - 640) / 2);
    })

Create and Run Transcoder

Finally, we create the transcoder, add the input and output sockets, and run the operation. The allowDemoMode(true) call allows the transcoder to work even without a valid license (useful for testing, but not recommended for production).

TTranscoder()
    .allowDemoMode(true)
    .addInput(input)
    // The output starts as a copy of the input
    .addOutput(
        input.clone()
            .file(outputFile)
            .videoInfoRef(0, [](TVideoStreamInfo& video) {
                // Set the new frame width and height to 640 x 480 and the display ratio to 4:3
                video.frameWidth(640).frameHeight(480)
                     .displayRatioWidth(4).displayRatioHeight(3);
            })
            .pinRef(0, [](TMediaPin& pin) {
                // The input video is 854x480.
                // To make it 640x480 we have to cut (854 - 640) / 2 pixels from each side.
                pin.addParam(Param::Video::Crop::Left,  (854 - 640) / 2)
                   .addParam(Param::Video::Crop::Right, (854 - 640) / 2);
            })
    )
    .transcode();

Complete C++ Code

Here’s the complete working example that demonstrates video cropping using AVBlocks. The input and output file paths are hardcoded, so no command line parsing is required.

#include <primo/avblocks/avb++.h>

#include <cstdio>
#include <print>

#include "../shim/shim23.h"

using namespace primo::avblocks;
using namespace primo::avblocks::modern;

int main()
{
    TLibrary library;

    const char* inputFile  = "AndrewConnolly_2014.mp4";
    const char* outputFile = "AndrewConnolly_2014_cropped.mp4";

    // transcoder will fail if output exists (by design)
    std::remove(outputFile);

    try {
        // Probe the input file and create the input socket from the probe
        auto input = TMediaSocket(TMediaInfo().file(inputFile).open());

        // Demo mode is allowed when using the demo version of the library.
        TTranscoder()
            .allowDemoMode(true)
            .addInput(input)
            // The output starts as a copy of the input
            .addOutput(
                input.clone()
                    .file(outputFile)
                    .videoInfoRef(0, [](TVideoStreamInfo& video) {
                        // Set the new frame width and height to 640 x 480 and the display ratio to 4:3
                        video.frameWidth(640).frameHeight(480)
                             .displayRatioWidth(4).displayRatioHeight(3);
                    })
                    .pinRef(0, [](TMediaPin& pin) {
                        // The input video is 854x480.
                        // To make it 640x480 we have to cut (854 - 640) / 2 pixels from each side.
                        pin.addParam(Param::Video::Crop::Left,  (854 - 640) / 2)
                           .addParam(Param::Video::Crop::Right, (854 - 640) / 2);
                    })
            )
            .transcode();

        std::println("Output: {}", outputFile);
        return 0;

    } catch (const TAVBlocksException& ex) {
        std::println(stderr, "AVBlocks error: {}", ex.what());
        return 1;
    }
}

How to Run

See the build instructions for macOS and the simple_video_crop example for details.

Download the sample video, the MP4 file from the TED talk video What’s the next window into our universe? by Andrew Connolly (Wide 480p, 854x480, 16:9):

cd samples/darwin/simple_video_crop
curl -L -o AndrewConnolly_2014.mp4 "https://archive.org/download/AndrewConnolly_2014/AndrewConnolly_2014.mp4"

Run the sample from the sample directory (the input/output file paths are relative to the working directory):

../../../bin/arm64/simple_video_crop    # or ../../../bin/x64/simple_video_crop

The cropped output file AndrewConnolly_2014_cropped.mp4 will be created in the samples/darwin/simple_video_crop directory.