Converting Videos Using AWS Elemental Mediaconvert In Java

Posted By : Himanshu Bhatt | 22-Jun-2019

 Introduction

Hi in this blog today I will show you how to convert videos from one format to another using AWS elemental mediaconvert using java. It is cloud-based media convert and the operations are not very heavy everything happens in the cloud. It is currently available with s3 storage only.

For setting up it and running it locally you need to have the following in your system installed:

  1. Aws account and s3 bucket.
  2. AWS Sam CLI installed locally and configure your roles, keys, and region.
  3. Eclipse with amazon SDK tools.
  4. Maven for building the file.
  5. Docker to run it locally.

We will make a lambda function that will get triggered on an event and it will start converting the videos provided to it we need to provide the file path of the source bucket and the name of the destination bucket. So the following code snippet implements the code:

 

package com.amazonaws.lambda.upload;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.amazonaws.lambda.constants.Constants;
import com.amazonaws.lambda.staticfunction.Function;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.mediaconvert.AWSMediaConvert;
import com.amazonaws.services.mediaconvert.AWSMediaConvertClientBuilder;
import com.amazonaws.services.mediaconvert.model.CreateJobRequest;
import com.amazonaws.services.mediaconvert.model.CreateJobResult;
import com.amazonaws.services.mediaconvert.model.DescribeEndpointsRequest;
import com.amazonaws.services.mediaconvert.model.JobSettings;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertLambda implements RequestHandler<S3Event, Map<String, Object>> {

	@Override
	public Map<String, Object> handleRequest(S3Event event, Context context) {
		String region = "us-east-2";
		Map<String, Object> map = new HashMap<>();
		AWSMediaConvert mediaConvertClient = AWSMediaConvertClientBuilder.standard().withRegion(region).build();
		DescribeEndpointsRequest request = new DescribeEndpointsRequest();
		String destinationBucket = System.getenv(Constants.DESTINATION_BUCKET);
		System.out.println("destination bucket is ::: " + destinationBucket);
		String sourceBucket = System.getenv(Constants.BUCKET);
		String sourceUrl = "s3://" + sourceBucket + File.separator + "bird.avi";
		String destinationUrl = "s3://" + destinationBucket + File.separator + "mediaDestination/";
		System.out.println("Source bucket is ::::" + sourceBucket);
		String role = System.getenv(Constants.ROLE);
		System.out.println("Role ::::" + role);
//        String endpoint = mediaConvertClient.describeEndpoints(request).getEndpoints().get(0).getUrl();
		JobSettings jobSettings = null;
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String fileName = Function.readFile("resolution720.json");
			JSONObject json = new JSONObject(fileName);
			System.out.println(json);
			JSONArray outputGroups = json.getJSONArray("outputGroups");

			JSONObject outputGroupSettings = outputGroups.getJSONObject(0);
			JSONObject fileSettings = outputGroupSettings.getJSONObject("outputGroupSettings");
			JSONObject fileGroupSettings = fileSettings.getJSONObject("fileGroupSettings");
			fileGroupSettings.put("destination", destinationUrl);
			JSONArray inputs = json.getJSONArray("inputs");
			JSONObject fileInput = inputs.getJSONObject(0);
			fileInput.put("fileInput", sourceUrl);
			try (FileWriter file = new FileWriter("/tmp/job.json")) {
				file.write(json.toString());
				System.out.println("Successfully updated json object to file...!!");
			}
			String newJobFile = Function.readFile("/tmp/job.json");
			jobSettings = objectMapper.readValue(newJobFile, JobSettings.class);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		CreateJobRequest jobParam = new CreateJobRequest().withSettings(jobSettings);

		CreateJobResult mcResponse = new CreateJobResult();

		mcResponse = mediaConvertClient.createJob(jobParam);
		return (Map<String, Object>) map.put("result", mcResponse.toString());

	}

}

So here in the above code snippet, we have the lambda function that gets triggered when there is an S3 event that occurs. We provide the region of our AWS account. We provide the source bucket details and the destination bucket. We have a JSON file of job settings which have all the settings the video in which we want as the output for more info for these settings you can read the documentation provided by the AWS, we only update the source URL and the destination URL in that JSON file and we map that json file using object mapper with JobSettings class which is provided by the AWS API. Then we create the job request and send that request.

 

To run this locally using aws sam we have to make the template.yml file and in that we have to pass the name of the handler class.

 

 post
Method:upload
            / Path:
            Properties: Api
          Type:
          ListProducts:
        Events:Function
:Serverless::AWS: Type:
    Products:

  Resources: AWS Lambda Sample Project

Description:
31-10-2016-Serverless:AWS: Transform:
'09-09-2010' :AWSTemplateFormatVersion 

We have to make the build of this application we can use maven for that we will create a jar of this all by typing the command mvn clean install in the directory of the project.

To run it locally using sam we will type this command:

sam local invoke "Products" --event event_file.json

Thankyou.

 
 
 
 

About Author

Author Image
Himanshu Bhatt

Himanshu is a bright java developer. He is keen to learn new technologies. His hobbies are to travel and listen music.

Request for Proposal

Name is required

Comment is required

Sending message..