[OSS best practice] JAVA implements RTMP push stream upload OSS signature URL

Keywords: Java Mac SDK Python

Background introduction

OSS supports the use of RTMP protocol to push H264 encoded video stream and AAC encoded audio stream to OSS. Audio and video data pushed to OSS can be played on demand; in application scenarios that are not sensitive to delay, it can also be used for live broadcast. The RTMP push stream upload process is to create a live channel and generate a push stream address. This is also described in the official help document. For details, please refer to the document“ RTMP streaming upload ". As the currently provided example is Python, this article mainly introduces how to use JAVA to generate the signature URL of LiveChannel, including the push stream address and play address.

Signature URL format

At present, the streaming address and playback address obtained by the CreateLiveChannelResult class of OSS JAVA SDK do not have signature parameters. If the Bucket permission is private, the signature URL must be used to push the stream. The push stream address with signature is as follows:
rtmp://${bucket}.${host}/live/${channel}?OSSAccessKeyId=xxx&Expires=yyy&Signature=zzz&${params}

  • Live: the app name of the RTMP protocol. OSS uses live.
  • params: push flow parameter. The format is the same as the query string of HTTP request, that is, vara = valuea & varb = valueb.

The parameters and descriptions contained in the signature rule of push stream address are shown in the following table.

You can use playlistName to specify the name of the generated m3u8 file, whose value covers the configuration in LiveChannel.

The calculation rules of Signature are as follows

base64(hmac-sha1(AccessKeySecret,
+ Expires + "\n"
+ CanonicalizedParams
+ CanonicalizedResource))

The parameters and descriptions involved in the Signature calculation rules are shown in the following table

Create LiveChannel

Refer to the JAVA SDK of OSS Installation document Introduce the Java SDK. import the following classes
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CreateLiveChannelRequest;
import com.aliyun.oss.model.CreateLiveChannelResult;

Create LiveChennel through CreateLiveChannelRequest class, and obtain the streaming address and playback address through CreateLiveChannelResult. The example code is as follows

public static void main(String[] args) {
    // TODO Auto-generated method stub
    // endpoint take Hangzhou as an example. Please fill in other region s according to the actual situation
    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // The cloud account AccessKey has all API access rights. It is recommended to follow Alibaba cloud security best practices, create and use RAM sub accounts for API access or daily operation and maintenance. Please log in https://ram.console.aliyun.com to create
    String accessKeyId = "<Your AccessKeyId>";
    String accessKeySecret = "<Your AccessKeySecret>";
    String bucketName = "<Your Bucket Name>";
    String liveChannelName = "testChannel";//The name of your LiveChannel, such as testChannel
    // Create an OSSClient instance
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);        
    //Create livechannel, print streaming address and playback address (unsigned)
    CreateLiveChannelRequest request = new CreateLiveChannelRequest(bucketName, liveChannelName);
    CreateLiveChannelResult result = new CreateLiveChannelResult();
    result = ossClient.createLiveChannel(request);
    System.out.println("Streaming address:"+result.getPublishUrls());
    System.out.println("Play address:"+result.getPlayUrls());        
    // Close client
    ossClient.shutdown();        
}

Generate signature push stream URL

Introduce the following dependencies
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

private final static String CHARSET_UTF8 = "utf8";
private final static String ALGORITHM = "HmacSHA1";

Construct signature string function, return signature string signString

public static String buildSignString(String Expires,String CanonicalizedParams,String CanonicalizedResource){
    String signString = Expires + "\n"
            + CanonicalizedParams + "\n"
            + CanonicalizedResource;
    return signString;
}    

The function to calculate the signature. The parameter is the signature string signString+AccessKeySecret

public static String hmacSha1(String signString, String AccessKeySecret) {
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(AccessKeySecret.getBytes(), ALGORITHM);
        mac.init(keySpec);
        byte[] rawHmac;
        rawHmac = mac.doFinal(signString.getBytes(CHARSET_UTF8));
        return new String(Base64.encodeBase64(rawHmac));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Main function, generate streaming URL


public static void main(String[] args) throws Exception{        
    String bucketName= "<Your Bucket Name>";
    String Endpoint= "oss-cn-hangzhou.aliyuncs.com";//Endpoint
    String channelName = "testChannel";//liveCahnnel name
    String CanonicalizedParams = "playlistName:playlist.m3u8";//The format is "playlistName: < the specified m3u8 name >
    String CanonicalizedResource = "/test-bucket/testChannel";//CanonicalizedResource format is / BucketName/ChannelName
    String accessKeyId= "<Your AccessKeyId>";
    String secretAccessKey= "<Your AccessKeySecret>";
    String Expires = Long.toString(System.currentTimeMillis()/1000L+3600); //Generate a unix timestamp Expires to define the URL expiration time
    String Signature = (hmacSha1(buildSignString(Expires,CanonicalizedParams,CanonicalizedResource),secretAccessKey));
    
    //The format of push stream address is: RTMP: / / bucketname. Endpoint / Live / channelname? PlaylistName = playlist. M3u8 & expires = XXX & ossaccesskeyid = XXX & Signature = XXX
    System.out.println("Streaming address is\n"+"rtmp://"+bucketName+"."+Endpoint+"/live/"+channelName+"?playlistName=playlist.m3u8"+"&Expires="+Expires+"&OSSAccessKeyId="+accessKeyId+"&Signature="+Signature);

}

Generate signature playback URL

The signed playback address of m3u8 can be generated directly by the generatedesignedurl method in the Java SDK. The example is as follows

    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    Date expiration = new Date(new Date().getTime() + 360000 * 1000);
    java.net.URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
    System.out.println(url);
    ossClient.shutdown();

Posted by LOUDMOUTH on Thu, 05 Mar 2020 03:41:22 -0800