Generating thumbnails for Videos using ffmpeg Lambda layer in Node.js

News
01 Apr 2023 / by Ashith VL & Srilekha in NodeJS

Let's dive into why video thumbnails are important!

Generating video thumbnails is important because they give viewers a quick visual representation of what the video is about. Thumbnails help to catch viewers' attention and draw them into watching the video. They are also important for SEO purposes, as they help videos to stand out in search engine results pages. Finally, they help generate more click-throughs, which can lead to more views of the video.

How AWS lambda and S3 service are used for thumbnail generation for video?

Generating video thumbnails in node.js is an essential part of many web and mobile applications. Creating a thumbnail image from a video can help users quickly identify what the video is about, as well as make it more visually appealing. Unfortunately, creating thumbnails can be a difficult and time-consuming process. Thankfully, using AWS Lambda and S3, you can now quickly and easily generate video thumbnails in node.js.

Using AWS Lambda and S3, you can create a thumbnail image from any video file without having to manually write any code. AWS Lambda is a serverless computing service that runs code in response to events, and S3 is a cloud storage service for storing and retrieving data. With these two services, you can create a thumbnail image from any video file stored in S3.

First, you’ll need to set up a Lambda function. This function will be triggered when a new video file is uploaded to your S3 bucket. When the function is triggered, it will use the AWS Node.js SDK to retrieve the video file from S3. Once the file is retrieved, the Node.js code will use the ffmpeg library to generate a thumbnail image from the video file. Finally, the thumbnail image will be uploaded to desired S3 bucket. This process can be automated with the help of AWS Step Functions. Step Functions allow you to create a workflow that runs a series of steps in sequence. This can be used to generate thumbnails for multiple video files in a single operation. Generating video thumbnails in node.js using AWS Lambda and S3 is a great way to quickly and easily generate thumbnails. With a few lines of code and a few clicks, you can have a thumbnail image generated from any video file in no time. Plus, you can automate the process with AWS Step Functions, making it even easier to generate multiple thumbnails in one go. So, if you’re looking for an easy way to generate thumbnails for your videos, give node.js and AWS a try!

Architecture Diagram

bucket

Why ffmpeg lambda layer?

FFmpeg Lambda Layer is a powerful tool for generating video thumbnails. It is faster and more efficient than traditional methods and is designed to work with Amazon Web Services (AWS) Lambda functions. By leveraging the serverless capabilities of Lambda, FFmpeg Lambda Layer allows you to generate thumbnails from video files quickly, without having to provision and manage any additional infrastructure. This means that it is perfect for applications that require thumbnails to be generated on the fly and for applications that are running on a serverless architecture.

Adding lambda layers in two ways:

  1. Using binary files

  1. Download the ffmpeg binaries from the official website.
  2. Create a zip archive of the ffmpeg binary files
  3. Create a new Lambda Layer using the AWS Lambda console.
  4. Upload the zip archive as the source code and configure the Layer as needed.

  1. Using ARN

  1. Login to AWS Console.
  2. Go to the Lambda service page.
  3. Click on the "Layers" section in the left sidebar.
  4. Click on the "Create Layer" button.
  5. Select the "Specific an ARN" option.
  6. Enter the ARN for ffmpeg layer.
  7. Click "Add".
addLayer

Setting up S3 trigger for lambda function

To configure a Lambda function as a trigger for all object creation events for video files in an Amazon S3 bucket, you need to perform the following steps:

  • Sign in to the AWS Management Console and open the Lambda console.
  • Create a new Lambda function and select a runtime.
  • Configure the function as needed.
  • In the Designer tab, click on “S3” from the list of event sources.
  • Select the bucket that you want to trigger the function from and click “Next.”
  • In the next section, set the Prefix and Suffix to match the objects in the bucket that you want the function to trigger on, for video, we can set it as .mp4 or any of your preferred video file type.
  • Click “Add” and then “Save” to save the changes.
  • Test the function to make sure it is working as expected.
thumbnail_generator trigger_configuration image_trigger

How video thumbnails are generated using the specified lambda layers in node.js and uploaded in S3?

  • Create an AWS Lambda Layer containing the necessary binaries for FFmpeg.
  • Upload the Layer to an S3 bucket where it will be stored and accessed by Lambda
  • Create a Lambda function with the FFmpeg binary Layer as a dependency.
  • Within the Lambda function, use the Node.js fs module to read the video file from S3.
  • Use the Node.js child_process module to call FFmpeg and generate the thumbnail from the video file.
  • Use the Node.js fs module to save the thumbnail to a temporary file.
  • Use the Node.js AWS SDK to upload the thumbnail to S3.
  • Clean up the temporary file.

Code

const AWS = require("aws-sdk");
const fs = require("fs");
const { spawnSync } = require("child_process");

const videoFileUploadHandler = (event, context, callback) => {
  const s3 = new AWS.S3();
  const bucket = event.Records[0].s3.bucket.name;
  const key = event.Records[0].s3.object.key;
  const targetDurationSeconds = 5;

  // find the duration of the video
  const ffprobePath = "/opt/bin/ffprobe"
  const ffprobeParams = [
    "-v",
    "error",
    "-show_entries",
    "format=duration",
    "-of",
    "default=noprint_wrappers=1:nokey=1",
    `s3://${bucket}/${key}`
  ];
  const ffprobeResult = spawnSync(ffprobePath, ffprobeParams);

  // calculate the time to generate thumbnail
  const videoDurationSeconds = parseFloat(ffprobeResult.stdout.toString());
  const thumbnailTimeSeconds = Math.ceil(videoDurationSeconds / targetDurationSeconds);

  // generate the thumbnail
  const thumbnailName = key.split(".")[0] + ".jpg";
  const ffmpegPath = "/opt/bin/ffmpeg";
  const ffmpegParams = [
    "-i",
    `s3://${bucket}/${key}`,
    "-ss",
    `${thumbnailTimeSeconds}`,
    "-vframes",
    "1",
    "-q:v",
    "2",
    "-f",
    "image2",
    "-vcodec",
    "mjpeg",
    `/tmp/${thumbnailName}`
  ];
  spawnSync(ffmpegPath, ffmpegParams);

  // upload the thumbnail
  const thumbnailData = fs.readFileSync(`/tmp/${thumbnailName}`);
  const thumbnailParams = {
    Body: thumbnailData,
    Bucket: bucket,
    Key: thumbnailName
  };
  s3.putObject(thumbnailParams, (err, data) => {
    if (err) {
      console.log(err);
      callback(err);
    } else {
      console.log(`Successfully generated and uploaded thumbnail ${thumbnailName}`);
      callback(null, data);
    }
  });
};

exports.handler = videoFileUploadHandler;

              

Advantages of our implementation of video thumbnail generation over other video thumbnail generation libraries that are available in Node.js

  • Speed and scalability: By using ffmpeg aws lambda layer, you can generate thumbnails for videos with lightning-fast speed and scale it up to millions of requests without any hassle. This is not possible with other video thumbnail generation libraries available in Node.js.
  • Cost savings: Ffmpeg aws lambda layer can help you save money on hosting and server costs since it runs on the cloud and scales up automatically based on the requests.
  • Easy to use: ffmpeg aws lambda layer is easy to use and requires minimal setup and configuration. All you need to do is upload your video and specify the output size, and the layer will generate the thumbnails for you.
  • Enhanced security: ffmpeg aws lambda layer is secure and highly reliable, ensuring that your videos and thumbnails are safe and secure.

Conclusion

In conclusion, using FFmpeg Lambda Layer with Node.js and S3 is an effective solution for generating video thumbnails. It is a convenient and cost-effective way to quickly generate thumbnails for your video assets. The process is simple and straightforward, and the results are of a high quality. With this solution, you can easily create thumbnails for your videos, allowing you to better market and promote them.