How to convert any input video file format in S3 bucket to any other video file format using Elastic Transcoder and Lambda
Tags: aws, awselastictranscoder, awslambda, security
Published: 2021-06-27 18:22:18

“Challenges faced to find the solution of how to convert the video file format from .mp3 to .ts format within some seconds”. I have checked different ways so that I can get my video file format conversion within a few seconds and within my budget. I got the solution by using an amazon elastic transcoder service in which I am able to set the configuration of the transcoding pipeline and able to create my custom presets as well. The cost of the pipeline is in my budget. Even I can create different presets as 1M, 1.5M, 600K and many more as per my need or can use the existing preset as well. I have created code for lambda function with s3 trigger which automatically generates the output in s3 bucket whenever i do input in my bucket of any video file format. My output will be based on the lambda code of preset value which has been set. 

Amazon Elastic Transcoder is media transcoding in the cloud. It is designed to be a highly scalable, easy to use and a cost effective way for developers and businesses to convert (or “transcode”) media files from their source format into versions that will playback on devices like smartphones, tablets and PCs. 

What's New with Amazon Elastic Transcoder??

- Amazon Elastic Transcoder Adds Support For Clip Stitching
- Amazon Elastic Transcoder Available In The Asia Pacific (Mumbai) Region
- Amazon Elastic Transcoder Now Publishes Operational Metrics to Amazon CloudWatch
- Amazon Elastic Transcoder Available In The Asia Pacific (Sydney) Region
- Amazon Elastic Transcoder Adds Support For WAV
- Amazon Elastic Transcoder Now Supports MPEG-DASH
- Amazon Elastic Transcoder Adds Support for VP9

To learn more, read the [AWS Elastic Transcoder](https://docs.aws.amazon.com/elastictranscoder/latest/developerguide/introduction.html). 

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration. Just upload your code as a ZIP file or container image, and Lambda automatically and precisely allocates compute execution power and runs your code based on the incoming request or event, for any scale of traffic. You can set up your code to automatically trigger from 140 AWS services or call it directly from any web or mobile app. You can write Lambda functions in your favorite language (Node.js, Python, Go, Java, and more) and use both serverless and container tools, such as AWS SAM or Docker CLI, to build, test, and deploy your functions. To learn more, read the [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html).
 
In this post, you will get to know how to convert any input video file format in S3 bucket to any other video file format using Elastic Transcoder and Lambda. Here I have taken two S3 buckets and then created a transcode pipeline with preset. And set a lambda code with IAM role and set a S3 trigger on it which will automatically generate the output video files of different formats in the s3 bucket. 

#Prerequisites
You’ll need an Amazon Simple Storage Service for this post. [Getting started with amazon Simple Storage Service](https://aws.amazon.com/s3/getting-started/) provides instructions on how to create a bucket in simple storage service. For this blog, I assume that I have two buckets for input and output of videos.

#Architecture Overview    
##Diagram 
![Architectural Flow Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fnqcb45elpjlm0ujci9z.png)                                                                                                   
The architectural diagrams show the overall deployment architecture with data flow, AWS S3, AWS Elastic Transcoder and AWS Lambda.

#Solution overview
The blog post consists of the following phases:
1. Create AWS Elastic Transcoder Pipeline and Presets
2. Create IAM role and Lambda function with S3 trigger
3. Testing of video file format and check of cloudwatch logs

I have two S3 bucket for input and output of video as below →
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gawvokokbqjpkwq567my.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rbeqkdernbkh7rg33sm.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzr50hjs6zzdssgwxypd.png)

##Phase 1: Create AWS Elastic Transcoder Pipeline and Presets
1. Open the AWS Elastic Transcoder console and create a new pipeline.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/khi2bintlumgi6quhdrd.png)
2. In the new pipeline, give the pipeline name as transcodepipeline. Choose the source bucket and IAM role to be as default only. In configuration of s3 bucket for transcoded files and playlists, give bucket name as destination bucket and storage class as standard.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rd97wdfjlkp32bhhdgjl.png)
3. Click on add permission and choose grantee type as Amazon S3 Group. And Choose grantee as All Users with Open/Download Access only. And leave other options as default and then create the pipeline.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zuw0bptcnm1kigy3dnju.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3e3rtu1jahwub6t19j2.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ssj7088cckpeu0dcyvr.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5u109ivk3f3wk7zvnds.png)
4. We can even schedule the job for our pipeline as per requirement from Jobs option.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fmksemjxu7yk7rafa0de.png)
5. We can create a new preset or use the existing system preset as well. Here I have created 4 presets of the same configuration for different Generic as HLS 400k, HLS 600k, HLS 1.5M and HLS 2M.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mt3x1zzms5bokk1x96dw.png)
6. Create a new preset named as Preset: HLS 400k. Choose container type as ts and tick all available settings. Set video max frame rate as 30 and leave other settings as default. Checkout other configurations as well for HLS 600k, HLS 1.5M and HLS 2M.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57fdj9k6qi8cskdq2ndn.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9ugtajudpv1wap8wvhc.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3pekudruxujms7iwsuru.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmr16ntudgft95dmm7r6.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtd2zhkobw86r1ytmvos.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ix7awlfogbrdgcl2jtut.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hufp36aw0zj4vpvzvhfj.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9q3wljea44qa57decot.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4u82y5n1ez1wbs4o8qs.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4tochl2vf7osdv893i1.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6w6gf4jh5bqdflnetmea.png)

##Phase 2: Create IAM role and Lambda function with S3 trigger
1. In AWS IAM console, create a role named as LambdaS3CW with policy as elastic transcoder full access, s3 full access and cloudwatch full access.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70k0sg45ymcdr4bzxnw0.png)
2. In AWS Lambda console, Create a lambda function named as transcoderfunction with IAM role LambdaS3CW and Node.js version. In the code section, set the pipeline id from the pipeline created and preset id from preset created. Also set the preset, thumbnail and playlist as per requirement in the code.

//Use the code snippet
'use strict';
var AWS = require('aws-sdk');
var s3 = new AWS.S3({
apiVersion: '2012–09–25'
});
var eltr = new AWS.ElasticTranscoder({
apiVersion: '2012–09–25',
region: 'ap-south-1'
});
exports.handler = function(event, context) {
console.log('Executing Elastic Transcoder');
var bucket = event.Records[0].s3.bucket.name;
var key = event.Records[0].s3.object.key;
var pipelineId = '1618142748073-skxu76';
if (bucket !== 'transcodevideo-src') {
context.fail('Incorrect Input Bucket');
return;
}
var srcKey =  decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));   //the object may have spaces
var newKey = key.split('.')[0];
var fk= "400K";
var sk= "600K";
var om= "1.5M";
var tm= "2M";
var th= "Thumb"
var params = {
PipelineId: pipelineId,
OutputKeyPrefix: newKey + '/',
Input: {
Key: srcKey,
FrameRate: 'auto',
Resolution: 'auto',
AspectRatio: 'auto',
Interlaced: 'auto',
Container: 'auto'
},
Outputs: [{
Key:  fk + '/' +'hls4K-' + newKey + '.ts',
ThumbnailPattern: th +'/'+'thumbs4K-{count}',
PresetId: '1562047543931-59morw',//HLS v3 400K/s
SegmentDuration:"5"
},
{
Key:  sk + '/' +'hls6K-' + newKey + '.ts',
ThumbnailPattern: th +'/'+'thumbs6K-{count}',
PresetId: '1562047718852-9h1hs7', //HLS v3 600K/s
SegmentDuration:"5"
},
{
Key:  om + '/' +'hls1.5M-' + newKey + '.ts',
ThumbnailPattern: th +'/'+'thumbs1.5M-{count}',
PresetId: '1562047826616-c3wgvg', //HLS v3 1.5M/s
SegmentDuration:"5"
},
,
{
Key:  tm + '/' +'hls2M-' + newKey + '.ts',
ThumbnailPattern: th +'/'+'thumbs2M-{count}',
PresetId: '1562047886667-378v0i', //HLS v3 2M/s
SegmentDuration:"5"
}
],
Playlists: [{
Format: 'HLSv3',
Name: 'hls-'+ newKey,
OutputKeys: [ fk+ '/' +'hls4K-'+ newKey + '.ts',sk + '/' +'hls6K-' + newKey + '.ts',om + '/' 
            +'hls1.5M-' + newKey + '.ts',,tm + '/' +'hls2M-' + newKey + '.ts']
}]
};
console.log('Starting Job');
eltr.createJob(params, function(err, data){
if (err){
console.log(err);
} else {
console.log(data);
}
context.succeed('Job well done');
});
};
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3p4p3bp7jjsnaivme1n8.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5rrftpd36lytu9lndoaq.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhwrcg1v5pjmva4yd5ja.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/im7ezwozoxsr8ddvdt3l.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7uz0iwczhnkzcmx7j0gs.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ei16el4bvsk31sakfjvd.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzwb3uxgg22avpf8xmla.png)
3.Set the lambda function timeout as 5 min 0 sec and set a S3 trigger for the source bucket. So that whenever there is an input of any video file format in the source bucket the trigger automatically converts the video format as per preset and saves the output in the destination bucket. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtpt2sjz1y2ycgdzea7u.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9n3tfnnuhh5okscafdym.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q20rh2n6jfa45qmkpw6d.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2hmqt07733siml1q0zj.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkbohh17xkyp2makchzs.png)
4.Deploy and test the lambda code to check the error in function.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y2xts3hd1v4ymqjy4tof.png)

##Phase 3: Testing of video file format and check of cloudwatch logs
1. I have input the .mp4 video in the source bucket and got the results of the video in a different file format in the destination bucket. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5maaec97kcwji27itaa8.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84lc19r8ac31nxrvxpkh.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/knjinl06b089lfphgz1l.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zj8b50vs96ezc6q3q3fk.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z12po71u7hi51d68zsqv.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ukziuddwvoswyqsdl0jg.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rnr13e4e37anm5ph72du.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it7pdb1un6hirj7sjsji.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhc7exsn44psrvi9xb65.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tp7ianevu6slmjik9xs4.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/im076e43pxwxe5mqizh6.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3271346unp7p41x4tskf.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cq1nb45r74he7l06tmqt.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gz47pbdxunzqm81ejdol.png)
2. In the cloudwatch log group, we can see the logs of the video transcoding activity. And can also monitor the success or error of lambda function(or code) activity in lambda.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8raocr105y6fmxg0j7n.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zr21p9j7smfwuwdd44d7.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tenctktut3v75lzw9as.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8wykyoo9yazqdqsmm0ma.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oepy4rtfwxjnco7wrxu3.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zpwbxuv399r5e5fdiwbc.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7x6rho5e6evswlui34r4.png)

#Clean-up
Delete the environment as: S3 bucket, elastic transcoder(preset, pipeline), IAM role, Lambda function and cloudwatch log group.

#Pricing
I review the pricing and estimated cost of this example. 
For Elastic Transcoder →
Cost of SD content transcoded for 20 minutes = $0.30
For Lambda →
Cost of request and lambda-GB per second = $0.00
For Simple Storage Service →
Cost of APS3-Requests = $0.01
For cloudwatch, data transfer and simple notification (under free tier) →	 
Cost = $0.00 
Total Cost = $(0.30+0.00+0.01+0.00) = $0.31

#Summary
In this post, I have shown you how to convert any input video file format in S3 bucket to any other video file format using Elastic Transcoder and Lambda. 
For more details on elastic transcoder and lambda service, Checkout Get started with AWS Elastic Transcoder and AWS Lambda, open the [AWS Elastic Transcoder console](https://ap-south-1.console.aws.amazon.com/elastictranscoder/home?region=ap-south-1#getting-started:) and [AWS Lambda console](https://ap-south-1.console.aws.amazon.com/lambda/home?region=ap-south-1#/functions). To learn more, read the [AWS Elastic Transcoder documentation](https://docs.aws.amazon.com/elastic-transcoder/?id=docs_gateway) and [AWS Lambda documentation](https://docs.aws.amazon.com/lambda/?id=docs_gateway). 

Thanks for reading!

Connect with me: [Linkedin](https://www.linkedin.com/in/gargee-bhatnagar-6b7223114)