All Products
Search
Document Center

ApsaraVideo Media Processing:Create a workflow for HLS encryption

Last Updated:Feb 25, 2025

This topic provides the sample code for using ApsaraVideo Media Processing (MPS) SDK for Java to create a workflow for HTTP-Live-Streaming (HLS) encryption.

Overview

You can also call the AddMediaWorkflow operation to create a workflow for HLS encryption. For more information, see AddMediaWorkflow.

Dependencies

  • Install MPS SDK for Java. For more information, see Install Alibaba Cloud SDK for Java.

  • Add other dependencies.

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.68.noneautotype</version>
    </dependency>

Sample code

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;
/**
 * *****   Usage notes     ******
 * This sample code creates a workflow for HLS encryption. If you perform HLS encryption for the first time, you must use this sample code to create a workflow for HLS encryption and run the workflow once to ensure that system configurations are valid.
 * The topology of the workflow is complex. You must pay attention to the accuracy of parameter settings when you modify the topology. For more information, see "AddMediaWorkflow" at https://www.alibabacloud.com/help/zh/apsaravideo-for-media-processing/latest/api-mts-2014-06-18-addmediaworkflow.
 * The KeyUri parameter specifies the endpoint used to obtain the decryption key. Make sure that the specified key uniform resource identifier (URI) is valid. Otherwise, the decryption fails.
 * For more information about HLS encryption, see xxxxxxxxxxxx.
 */
public class MediaHlsWorkflow {

    // The ID of the MPS queue. To view the ID of an MPS queue, log on to the MPS console and choose Global Settings > MPS Queue and Callback in the left-side navigation pane.
    final static String PIPELINE_ID = "bee7a5b9e*******e40a0cbf";
    // The ID of the template. For more information about preset templates, visit https://www.alibabacloud.com/help/en/mps/developer-reference/preset-template-details.
    final static String TEMPLATE_ID = "S00000001-100020";
    final static String OSS_LOCATION = "oss-cn-shanghai";
    // The name of the input media bucket that is specified in the MPS console.
    final static String INPUT_BUCKET = "<your bucket name>";
    // The trigger path. The path name must end with a forward slash (/).
    final static String INPUT_PATH = "mps-test/demo/";
    // The name of the output media bucket that is specified in the MPS console.
    final static String OUTPUT_BUCKET = "<your bucket name>";
    // The encryption type. Set this parameter to hls-aes-128.
    final static String ENCRYPTION_TYPE = "hls-aes-128";
    // The endpoint used to obtain the decryption key. Example: http://example.aliyundoc.com.
    final static String HLS_KEY_URI = "http://127.0.0.1:8888";
    final static String ACT_START = "Act-Start";
    final static String ACT_ENCRYPTION = "Act-HLS-Encryption";
    final static String ACT_REPORT = "Act-Report";

    /**
     * <b>description</b> :
     * <p>Use your AccessKey pair to initialize the client.</p>
     * @return Client
     *
     * @throws Exception
     */
    public static com.aliyun.mts20140618.Client createClient() throws Exception {

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "mts.cn-shanghai.aliyuncs.com";
        return new com.aliyun.mts20140618.Client(config);
    }

    /**
     * Create a workflow for HLS encryption.
     * @return
     * @throws Exception
     */
    public static void addMediaHlsWorkflow() throws Exception {
        com.aliyun.mts20140618.Client client = MediaHlsWorkflow.createClient();
        com.aliyun.mts20140618.models.AddMediaWorkflowRequest addMediaWorkflowRequest = new com.aliyun.mts20140618.models.AddMediaWorkflowRequest()
                // The name of the watermark.
                .setName("workflow for HLS encryption")
                // The job output configuration.
                .setTopology(createWorkflow().toJSONString());

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // Write your own code to display the response of the API operation if necessary.
            client.addMediaWorkflowWithOptions(addMediaWorkflowRequest, runtime);
        } catch (TeaException error) {
            // In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes only. 
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes only. 
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

    /**
     * Create the topology of the workflow.
     * @return
     */
    private static JSONObject createWorkflow() {
        JSONObject workflow = new JSONObject();
        JSONObject activities = new JSONObject();
        activities.put(ACT_START, createStartActivity());
        activities.put(ACT_ENCRYPTION, createTrancodeActivity());
        activities.put(ACT_REPORT, createReportActivity());
        workflow.put("Activities", activities);
        workflow.put("Dependencies", createDependencies());
        return workflow;
    }

    /**
     * Add a start node to the workflow.
     * @return
     */
    private static JSONObject createStartActivity() {
        JSONObject startActivity = new JSONObject();
        startActivity.put("Name", ACT_START);
        startActivity.put("Type", "Start");
        startActivity.put("Parameters", buildStartParameters());
        return startActivity;
    }

    /**
     * Add the input configurations.
     * @return
     */
    private static JSONObject buildStartParameters() {
        JSONObject parameters = new JSONObject();
        parameters.put("PipelineId", PIPELINE_ID);
        // The structure of the input media bucket.
        JSONObject inputFile = new JSONObject();
        inputFile.put("Bucket", INPUT_BUCKET);
        inputFile.put("Location", OSS_LOCATION);
        inputFile.put("ObjectPrefix", INPUT_PATH);

        parameters.put("InputFile", inputFile);
        return parameters;
    }

    /**
     * Add a transcoding node to the workflow.
     * @return
     */
    private static JSONObject createTrancodeActivity() {
        JSONObject transcodeActivity = new JSONObject();
        transcodeActivity.put("Name", ACT_ENCRYPTION);
        transcodeActivity.put("Type", "Transcode");

        JSONObject transcodeParamters = new JSONObject();
        transcodeParamters.put("OutputBucket", OUTPUT_BUCKET);
        transcodeParamters.put("OutputLocation", OSS_LOCATION);
        transcodeParamters.put("Outputs", buildOutputsConfig());

        transcodeActivity.put("Parameters", transcodeParamters);
        return transcodeActivity;
    }

    /**
     * Add the output configurations.
     * @return
     */
    private  static JSONArray buildOutputsConfig() {
        JSONArray outputs = new JSONArray();
        JSONObject output = new JSONObject();
        output.put("ObjectRegex", ACT_ENCRYPTION + "/{RunId}/{FileName}");
        output.put("TemplateId", TEMPLATE_ID);
        output.put("Encryption", buildEncryption());
        outputs.add(output);
        return outputs;
    }

    /**
     * Add the encryption configurations.
     * @return
     */
    private static JSONObject buildEncryption() {
        JSONObject encryption = new JSONObject();
        encryption.put("Type", ENCRYPTION_TYPE);
        encryption.put("KeyUri", HLS_KEY_URI);
        return encryption;
    }

    /**
     * Add the configurations of the Report node.
     * @return
     */
    private static JSONObject createReportActivity() {
        JSONObject reportActivity = new JSONObject();
        reportActivity.put("Name", ACT_REPORT);
        JSONObject parameters = new JSONObject();
        parameters.put("PublishType","Auto");
        reportActivity.put("Parameters", parameters);
        reportActivity.put("Type", "Report");
        return  reportActivity;
    }

    /**
     * Add dependencies.
     * The edges in the topology. The edges indicate the dependencies among activities. 
     * @return
     */
    private static JSONObject createDependencies() {
        JSONObject dependencies = new JSONObject();
        JSONArray subActivityOfStart = new JSONArray();
        subActivityOfStart.add(ACT_ENCRYPTION);
        dependencies.put(ACT_START, subActivityOfStart);
        JSONArray subActivityOfTranscode = new JSONArray();
        subActivityOfTranscode.add(ACT_REPORT);
        dependencies.put(ACT_ENCRYPTION, subActivityOfTranscode);
        dependencies.put(ACT_REPORT, new JSONArray());
        return dependencies;
    }
}