All Products
Search
Document Center

ApsaraVideo VOD:Media processing

Last Updated:Aug 22, 2023

This topic provides examples on how to use the API operations of the media processing module. The API operations are encapsulated in ApsaraVideo VOD SDK for Python. You can call the API operations to submit transcoding and snapshot jobs, query snapshot data, and preprocess videos in the production studio.

Usage notes

  • In this example, an AccessKey pair is used to initialize a client instance.

  • For more information about the request and response parameters of this operation, visit OpenAPI Explorer. You can click API Documentation in the top navigation bar to view information related to the API operation.

  • This topic provides sample code only for some complex API operations. To obtain sample code for other API operations, perform the following operations: Visit Alibaba Cloud OpenAPI Explorer. In the left-side navigation pane, find the API operation whose sample code you want to obtain and specify the required parameters on the Parameters tab. Then, click Initiate Call. On the SDK Sample Code tab, select the language to view and download the sample code.

Initialize a client

Before you use the SDK, initialize a client. For more information, see Initialization.

Submit a transcoding job without encryption

You can call the SubmitTranscodeJobs operation to submit a transcoding job without encryption.

Click SubmitTranscodeJobs to learn more about this API operation.

Sample code:

Note

The following code provides an example on transcoding without encryption. For more information about video encryption supported by Alibaba Cloud, see Alibaba Cloud proprietary cryptography.

"""
* Construct watermark parameters to be overridden. You can override only the URL of an image watermark and the content of a text watermark.
* Make sure that the ID of the watermark that you want to overwrite is associated with the ID of the transcoding template that you use. The ID of the transcoding template is specified by TranscodeTemplateId.
* You can call this operation to add only a watermark whose ID is associated with the ID of the transcoding template that you use.
"""
def build_override_params():
    # Override watermarks.
    watermarks = []

    // Override an image watermark. Example of the URL of an image file: https://192.168.0.0/16/watermarks/sample****.png.
    watermark1 = {'WatermarkId': '<watermarkId>', 'FileUrl': '<your File URL>'}
    watermarks.append(watermark1)

    # Override a text watermark.
    watermark2 = {'WatermarkId': '<watermarkId>', 'Content': 'new Text'}
    watermarks.append(watermark2)

    return {'Watermarks': watermarks}


"""  Start transcoding.   """
from aliyunsdkvod.request.v20170321 import SubmitTranscodeJobsRequest
def normal_submit_transcode_jobs(clt):
    request = SubmitTranscodeJobsRequest.SubmitTranscodeJobsRequest()

    # Specify the ID of the video that you want to transcode.
    request.set_VideoId('<videoId>')

    # Specify the transcoding template group.
    request.set_TemplateGroupId('<templateGroupId>')

    """
    # Configure optional parameters to overwrite watermarks.
    overrideParams = build_override_params()
    request.set_OverrideParams(json.dumps(overrideParams))
    """

    request.set_accept_format('JSON')
    response = json.loads(clt.do_action_with_exception(request))
    return response

try:
    clt = init_vod_client()
    jobs = normal_submit_transcode_jobs(clt)
    print(jobs['TranscodeJobs']['TranscodeJob'])
    print(json.dumps(jobs, ensure_ascii=False, indent=4))

except Exception as e:
    print(e)
    print(traceback.format_exc())

Submit a transcoding job with HLS encryption enabled

You can call the SubmitTranscodeJobs operation to submit a transcoding job with HLS encryption enabled.

Click SubmitTranscodeJobs to learn more about this API operation.

Sample code:

Note

The following code provides an example on transcoding with HLS encryption enabled. For more information, see HLS encryption.

"""
* Optional configurations of HLS encryption. If you do not use HLS encryption, these configurations are not required.
"""
from aliyunsdkvod.request.v20170321 import GenerateKMSDataKeyRequest
from aliyunsdkcore.http import protocol_type
def build_encrypt_config(clt):
    try:
        # Generate a random data key for encryption. The response contains the plaintext and ciphertext of the data key.
        # Specify only the ciphertext for HLS encryption.
        request = GenerateKMSDataKeyRequest.GenerateKMSDataKeyRequest()

        request.set_protocol_type(protocol_type.HTTPS)
        request.set_accept_format('JSON')
        response = json.loads(clt.do_action_with_exception(request))

        // The URI of the operation that is used to decrypt the data key. To obtain the URI, concatenate the URL of the decryption service and the ciphertext of the data key. The ciphertext to decrypt varies among videos. Take note that you must deploy the decryption service.
        # You can customize the name of the Ciphertext parameter. The name in this example is only for reference.
        # Example of decryptKeyUri: http://example.aliyundoc.com/decrypt?' + 'Ciphertext=' + response['CiphertextBlob.
        decryptKeyUri = ['<your decryptKeyUri>']

        return {'DecryptKeyUri': decryptKeyUri, 'KeyServiceType': 'KMS', 'CipherText': response['CiphertextBlob']}

    except Exception as e:
        print(e)
        #print(traceback.format_exc())
        return None


"""  Start transcoding.   """
from aliyunsdkvod.request.v20170321 import SubmitTranscodeJobsRequest
def hlsencrypt_submit_transcode_jobs(clt):
    request = SubmitTranscodeJobsRequest.SubmitTranscodeJobsRequest()

    # Specify the ID of the video that you want to transcode.
    request.set_VideoId('<videoId>')

    # Specify the transcoding template group.
    request.set_TemplateGroupId('<templateGroupId>')

    # Use Key Management Service (KMS) to generate a random encryption key.
    encryptConfig = build_encrypt_config(clt)
    if encryptConfig is not None:
        request.set_EncryptConfig(json.dumps(encryptConfig))

    request.set_accept_format('JSON')
    response = json.loads(clt.do_action_with_exception(request))
    return response

try:
    clt = init_vod_client()
    jobs = hlsencrypt_submit_transcode_jobs(clt)
    print(jobs['TranscodeJobs']['TranscodeJob'])
    print(json.dumps(jobs, ensure_ascii=False, indent=4))

except Exception as e:
    print(e)
    print(traceback.format_exc())

Submit a snapshot job

You can call the SubmitSnapshotJob operation to submit a snapshot job.

Click SubmitSnapshotJob to learn more about this API operation.

Sample code:

Note

For more information about how to create a snapshot template, see Create a snapshot template.

from aliyunsdkvod.request.v20170321 import SubmitSnapshotJobRequest
def submit_snapshot_job(clt):
    request = SubmitSnapshotJobRequest.SubmitSnapshotJobRequest()

    # Specify the ID of the video from which you want to capture snapshots.
    request.set_VideoId('<videoId>')

    # Specify the ID of the snapshot template.
    #request.set_SnapshotTemplateId('<snapshotTemplateId>')

    # If you specify the ID of the snapshot template, the following parameters are ignored:
    request.set_Count(50)
    request.set_SpecifiedOffsetTime(0)
    request.set_Interval(1)
    request.set_Width(200)
    request.set_Height(200)

    # Configure image sprite-related parameters. This step is optional.
    spriteSnapshotConfig = {'CellWidth': 120, 'CellHeight': 68, 'Columns': 3,
                            'Lines': 10, 'Padding': 20, 'Margin': 50}
    # Specify whether to retain the source image after an image sprite is generated.
    spriteSnapshotConfig['KeepCellPic'] = 'keep'
    spriteSnapshotConfig['Color'] = 'tomato'
    request.set_SpriteSnapshotConfig(json.dumps(spriteSnapshotConfig))

    request.set_accept_format('JSON')
    response = json.loads(clt.do_action_with_exception(request))
    return response

try:
    clt = init_vod_client()
    job = submit_snapshot_job(clt)
    print(json.dumps(job, ensure_ascii=False, indent=4))

except Exception as e:
    print(e)
    print(traceback.format_exc())

Query snapshot data

You can call the ListSnapshots operation to query snapshot data.

Click ListSnapshots to learn more about this API operation.

Preprocess videos in the production studio

You can call the SubmitPreprocessJobs operation to preprocess videos in the production studio.

Click SubmitPreprocessJobs to learn more about this API operation.