Java tutorial
/** * 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 static org.junit.Assert.assertEquals; 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.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; 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.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 ZencodeAPI implements Transcoder { @Override public Verifiable submitTranscode(TranscodeInfo transcode, TranscodeEnvironment env, Account acc) { VerifiableTranscode toVerify = new VerifiableTranscode(transcode, env, acc, TranscodeEntryPointEnum.ZENCODE_API); toVerify.setTranscodeTime(System.currentTimeMillis()); ZencoderCredentials zc = null; for (Credentials c : acc.getCredentials()) { if (c instanceof ZencoderCredentials) { zc = (ZencoderCredentials) c; break; } } // TODO:throw if zc is bad // 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, zc); System.out.println(response); for (JsonNode rend : response.get("outputs")) { toVerify.addTranscodedFile(new TranscodedVideoFile(rend.get("url").asText(), transcode.getOptionById(rend.get("label").asLong()))); } return toVerify; } private JsonNode encodeFile(TranscodeInfo transcode, URI transcodeApiUrl, ZencoderCredentials zc) { HttpPost method = new HttpPost(transcodeApiUrl); BasicHeader keyHeader = new BasicHeader("Zencoder-Api-Key", zc.getApiKey()); method.addHeader(keyHeader); String json = getJson(transcode); 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 != 201) { 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) { String json = "{" + "\"input\": \"" + transcode.getFile().getHttpLocation() + "\"," + "\"output\": [" + getOutputObject(transcode) + "]" + "}"; return json; } private String getOutputObject(TranscodeInfo transcode) { String output = ""; for (TranscodeOption t : transcode.getOptions().getCopyOfOptions()) { output += "{"; output += "\"base_url\": \"s3://qatransnas/zencoder_output\","; if (t.getVideoContainer().equals(VideoContainer.M2TS)) { output += " \"type\": \"segmented\",\"format\": \"ts\","; } 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 += " \"width\": " + t.getWidth() + ","; output += " \"height\": " + t.getHeight() + ","; // output+="\"quality\": 5,"; output += " \"video_bitrate\": " + t.getVideoBitrate() / 1000 + ","; output += " \"audio_bitrate\": " + t.getAudioBitrate() / 1000 + ","; // output+="\"audio_quality\": 5,"; output += " \"one_pass\": " + t.isOnePass() + ","; if (t.getKeyFrameRate() != -1) { output += " \"forced_keyframe_rate\": " + (double) ((double) 1 / (double) t.getKeyFrameRate()) + ","; } if (t.getFramesPerSecond() != -1) { output += " \"frame_rate\": " + t.getFramesPerSecond() + ","; } if (t.isAudioOnly()) { output += " \"skip_video\": true,"; } if (t.getCodecProfile() == VideoCodecProfile.H264_BASE) { output += " \"h264_profile\": \"baseline\","; } else if (t.getCodecProfile() == VideoCodecProfile.H264_HIGH) { output += " \"h264_profile\": \"high\",\"h264_bframes\": 2,\"speed\": 1,"; } else if (t.getCodecProfile() == VideoCodecProfile.H264_HIGH) { output += " \"h264_profile\": \"main\",\"h264_bframes\": 2,\"speed\": 1,"; } output += " \"label\": \"" + t.getOptionId() + "\","; 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 MediaAPIException * @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; } }