Export (0) Print
Expand All
5 out of 8 rated this helpful - Rate this topic

Delivering Assets with the Media Services SDK for .NET

Updated: February 19, 2013

This topic shows options for delivering media assets that you have previously added to Media Services

Note that locators are not designed for managing per-user access control. To give different access rights to individual users, use Digital Rights Management (DRM) solutions.

This topic shows how to accomplish the following tasks for delivering Media Services content:

noteNote
Media Services uses the value of the IAssetFile.Name property when building URLs for the streaming content (for example, http://{WAMSAccount}.origin.mediaservices.windows.net/{GUID}/{IAssetFile.Name}/streamingParameters.) For this reason, percent-encoding is not allowed. The value of the Name property cannot have any of the following percent-encoding-reserved characters: !*'();:@&=+$,/?%#[]". Also, there can only be one ‘.’ for the file name extension.

noteNote
To process any media asset, first you must have a reference to the Media Services server context as described in the topic Connecting to Media Services with the Media Services SDK. The context object is represented by the variable named _context in the following code examples.

Download Media Assets

The code example in this section shows how to download media assets from Media Services. You can download any stored asset that is available in the Assets collection. Another typical download scenario is to download assets from the OutputMediaAssets collection, which is the set of one or more media assets that results from running a job. This code example shows how to download output media assets from a job, but you can apply the same approach to download other assets. A download that has not completed within 12 hours will fail.

The following code example shows how to download an output asset that results from a job. The code downloads only the first asset from the OutputMediaAssets collection. However, you could iterate through this collection to download multiple assets if they exist. For each asset, the code loops through its AssetFiles collection and downloads each individual file.

noteNote
This example also calls the GetJob method for getting a job reference as shown in the topic Managing Assets with the Media Services SDK for .NET.

static IAsset DownloadAssetToLocal(string jobId, string outputFolder)
{
    // This method illustrates how to download a single asset. 
    // However, you can iterate through the OutputAssets
    // collection, and download all assets if there are many. 

    // Get a reference to the job. 
    IJob job = GetJob(jobId);
    // Get a reference to the first output asset. If there were multiple 
    // output media assets you could iterate and handle each one.
    IAsset outputAsset = job.OutputMediaAssets[0];

    IAccessPolicy accessPolicy = _context.AccessPolicies.Create("File Download Policy", TimeSpan.FromDays(30), AccessPermissions.Read);
    ILocator locator = _context.Locators.CreateLocator(LocatorType.Sas, outputAsset, accessPolicy);

    BlobTransferClient blobTransfer = new BlobTransferClient
    {
        NumberOfConcurrentTransfers = 10,
        ParallelTransferThreadCount = 10
    };

    var downloadTasks = new List<Task>();
    foreach (IAssetFile outputFile in outputAsset.AssetFiles)
    {
        // Use the following event handler to check download progress.
        outputFile.DownloadProgressChanged += DownloadProgress;
        string localDownloadPath = Path.Combine(outputFolder, outputFile.Name);
        Console.WriteLine("File download path:  " + localDownloadPath);
        downloadTasks.Add(outputFile.DownloadAsync(Path.GetFullPath(localDownloadPath), blobTransfer, locator, CancellationToken.None));
    }

    Task.WaitAll(downloadTasks.ToArray());

    return outputAsset;
}

static void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine(string.Format("Asset File:{0}  {1}% download progress. ", ((IAssetFile)sender).Name, e.Progress));
} 

Create an Origin Locator to On Demand Content

Another way to access assets on demand in Media Services is to create a URL that links to an asset on the server. The URL is called a locator. The locators in Media Services are also associated with time-based permissions to access the assets (such as read, write, and list permissions). The type of locator that you can create to directly access on demand media assets is called a Shared Access Signature (SAS) locator. Every asset can have a collection of ILocator objects, which you can access by using the Locators property.

noteNote
When you create a locator for media content using the methods described in this topic, there may be a 30-second delay due to required storage and propagation processes in Azure Storage.

The following code example shows the necessary steps to create a SAS locator for an output asset produced by a job. The sample assumes that you have run a job and accessed its OutputMediaAssets collection, to obtain a reference to the outputAsset variable that is referenced in the code example. After you have run this code to generate SAS locators on an output asset, you can use the resulting URLs to directly access the files in Media Services. For a full runnable code example that incorporates this code into a job, see the Visual Studio code examples project referenced at the beginning of this topic.

The code example performs several key steps to perform when you create a SAS locator:

  • Define an access policy. This is how you determine the type of permissions and the duration for accessing an asset.

  • Create the SAS locator by calling the CreateLocator method (var locator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, accessPolicy);). Pass to the method an existing asset (such as an output asset from a job), an access policy, and a start time.

    noteNote
    The URL returned by the CreateLocator method is not the full URL to files in the asset. It is only the base path to the asset. To construct full URLs to specific files in the asset, you must complete the following step.

  • Build URLs to specific files in the asset. To do this, add the specific file name of a file from the asset to the locator Path property.

static void CreateOnDemandOriginLocator(IAsset outputAsset)
{
    // Declare an access policy for permissions on the asset. 
    // You can call an async or sync create method. 
    IAccessPolicy policy =
        _context.AccessPolicies.Create("My 30 day readonly policy",
            TimeSpan.FromDays(30),
            AccessPermissions.Read);

    // Create a SAS locator to enable direct access to the asset 
    // in blob storage. You can call a sync or async create method.  
    // You can set the optional startTime param as 5 minutes 
    // earlier than Now to compensate for differences in time  
    // between the client and server clocks. 
    ILocator locator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, outputAsset,
        policy,
        DateTime.UtcNow.AddMinutes(-5));
   Console.WriteLine(“Origin Locator base URI: “ + locator.Path);
    }
}

static string BuildFileSasUrl(IAssetFile file, ILocator locator)
{
    // Take the locator path, add the file name, and build 
    // a full SAS URL to access this file. This is the only 
    // code required to build the full URL.
    var uriBuilder = new UriBuilder(locator.Path);
    uriBuilder.Path = uriBuilder.Path + "/" + file.Name;
            
    // Optional:  print the locator.Path to the asset, and 
    // the full SAS URL to the file
    Console.WriteLine("Locator path: ");
    Console.WriteLine(locator.Path);
    Console.WriteLine();
    Console.WriteLine("Full URL to file: ");
    Console.WriteLine(uriBuilder.Uri.AbsoluteUri);
    Console.WriteLine();


    //Return the SAS URL.
    return uriBuilder.Uri.AbsoluteUri;
}

static void WriteToFile(string outFilePath, string fileContent)
{
    StreamWriter sr = File.CreateText(outFilePath);
    sr.WriteLine(fileContent);
    sr.Close();
}

Create an Origin Locator to Smooth Streaming or HLS Content

In Media Services there is also a way to directly access streaming media content. To do this, you can create an origin locator, which lets you directly access Smooth Streaming or Apple HTTP Live Streaming (HLS) content on an origin server. Similar to the SAS locator example, you can create a locator, then build a full URL to a specific file, and then access the content. With origin locators, you build the full URL to a streaming manifest file (the manifest file has an .ism file extension) in an asset. You can then provide the URL to a client application that can play streaming content, such as Microsoft Silverlight.

noteNote
When you create a locator for media content using the methods described in this topic, there may be a 30-second delay due to required storage and propagation processes in Azure Storage.

The following code example shows the necessary steps to create an origin locator for an output asset produced by a job. The example assumes that you have already obtained a reference to an asset that contains smooth streaming files, and the variable named assetToStream is referenced in the code. After you have run this code to generate an origin locator on the asset, you should be able to use the resulting URL to directly play back the streaming content in a streaming client player such as Silverlight.

The code example performs several key steps to perform when you create an origin locator:

  • Get a reference to the streaming manifest file in the asset. This is the file with the .ism extension.

  • Define an access policy. This is how you determine the type of permissions and the duration for accessing an asset.

  • Create the origin locator by calling the CreateLocator method (var originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, assetToStream, policy, DateTime.UtcNow.AddMinutes(-5))). Pass to the method an existing asset with streaming media files, an access policy, and a start time.

    noteNote
    The URL returned by the CreateLocator method is only the base path to the asset. To construct a full URL to the streaming manifest file, you must complete the following step.

  • Build a URL to the manifest file. To do this concatenate the locator Path value and the manifest file name. Then, append an appropriate format to the origin locator path. In case of a client that requires Smooth Streaming format, append the file.ism/Manifest string to the locator path. In case of a client that requires HLS, append the file.ism/Manifest(format=m3u8-aapl) string.

noteNote
To test the origin locator URL that points to the Smooth Streaming content, copy the URL of the manifest file that the code example creates. Create a simple Silverlight playback client as directed in the topic Getting Started with IIS Smooth Streaming, in the subsection titled Installing the Sample Client. To play back streaming media content from an origin locator URL, you do not need to set up IIS Media Services as described in the rest of the topic. Follow the directions to download the sample client and create a simple HTML page that hosts Silverlight to play streaming content. Paste the origin locator URL created by the sample into the HTML pages MediaUrl attribute as directed, and load the page in a browser to play the streaming content.

noteNote
To test the origin locator URL that points to the HLS content, copy the URL of the manifest file that the code example creates. If you do not have an iOS device to add the URL to, you can create a simple HTML page that can play back streaming content in a Safari browser. To do this, see the subsection titled "Creating an HTML 5 page for use in Safari" in the topic Apple HTTP Live Streaming with IIS Media Services.

public enum MediaContentType
{
    SmoothStreaming,
    HLS
}
public static ILocator GetStreamingOriginLocator(string targetAssetID, MediaContentType contentType)
{
    // Get a reference to the asset you want to stream.
    IAsset assetToStream = GetAsset(targetAssetID);

    // Get a reference to the streaming manifest file from the  
    // collection of files in the asset. 
    var theManifest =
                        from f in assetToStream.AssetFiles
                        where f.Name.EndsWith(".ism")
                        select f;

    // Cast the reference to a true IAssetFile type. 
    IAssetFile manifestFile = theManifest.First();
            
    // Create a 30-day readonly access policy. 
    IAccessPolicy policy = _context.AccessPolicies.Create("Streaming policy",
        TimeSpan.FromDays(30),
        AccessPermissions.Read);

    // Create a locator to the streaming content on an origin. 
    ILocator originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, assetToStream,
        policy,
        DateTime.UtcNow.AddMinutes(-5));
            
    // Display some useful values based on the locator.
    // Display the base path to the streaming asset on the origin server.
    Console.WriteLine("Streaming asset base path on origin: ");
    Console.WriteLine(originLocator.Path);
    Console.WriteLine();

    // Create a full URL to the manifest file. Use this for playback
    // in smooth streaming and HLS media clients. 
    string urlForClientStreaming = originLocator.Path + manifestFile.Name + "/manifest";
    if (contentType == MediaContentType.HLS)
        urlForClientStreaming = String.Format("{0}{1}", urlForClientStreaming, "(format=m3u8-aapl)"); 

    Console.WriteLine("URL to manifest for client streaming: ");
    Console.WriteLine(urlForClientStreaming);
    Console.WriteLine();

    // Display the ID of the origin locator, the access policy, and the asset.
    Console.WriteLine("Origin locator Id: " + originLocator.Id);
    Console.WriteLine("Access policy Id: " + policy.Id);
    Console.WriteLine("Streaming asset Id: " + assetToStream.Id);

    // For convenience, write the URL to a local file. Use the saved 
    // streaming URL to browse directly to the asset in a smooth streaming client.  
    string outFilePath = Path.GetFullPath(_outputFilesFolder + @"\" + "StreamingUrl.txt");
    WriteToFile(outFilePath, urlForClientStreaming);


    // Return the locator. 
    return originLocator;
}
 

See Also


Build Date:

2014-04-03
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.