Tutorial: Encode a remote file based on URL and stream the video - REST

Azure Media Services enables you to encode your media files into formats that can be played on a wide variety of browsers and devices. For example, you might want to stream your content in Apple's HLS or MPEG DASH formats. Before streaming, you should encode your high-quality digital media file. For encoding guidance, see Encoding concept.

This tutorial shows you how to encode a file based on a URL and stream the video with Azure Media Services using REST.

Play the video

This tutorial shows you how to:

  • Create a Media Services account
  • Access the Media Services API
  • Download Postman files
  • Configure Postman
  • Send requests using Postman
  • Test the streaming URL
  • Clean up resources

If you don't have an Azure subscription, create a free account before you begin.

Prerequisites

  • Create a Media Services account.

    Make sure to remember the values that you used for the resource group name and Media Services account name

  • Install the Postman REST client to execute the REST APIs shown in some of the AMS REST tutorials.

    We are using Postman but any REST tool would be suitable. Other alternatives are: Visual Studio Code with the REST plugin or Telerik Fiddler.

Download Postman files

Clone a GitHub repository that contains the Postman collection and environment files.

git clone https://github.com/Azure-Samples/media-services-v3-rest-postman.git

Access the Media Services API

To connect to Azure Media Services APIs, you use the Azure AD service principal authentication. The following command creates an Azure AD application and attaches a service principal to the account. You should use the returned values to configure your application.

Before running the script, you should replace the amsaccount and amsResourceGroup with the names you chose when creating these resources. amsaccount is the name of the Azure Media Services account where to attach the service principal.

The following command returns a json output:

az ams account sp create --account-name amsaccount --resource-group amsResourceGroup

This command produces a response similar to this:

{
  "AadClientId": "00000000-0000-0000-0000-000000000000",
  "AadEndpoint": "https://login.microsoftonline.com",
  "AadSecret": "00000000-0000-0000-0000-000000000000",
  "AadTenantId": "00000000-0000-0000-0000-000000000000",
  "AccountName": "amsaccount",
  "ArmAadAudience": "https://management.core.windows.net/",
  "ArmEndpoint": "https://management.azure.com/",
  "Region": "West US 2",
  "ResourceGroup": "amsResourceGroup",
  "SubscriptionId": "00000000-0000-0000-0000-000000000000"
}

If you would like to get an xml in the response, use the following command:

az ams account sp create --account-name amsaccount --resource-group amsResourceGroup --xml

Configure Postman

This section configures the Postman.

Configure the environment

  1. Open the Postman.

  2. On the right of the screen, select the Manage environment option.

    Manage env

  3. From the Manage environment dialog, click Import.

  4. Browse to the Azure Media Service v3 Environment.postman_environment.json file that was downloaded when you cloned https://github.com/Azure-Samples/media-services-v3-rest-postman.git.

  5. The Azure Media Service v3 Environment environment is added.

    Note

    Update access variables with values you got from the Access the Media Services API section above.

  6. Double-click on the selected file and enter values that you got by following the accessing API steps.

  7. Close the dialog.

  8. Select the Azure Media Service v3 Environment environment from the dropdown.

    Choose env

Configure the collection

  1. Click Import to import the collection file.

  2. Browse to the Media Services v3.postman_collection.json file that was downloaded when you cloned https://github.com/Azure-Samples/media-services-v3-rest-postman.git

  3. Choose the Media Services v3.postman_collection.json file.

    Import a file

Send requests using Postman

In this section, we send requests that are relevant to encoding and creating URLs so you can stream your file. Specifically, the following requests are sent:

  1. Get Azure AD Token for Service Principal Authentication
  2. Create an output asset
  3. Create a Transform
  4. Create a Job
  5. Create a Streaming Locator
  6. List paths of the Streaming Locator

Note

This tutorial assumes you are creating all resources with unique names.

Get Azure AD Token

  1. In the left window of the Postman, select "Step 1: Get AAD Auth token".

  2. Then, select "Get Azure AD Token for Service Principal Authentication".

  3. Press Send.

    The following POST operation is sent.

    https://login.microsoftonline.com/:tenantId/oauth2/token
    
  4. The response comes back with the token and sets the "AccessToken" environment variable to the token value. To see the code that sets "AccessToken" , click on the Tests tab.

    Get AAD token

Create an output asset

The output Asset stores the result of your encoding job.

  1. In the left window of the Postman, select "Assets".

  2. Then, select "Create or update an Asset".

  3. Press Send.

    • The following PUT operation is sent:

      https://management.azure.com/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/assets/:assetName?api-version={{api-version}}
      
    • The operation has the following body:

      {
      "properties": {
          "description": "My Asset",
          "alternateId" : "some GUID"
       }
      }
      

Create a transform

When encoding or processing content in Media Services, it is a common pattern to set up the encoding settings as a recipe. You would then submit a Job to apply that recipe to a video. By submitting new jobs for each new video, you are applying that recipe to all the videos in your library. A recipe in Media Services is called as a Transform. For more information, see Transforms and Jobs. The sample described in this tutorial defines a recipe that encodes the video in order to stream it to a variety of iOS and Android devices.

When creating a new Transform instance, you need to specify what you want it to produce as an output. The required parameter is a TransformOutput object. Each TransformOutput contains a Preset. Preset describes the step-by-step instructions of video and/or audio processing operations that are to be used to generate the desired TransformOutput. The sample described in this article uses a built-in Preset called AdaptiveStreaming. The Preset encodes the input video into an auto-generated bitrate ladder (bitrate-resolution pairs) based on the input resolution and bitrate, and produces ISO MP4 files with H.264 video and AAC audio corresponding to each bitrate-resolution pair. For information about this Preset, see auto-generating bitrate ladder.

You can use a built-in EncoderNamedPreset or use custom presets.

Note

When creating a Transform, you should first check if one already exists using the Get method. This tutorial assumes you are creating the transform with a unique name.

  1. In the left window of the Postman, select "Encoding and Analysis".

  2. Then, select "Create Transform".

  3. Press Send.

    • The following PUT operation is sent.

      https://management.azure.com/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/transforms/:transformName?api-version={{api-version}}
      
    • The operation has the following body:

      {
          "properties": {
              "description": "Standard Transform using an Adaptive Streaming encoding preset from the library of built-in Standard Encoder presets",
              "outputs": [
                  {
                  "onError": "StopProcessingJob",
              "relativePriority": "Normal",
                  "preset": {
                      "@odata.type": "#Microsoft.Media.BuiltInStandardEncoderPreset",
                      "presetName": "AdaptiveStreaming"
                  }
                  }
              ]
          }
      }
      

Create a job

A Job is the actual request to Media Services to apply the created Transform to a given input video or audio content. The Job specifies information like the location of the input video, and the location for the output.

In this example, the job's input is based on an HTTPS URL ("https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/").

  1. In the left window of the Postman, select "Encoding and Analysis".

  2. Then, select "Create or Update Job".

  3. Press Send.

    • The following PUT operation is sent.

      https://management.azure.com/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/transforms/:transformName/jobs/:jobName?api-version={{api-version}}
      
    • The operation has the following body:

      {
      "properties": {
          "input": {
          "@odata.type": "#Microsoft.Media.JobInputHttp",
          "baseUri": "https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/",
          "files": [
                  "Ignite-short.mp4"
              ]
          },
          "outputs": [
          {
              "@odata.type": "#Microsoft.Media.JobOutputAsset",
              "assetName": "testAsset1"
          }
          ]
      }
      }
      

The job takes some time to complete and when it does you want to be notified. To see the progress of the job, we recommend using Event Grid. It is designed for high availability, consistent performance, and dynamic scale. With Event Grid, your apps can listen for and react to events from virtually all Azure services, as well as custom sources. Simple, HTTP-based reactive event handling helps you build efficient solutions through intelligent filtering and routing of events. See Route events to a custom web endpoint.

The Job usually goes through the following states: Scheduled, Queued, Processing, Finished (the final state). If the job has encountered an error, you get the Error state. If the job is in the process of being canceled, you get Canceling and Canceled when it is done.

Job error codes

See Error codes.

Create a streaming locator

After the encoding job is complete, the next step is to make the video in the output Asset available to clients for playback. You can accomplish this in two steps: first, create a Streaming Locator, and second, build the streaming URLs that clients can use.

The process of creating a Streaming Locator is called publishing. By default, the Streaming Locator is valid immediately after you make the API calls, and lasts until it is deleted, unless you configure the optional start and end times.

When creating a Streaming Locator, you will need to specify the desired StreamingPolicyName. In this example, you will be streaming in-the-clear (or non-encrypted) content, so the predefined clear streaming policy (PredefinedStreamingPolicy.ClearStreamingOnly) is used.

Important

When using a custom StreamingPolicy, you should design a limited set of such policies for your Media Service account, and re-use them for your StreamingLocators whenever the same encryption options and protocols are needed.

Your Media Service account has a quota for the number of Streaming Policy entries. You should not be creating a new Streaming Policy for each Streaming Locator.

  1. In the left window of the Postman, select "Streaming Policies".

  2. Then, select "Create a Streaming Locator".

  3. Press Send.

    • The following PUT operation is sent.

      https://management.azure.com/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/streamingPolicies/:streamingPolicyName?api-version={{api-version}}
      
    • The operation has the following body:

      {
          "properties":{
          "assetName": "{{assetName}}",
          "streamingPolicyName": "{{streamingPolicyName}}"
          }
      }
      

List paths and build streaming URLs

List paths

Now that the Streaming Locator has been created, you can get the streaming URLs

  1. In the left window of the Postman, select "Streaming Policies".

  2. Then, select "List Paths".

  3. Press Send.

    • The following POST operation is sent.

      https://management.azure.com/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/streamingLocators/:streamingLocatorName/listPaths?api-version={{api-version}}
      
    • The operation has no body:

  4. Note one of the paths you want to use for streaming, you will use it in the next section. In this case, the following paths were returned:

    "streamingPaths": [
        {
            "streamingProtocol": "Hls",
            "encryptionScheme": "NoEncryption",
            "paths": [
                "/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest(format=m3u8-aapl)"
            ]
        },
        {
            "streamingProtocol": "Dash",
            "encryptionScheme": "NoEncryption",
            "paths": [
                "/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest(format=mpd-time-csf)"
            ]
        },
        {
            "streamingProtocol": "SmoothStreaming",
            "encryptionScheme": "NoEncryption",
            "paths": [
                "/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest"
            ]
        }
    ]
    

Build the streaming URLs

In this section, let's build an HLS streaming URL. URLs consist of the following values:

  1. The protocol over which data is sent. In this case "https".

    Note

    If a player is hosted on an https site, make sure to update the URL to "https".

  2. StreamingEndpoint's hostname. In this case, the name is "amsaccount-usw22.streaming.media.azure.net".

    To get the hostname, you can use the following GET operation:

    https://management.azure.com/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/amsResourceGroup/providers/Microsoft.Media/mediaservices/amsaccount/streamingEndpoints/default?api-version={{api-version}}
    
  3. A path that you got in the previous (List paths) section.

As a result, the following HLS URL was built

https://amsaccount-usw22.streaming.media.azure.net/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest(format=m3u8-aapl)

Test the streaming URL

Note

Make sure the Streaming Endpoint from which you want to stream is running.

To test the stream, this article uses Azure Media Player.

  1. Open a web browser and navigate to https://aka.ms/azuremediaplayer/.
  2. In the URL: box, paste the URL you built.
  3. Press Update Player.

Azure Media Player can be used for testing but should not be used in a production environment.

Clean up resources in your Media Services account

Generally, you should clean up everything except objects that you are planning to reuse (typically, you will reuse Transforms, and you will persist Streaming Locators, etc.). If you want for your account to be clean after experimenting, you should delete the resources that you do not plan to reuse.

To delete a resource, select "Delete ..." operation under whichever resource you want to delete.

Clean up resources

If you no longer need any of the resources in your resource group, including the Media Services and storage accounts you created for this tutorial, delete the resource group you created earlier.

Execute the following CLI command:

az group delete --name amsResourceGroup

Ask questions, give feedback, get updates

Check out the Azure Media Services community article to see different ways you can ask questions, give feedback, and get updates about Media Services.

Next steps

Now that you know how to upload, encode, and stream your video, see the following article: