com.brightcove.zartan.encode.TencodeAPI.java Source code

Java tutorial

Introduction

Here is the source code for com.brightcove.zartan.encode.TencodeAPI.java

Source

/**
 * Copyright (C) 2012 Brightcove Inc. All Rights Reserved. No use, copying or distribution of this
 * work may be made except in accordance with a valid license agreement from Brightcove Inc. This
 * notice must be included on all copies, modifications and derivatives of this work.
 * 
 * Brightcove Inc MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. BRIGHTCOVE SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS
 * SOFTWARE OR ITS DERIVATIVES.
 * 
 * "Brightcove" is a registered trademark of Brightcove Inc.
 */
package com.brightcove.zartan.encode;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import com.brightcove.zartan.common.account.Account;
import com.brightcove.zartan.common.account.Credentials;
import com.brightcove.zartan.common.account.ZencoderCredentials;
import com.brightcove.zartan.common.encode.TranscodeEntryPointEnum;
import com.brightcove.zartan.common.encode.TranscodeInfo;
import com.brightcove.zartan.common.encode.TranscodeOption;
import com.brightcove.zartan.common.encode.TranscodeOption.VideoBitrateType;
import com.brightcove.zartan.common.encode.TranscodeOption.VideoCodecProfile;
import com.brightcove.zartan.common.encode.TranscodeOption.VideoContainer;
import com.brightcove.zartan.common.environment.TranscodeEnvironment;
import com.brightcove.zartan.common.file.TranscodedVideoFile;
import com.brightcove.zartan.common.verifier.Verifiable;
import com.brightcove.zartan.common.verifier.VerifiableTranscode;

public class TencodeAPI implements Transcoder {

    @Override
    public Verifiable submitTranscode(TranscodeInfo transcode, TranscodeEnvironment env, Account acc) {
        VerifiableTranscode toVerify = new VerifiableTranscode(transcode, env, acc,
                TranscodeEntryPointEnum.TENCODE_API);
        toVerify.setTranscodeTime(System.currentTimeMillis());

        // TODO:throw if env has a bad url
        URI targetURL = null;
        try {
            targetURL = new URL(env.getTranscodeApiUrl()).toURI();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        JsonNode response = encodeFile(transcode, targetURL, toVerify);

        return toVerify;
    }

    private JsonNode encodeFile(TranscodeInfo transcode, URI transcodeApiUrl, VerifiableTranscode toVerify) {

        HttpPost method = new HttpPost(transcodeApiUrl);

        String json = getJson(transcode, toVerify);
        System.out.println(json);

        StringEntity entity;
        try {
            entity = new StringEntity(json);

            entity.setContentType("application/json");

            method.setEntity(entity);

            HttpResponse response = null;
            DefaultHttpClient httpAgent = new DefaultHttpClient();

            response = httpAgent.execute(method);

            // Make sure the HTTP communication was OK (not the same as an error in the Media API
            // reponse)
            Integer statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpAgent.getConnectionManager().shutdown();
                // TODO:throw inteligent failure
                return null;
            }

            // Parse the response
            HttpEntity resentity = response.getEntity();
            JsonNode jsonObj = getJSONFromEntity(resentity);
            httpAgent.getConnectionManager().shutdown();
            return jsonObj;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    private String getJson(TranscodeInfo transcode, VerifiableTranscode toVerify) {
        String json = "{ \"sourceURL\": \"" + transcode.getFile().getHttpLocation() + "\"," + "\"renditions\": ["
                + getOutputObject(transcode, toVerify) + "]" +

                "}";
        return json;
    }

    private String getOutputObject(TranscodeInfo transcode, VerifiableTranscode toVerify) {
        String output = "";
        for (TranscodeOption t : transcode.getOptions().getCopyOfOptions()) {
            output += "{";

            String target = "/mnt/scratch2/upload/upload/transcode-output/zartan/output-" + t.getOptionId()
                    + transcode.getFile().getFileName() + ".mp4";
            output += " \"targetURL\": \"file://" + target + "\",";
            toVerify.addTranscodedFile(new TranscodedVideoFile(target, t));

            if (t.getVideoContainer().equals(VideoContainer.M2TS)) {
                output += "\"format\": \"apple-hls\",";
            } else if (t.getVideoContainer().equals(VideoContainer.MP4)) {
                output += " \"format\": \"mp4\",";
            } else if (t.getVideoContainer().equals(VideoContainer.FLV)) {
                output += " \"format\": \"flv\",";
            }
            output += " \"video_codec\": \"" + t.getCodec().toString().toLowerCase() + "\",";
            output += " \"audio_codec\": \"aac\",";
            output += " \"frame_size\": \"" + t.getWidth() + "x" + t.getHeight() + "\",";

            // output+="\"quality\": 5,";
            output += " \"video_bitrate\": " + t.getVideoBitrate() + ",";

            output += " \"audio_bitrate\": " + t.getAudioBitrate() + ",";
            // output+="\"audio_quality\": 5,";
            if (!t.isOnePass() && t.getVideoBitrateType() == VideoBitrateType.VBR) {
                output += " \"rate_control\": \"vbr_two_pass\",";
            } else if (t.isOnePass() && t.getVideoBitrateType() == VideoBitrateType.VBR) {
                output += " \"rate_control\": \"vbr_one_pass\",";
            } else {
                output += " \"rate_control\": \"cbr\",";
            }

            if (t.getKeyFrameRate() != -1) {
                output += " \"keframe_rate\": \"" + t.getKeyFrameRate() + "_second\",";
            }

            if (t.getFramesPerSecond() != -1) {
                output += " \"frames_per_second\": " + t.getFramesPerSecond() + ",";
            }

            if (t.isAudioOnly()) {
                output += " \"ignore_video\": true,";
            }

            if (t.getCodecProfile() == VideoCodecProfile.H264_HIGH) {
                output += " \"video_profile\": \"H264_HIGH\",";

            }
            output = output.substring(0, output.length() - 1);
            output += "},";
        }
        output = output.substring(0, output.length() - 1);
        return output;
    }

    /**
     * Downloads and parses the response stream of an http call.
     * 
     * @param entity
     * @return Parsed JsonNode object
     * @throws MediaAPIError
     * @throws IOException
     * @throws IllegalStateException
     */
    private JsonNode getJSONFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        if (entity == null) {
            return null;
        }

        String output = "";
        String buffer = "";
        InputStream instream;

        instream = entity.getContent();

        String charSet = "UTF-8";

        buffer = IOUtils.toString(instream, charSet);

        // Parse JSON
        JsonNode jsonObj = null;
        if (buffer.equals("null")) {
            buffer = "{\"result\":null}";
        }
        jsonObj = mapper.readTree(buffer);

        return jsonObj;
    }

}