Ajouve
Ajouve

Reputation: 10049

ffmpeg crop with negative offset

I have a nodejs application which is cropping videos using ffmpeg

From time to time I have an error because I am trying to crop out of the video, see attached image where the black is the video and in red the crop zone. My final video has to be a square.

enter image description here

If I am replacing the negative offset with 0 the final result will not be a square.

I just need to add a black background on the non-existing part

This is my actual code

const cropVideo = (buffer, width, height, x, y) => {

    const inputFile = tmp.fileSync();
    const outputFile = tmp.fileSync();

    fs.writeFileSync(inputFile.name, buffer);

    return new Promise((resolve, reject) => {
        ffmpeg(inputFile.name)
            .videoFilters(`crop=${width}:${height}:${x}:${y}`)
            .format('mp4')
            .on('error', reject)
            .on('end', () => resolve(fs.readFileSync(outputFile.name)))
            .save(outputFile.name);
    })
}

Upvotes: 0

Views: 450

Answers (1)

Ajouve
Ajouve

Reputation: 10049

I found a solution creating a working offset

const cropVideo = (buffer, width, height, x, y) => {

    const inputFile = tmp.fileSync();
    const outputFile = tmp.fileSync();

    fs.writeFileSync(inputFile.name, buffer);

    const workOffset = 2000;

    return new Promise((resolve, reject) => {
        ffmpeg(inputFile.name)
            .videoFilters(`pad=10000:10000:${workOffset}:${workOffset}`)
            .videoFilters(`crop=${width}:${height}:${x + workOffset}:${y + workOffset}`)
            .format('mp4')
            .on('error', reject)
            .on('end', () => resolve(fs.readFileSync(outputFile.name)))
            .save(outputFile.name);
    })
}

Upvotes: 1

Related Questions