1 out of 3 rated this helpful - Rate this topic

Process Assets with the Media Services SDK for .NET

This topic is part of the Windows Azure Media Services series titled Building Applications with the Media Services SDK for .NET, and it shows how to process assets that you have previously ingested into Media Services. In a Media Services application, you can process content by encoding in various media formats. Or you can convert the container file or stream that contains a set of media files to a different container file or stream (also called transmuxing). You can also create processing jobs (represented by the Jobs collection), which enable you to schedule and automate the processing of assets. In the Media Services architecture, an IJob object represents a collection of one or more ITask objects. Each task is an individual item of work that involves processing content for example, encoding, encrypting, and transforming. This section shows how to perform several typical Media Services processing tasks.

ImportantImportant
A Visual Studio project with source code accompanies and is required for this series. If you have not yet downloaded and set up this project, see the directions in the introductory topic titled Building Applications with the Media Services SDK for .NET. Each code example in this topic is illustrated with one or more methods in the downloaded project (the solution file for the project is MediaServicesSDKSamples.sln). To find the code for a specific example, search for the example method name in the downloaded project. To run a specific code example, call the associated method with the required parameters.

This topic shows how to accomplish the following processing tasks:

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

Accessing a Media Processor

A common task that is required for most processing jobs is to call a specific media processor to handle the job. In Media Services, a media processor is a component that handles a specific processing task, such as encoding, format conversion, encrypting, or decrypting media content.

In the current release, you can use any of the following media processors. To use a specific media processor, pass the string name for the processor into a call such as the GetLatestMediaProcessorByName method in this section. The other processing code examples in this topic show you how to use the various media processors.

 

Media Processor Name Processor Id Description

Windows Azure Media Encoder

nb:mpid:UUID:70bdc2c3-ebf4-42a9-8542-5afc1e55d217

Lets you run encoding tasks using the Media Encoder.

Windows Azure Media Packager

nb:mpid:UUID:A2F9AFE9-7146-4882-A5F7-DA4A85E06A93

Lets you convert media assets from .mp4 to smooth streaming format. Also, lets you convert media assets from smooth streaming to the Apple HTTP Live Streaming (HLS) format.

Windows Azure Media Encryptor

nb:mpid:UUID:38A620D8-B8DC-4E39-BB2E-7D589587232B

Lets you encrypt media assets using PlayReady Protection.

Storage Decryption

nb:mpid:UUID:aec03716-7c5e-4f68-b592-f4850eba9f10

Lets you decrypt media assets that were encrypted using storage encryption.

The following code shows how to create a media processor. You can call the GetLatestMediaProcessorByName method and pass in one of the preceding media processor strings that specify which processor to use. The method returns a valid media processor instance.

private static IMediaProcessor GetLatestMediaProcessorByName(string mediaProcessorName)
{
    // The possible strings that can be passed into the 
    // method for the mediaProcessor parameter:
    //   Windows Azure Media Encoder
    //   Windows Azure Media Packager
    //   Windows Azure Media Encryptor
    //   Storage Decryption

    var processor = _context.MediaProcessors.Where(p => p.Name == mediaProcessorName).
        ToList().OrderBy(p => new Version(p.Version)).LastOrDefault();

    if (processor == null)
        throw new ArgumentException(string.Format("Unknown media processor", mediaProcessorName));

    return processor;
}

The following example calls the GetLatestMediaProcessorByName method and passes "Windows Azure Media Encoder" as the name.

IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Encoder");

Encode a Video

Encoding jobs are one of the most common processing operations in Media Services. You create encoding jobs to convert media files from one encoding to another. When you encode, you can use the Media Services built-in Media Encoder. You can also use an encoder provided by a Media Services partner; third party encoders are available through the Windows Azure Marketplace. You can specify the details of encoding tasks by using preset strings defined for your encoder, or by using preset configuration files. To see the types of presets that are available, see Task Presets for Windows Azure Media Services.

The following example shows how to create an encoding job based on a preset string. You can find a list of preset strings in the topic Task Preset Strings for Windows Azure Media Encoder. If you call this method passing in a media file (for example, a .wmv file), it is encoded with settings associated with the specified preset string, and the resulting encoded file is available in .mp4 format. For information on how to retrieve the encoded file or other job outputs, see Deliver Assets with the Media Services SDK for .NET.

The code example completes the following items to create the encoding job:

  • Create or pass an asset to the job. In this example, create a storage-encrypted asset to protect the contents.

  • Declare a new job, using the Create method.

  • Get a media processor to process the job. To do this, call the GetLatestMediaProcessorByName method shown in the Get a Media Processor section. In this example, the code uses the Windows Azure Media Encoder to encode the media file.

  • Declare a task. To declare a task, you must give the task a friendly name, and then pass to it a media processor instance, a configuration string for handling the processing job, and a TaskCreationOptions setting (which specifies whether to encrypt the configuration data).

  • Specify an input asset for the task. In this example, the input asset is created in the first step.

  • Specify an output asset for the task. By default, all assets are created as storage encrypted. To output a clear, unencrypted asset for playback, the code specifies None. If you are creating a PlayReady Protection Job, the task will always set the AssetCreationOptions of the output asset to CommonEncryptionProtected.

  • Submit the job. To learn more about getting output from a job, see Deliver Assets with the Media Services SDK for .NET.

public static IJob CreateEncodingJob( string inputMediaFilePath, string outputFolder)
{
    //Create an encrypted asset and upload to storage. 
    IAsset asset = CreateAssetAndUploadSingleFile(AssetCreationOptions.StorageEncrypted, inputMediaFilePath);

    // Declare a new job.
    IJob job = _context.Jobs.Create("My encoding job");
    // Get a media processor reference, and pass to it the name of the 
    // processor to use for the specific task.
    IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Encoder");

    // Create a task with the encoding details, using a string preset.
    ITask task = job.Tasks.AddNew("My encoding task",
        processor,
        "H264 Broadband 720p",
        _protectedConfig);

    // Specify the input asset to be encoded.
    task.InputAssets.Add(asset);
    // Add an output asset to contain the results of the job. 
    // This output is specified as AssetCreationOptions.None, which 
    // means the output asset is in the clear (unencrypted). 
    task.OutputAssets.AddNew("Output asset",
        AssetCreationOptions.None);

    // Use the following event handler to check job progress.  
    job.StateChanged += new
            EventHandler<JobStateChangedEventArgs>(StateChanged);

    // Launch the job.
    job.Submit();

    // Optionally log job details. This displays basic job details
    // to the console and saves them to a JobDetails-{JobId}.txt file 
    // in your output folder.
    LogJobDetails(job.Id);

    // Check job execution and wait for job to finish. 
    Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
    progressJobTask.Wait();

     // Get an updated job reference after waiting for a job on 
     // a thread.
     job = GetJob(job.Id);

    return job;
}

private static void LogJobDetails(string jobId)
{
   StringBuilder builder = new StringBuilder();
   IJob job = GetJob(jobId);

   builder.AppendLine("\nJob ID: " + job.Id);
   builder.AppendLine("Job Name: " + job.Name);
   builder.AppendLine("Job submitted (client UTC time): " + DateTime.UtcNow.ToString());
   builder.AppendLine("Media Services account name: " + _accountName);

   // Write the output to a local file and to the console. The template 
   // for an error output file is:  JobDetails-{JobId}.txt
   string outputFile = Path.Combine(_outputFilesFolder, @"JobDetails-" + JobIdAsFileName(job.Id) + ".txt");
   WriteToFile(outputFile, builder.ToString());
   Console.Write(builder.ToString());
}

Create a Job with Chained Tasks

In many application scenarios, developers want to create a series of processing tasks. In Media Services, you can create a series of chained tasks. Each task performs different processing steps and can use different media processors. The chained tasks can hand off an asset from one task to another, performing a linear sequence of tasks on the asset. However, the tasks performed in a job are not required to be in a sequence. When you create a chained task, the chained ITask objects are created in a single IJob object.

The following code example shows how to create an encoding job that contains two chained tasks. The first task encodes and storage-encrypts a media asset. This is essentially the same task shown in the Create an Encoding Job section. The second task decrypts the asset that the first task created. See the following details in the code:

  • The first task adds an output media asset (using the StorageEncrypted setting). This means that the encoded asset that is output from the first task has its contents protected, but it also means that it must be decrypted before play back. The second task provides the decryption step.

  • The second task declares a different media processor. This method also calls the GetLatestMediaProcessorByName method shown in the Get a Media Processor section. Because the second task is decrypting a storage encrypted asset, it creates an instance of the Storage Decryption media processor.

  • The second task uses the output media asset from the first task as its input media asset. In the code, when the second task adds its input media asset, it passes the output asset from the first task to the method (task.OutputMediaAssets[0]). This is an example of how to chain tasks: one task takes the output of a previous task as input.

  • The second task specifies that the output asset is created unencrypted (by using the None setting). The second task takes the storage encrypted, encoded asset from the first task as input, and then outputs a decrypted version of the asset. For information on how to download the decrypted asset or access it on the server, see Deliver Assets with the Media Services SDK for .NET.

public static IJob CreateChainedTaskEncodingJob( string inputMediaFilePath, string outputFolder)
{
    //Create an encrypted asset and upload to storage. 
    IAsset asset = CreateAssetAndUploadSingleFile(AssetCreationOptions.StorageEncrypted, inputMediaFilePath);

    // Declare a new job.
    IJob job = _context.Jobs.Create("My task-chained encoding job");

    // Set up the first task to encode the input file.

    // Get a media processor reference


    IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Encoder");

    // Create a task with the encoding details, using a string preset.
    ITask task = job.Tasks.AddNew("My encoding task",
        processor,
        "H264 Broadband 720p",
        _protectedConfig);

    // Specify the input asset to be encoded.
    task.InputAssets.Add(asset);

    // Specify the storage-encrypted output asset.
    task.OutputAssets.AddNew("My storage-encrypted output asset",
        AssetCreationOptions.StorageEncrypted);

    // Set up the second task to decrypt the encoded output file from 
    // the first task.

    // Get another media processor instance
    IMediaProcessor decryptProcessor = GetLatestMediaProcessorByName("Storage Decryption");

    // Declare the decryption task. 
    ITask decryptTask = job.Tasks.AddNew("My decryption task",
        decryptProcessor,
        string.Empty,
        _clearConfig);

    // Specify the input asset to be decrypted. This is the output 
    // asset from the first task. 
    decryptTask.InputAssets.Add(task.OutputAssets[0]);

    // Specify an output asset to contain the results of the job. 
    // This should have AssetCreationOptions.None. 
    decryptTask.OutputAssets.AddNew("My decrypted output asset",
 AssetCreationOptions.None);

    // Use the following event handler to check job progress. 
    job.StateChanged += new
 EventHandler<JobStateChangedEventArgs>(StateChanged);

    // Launch the job.
    job.Submit();

    // Optionally log job details. 



    LogJobDetails(job.Id);

    // Check job execution and wait for job to finish. 
    Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
    progressJobTask.Wait();

     // Get an updated job reference after waiting for a job on 
     // a thread.
     job = GetJob(job.Id);

     return job;
}

Working with Smooth Streaming

In order to stream content you need to convert it into a streaming format. You can encode directly into a Smooth Streaming format using one of the Windows Media Encoder H.264 Smooth Streaming task presets or you can convert content that has already been encoded into H.264 into a Smooth Streaming format. This operation is performed by the Windows Azure Media Packager. The packager changes the container that holds the video, but does not modify the video encoding. The Windows Media Packager does not accept string presets, so you must supply configuration in XML. You can find the XML configuration for most packaging tasks in the Task Preset for Windows Azure Media Packager topic. Windows Azure Media Services supports the Smooth Streaming and Apple HTTP Live Streaming (HLS) formats. This section will show you how to ingest an MP4 file and create a job to convert it to Smooth Streaming.

Note, if you want to convert WMV files to Smooth Streaming, you must first encode your files from WMV to H.264. WMV is a video codec that typically has an ASF container format. H.264 is a video codec that can be used with the MP4 container format. Smooth Streaming uses a variant of MP4 called fragmented MP4 or f-mp4. Smooth streaming is an adaptive streaming format that requires a set of files of different bitrates and all encoded with fragments that are aligned across the bitrates. A set of MP4 files that are encoded with aligned fragments can be converted to f-mp4 without requiring a re-encode. This is not the case with WMV files. For more information, see Smooth Streaming Technical Overview.  

You can create a Smooth Streaming stream in a number of ways:

  • Encode your video (a single video file) using one of the H.264 Smooth Streaming task presets to encode directly into Smooth Streaming, For more information, see Task Preset Strings for Windows Azure Media Encoder

  • Encode your video (a single video file) using one of the H.264 Adaptive bitrate task presets using the Windows Media Encoder and then use the Windows Media Packager to convert the adaptive bitrate MP4 files to Smooth Streaming

  • Encode your video locally to a number of different bit rates, create a .ism file describing the video files, upload them into the Windows Azure Storage account associated with you Windows Azure Media account, and then use the Windows Azure Media Packager to convert the MP4 files into Smooth Streaming files.

Encode to Smooth Streaming

Encoding to a Smooth Streaming format is done using the following steps:

  1. Create and upload an asset for the job.

  2. Create a new job.

  3. Get a media processor to process the job. In this example, the code uses the Windows Azure Media Encoder to encode the media file.

  4. Create a new task, specifying a task name. the media processor to use, a task preset (or configuration XML), and task option that controls encryption of the output asset.

  5. Specify an input asset for the task. In this case the MP4 asset we created and uploaded.

  6. Specify an output asset for the task. An asset that points to the generated output.

  7. Submit the job. To learn more about getting output from a job, see Deliver Assets with the Media Services SDK for .NET.

private static IJob EncodeToSmoothStreaming(string inputMediaFilePath)
{
   //Create an encrypted asset and upload the mp4. 
   IAsset asset = CreateAssetAndUploadSingleFile(AssetCreationOptions.StorageEncrypted, inputMediaFilePath);

   // Declare a new job.
   IJob job = _context.Jobs.Create("My MP4 to Smooth Streaming encoding job");

   // Get a media processor reference, and pass to it the name of the 
   // processor to use for the specific task.
  IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Encoder");

   // Create a task to encode to Smooth Streaming. Configuration is specified with a Task preset string 
   ITask task = job.Tasks.AddNew("My Mp4 to Smooth Task",
      processor,
      "H264 Smooth Streaming 720p",
      _clearConfig);

   // Specify the input asset to be encoded.
   task.InputAssets.Add(asset);

   // Add an output asset to contain the results of the job. We do not need 
   // to persist the output asset to storage, so set the shouldPersistOutputOnCompletion
   // param to false. 
   task.OutputAssets.AddNew("Output asset", AssetCreationOptions.None);

   // Use the following event handler to check job progress. 
   job.StateChanged += new EventHandler<JobStateChangedEventArgs>(StateChanged);

   // Launch the async job.
   job.Submit();

   // Optionally log job details. 
   LogJobDetails(job.Id);

   // Check job execution and wait for job to finish. 
   Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
   progressJobTask.Wait();

   // Get a refreshed job reference after waiting on a thread.
   job = GetJob(job.Id);

   // Check for error
   if (job.State == JobState.Error)
   {
      Console.WriteLine("\nExiting method due to job error.");
   }
   return job;
}

Encode to Adaptive Bitrate MP4 and Convert to Smooth Streaming

This example shows how to encode a video to Adaptive Bitrate MP4 and convert to smooth streaming. It uses a set of two chained tasks. The first task encodes to adaptive bitrate MP4 files and the second task converts the MP4 files to Smooth Streaming. The following steps are performed:

  1. Create an Asset and upload a single file

  2. Get an instance of the Windows Media Encoder

  3. Create a new Job

  4. Create a Task to encode to an adaptive bitrate set

  5. Create a Task to convert the adaptive bitrate set to Smooth Streaming

  6. Submit the Job

private static IJob EncodeToAdaptiveBitrateAndConvertToSmooth(string inputMediaFilePath)
{
   // Create asset and upload file
   IAsset asset = CreateAssetAndUploadSingleFile(AssetCreationOptions.None, inputMediaFilePath);

   // Get instance of Windows Media Encoder
   IMediaProcessor encoder = GetLatestMediaProcessorByName("Windows Azure Media Encoder");

   // Create a new Job
   IJob job = _context.Jobs.Create("Encode to multi-bitrate and convert to smooth job");

   // Create a new task to encode to adaptive bitrate
   ITask adpativeBitrateTask = job.Tasks.AddNew("MP4 to Adaptive Bitrate Task", encoder, "H264 Adaptive Bitrate MP4 Set 720p", TaskOptions.None);
   adpativeBitrateTask.InputAssets.Add(asset);
   IAsset abrAsset = adpativeBitrateTask.OutputAssets.AddNew("Adaptive Bitrate Asset", AssetCreationOptions.None);

   // Get instance of Windows Media Packager
   IMediaProcessor packager = GetLatestMediaProcessorByName("Windows Azure Media Packager");

   // Windows Media Packager does not accept string presets, so load xml configuration
   string smoothConfig = File.ReadAllText(Path.Combine(_configFilePath, "MediaPackager_MP4toSmooth.xml"));

   // Create a new Task to convert adaptive bitrate to Smooth Streaming
   ITask smoothStreamingTask = job.Tasks.AddNew("Adaptive Bitrate to Smooth Task", packager, smoothConfig, TaskOptions.None);
   smoothStreamingTask.InputAssets.Add(abrAsset);
   smoothStreamingTask.OutputAssets.AddNew("Smooth Asset", AssetCreationOptions.None);
            
   // Use the following event handler to check job progress.  
   job.StateChanged += new EventHandler<JobStateChangedEventArgs>(StateChanged);

   // Launch the job.
   job.Submit();

   // Optionally log job details. 
   LogJobDetails(job.Id);

   // Check job execution and wait for job to finish. 
   Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
   progressJobTask.Wait();


   // Get a refreshed job reference after waiting on a thread.
   job = GetJob(job.Id);

   // Check for error
   if (job.State == JobState.Error)
   {
      Console.WriteLine("\nExiting method due to job error.");
   }

   return job;
}

Convert Multiple Bitrate MP4 files to Smooth Streaming

When converting multiple bitrate MP4 files to Smooth Streaming you must create an .ism file that lists the MP4 files (audio and video) to be used. The following is an example .ism file:

<?xml version="1.0" encoding="utf-8"?>
<smil xmlns="http://www.w3.org/2001/SMIL20/Language">
  <body>
    <switch>
      <video src="interview1_384p_H264_184Kbps_AAC.mp4" />
      <video src="interview1_384p_H264_205Kbps_AAC.mp4" />
      <video src="interview1_384p_H264_228Kbps_AAC.mp4" />
      <video src="interview1_384p_H264_254Kbps_AAC.mp4" />
      <video src="interview1_384p_H264_283Kbps_AAC.mp4" />
      <video src="interview1_384p_H264_315Kbps_AAC.mp4" />
      <video src="interview1_384p_H264_350Kbps_AAC.mp4" />
      <audio src="interview1_384p_H264_184Kbps_AAC.mp4" /> <!-- Because we do not have a separate audio file, we point to the first .MP4 file for audio -->
    </switch>
  </body>
</smil>
WarningWarning
Make sure the .ism file is UTF-8 encoded

After creating the .ism file perform the following steps to convert your multiple bitrate MP4 files to Smooth Streaming

  1. Create an asset and upload your MP4 and .ism files

  2. Find the .ism file in storage and mark it as the primary file in the asset

  3. Get an instance of the Windows Azure Media Packager

  4. Create a new Job

  5. Read in the Media Packager configuration file

  6. Create a new Task to do the conversion, passing in a Task name, the packager, the XML configuration, and any encryption options

  7. Submit the Job

  8. Check for errors.

static IJob ConvertMultipleBitrateToSmoothStreaming(string configFilePath,
string inputFolder, string outputFolder)
{
   // Create the asset that contains MP4 multi-bitrate and .ism files 
   IAsset mbrAsset = CreateAssetAndUploadMultipleFiles(AssetCreationOptions.None, inputFolder);

   // Check for the .ism file and set it as the primary file
   var mbrAssetFiles = mbrAsset.AssetFiles.ToList().
      Where(f => f.Name.EndsWith(".ism", StringComparison.OrdinalIgnoreCase)).ToArray();

   if (mbrAssetFiles.Count() != 1)
      throw new ArgumentException("The asset should have only one, .ism file");

   mbrAssetFiles.First().IsPrimary = true;
   mbrAssetFiles.First().Update();

   // Get an instance of the Windows Azure media packager
   IMediaProcessor packager = GetLatestMediaProcessorByName("Windows Azure Media Packager");

   // Create a new Job
   IJob job = _context.Jobs.Create("Multi Bitrate To Smooth Job");

   // Read in config file
   string smoothConfig = File.ReadAllText(Path.Combine(_configFilePath, "MediaPackager_MP4ToSmooth.xml"));

   // Create a new Task to do the conversion
   ITask mbrToSmoothTask = job.Tasks.AddNew("MBR to Smooth Task", packager, smoothConfig, TaskOptions.None);
   mbrToSmoothTask.InputAssets.Add(mbrAsset);
   mbrToSmoothTask.OutputAssets.AddNew("Smooth Asset", AssetCreationOptions.None);

   // Use the following event handler to check job progress.  
   job.StateChanged += new EventHandler<JobStateChangedEventArgs>(StateChanged);

   // Launch the job.
   job.Submit();

   // Optionally log job details
   LogJobDetails(job.Id);

   // Check job execution and wait for job to finish. 
   Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
   progressJobTask.Wait();

   // Get a refreshed job reference after waiting on a thread.
   job = GetJob(job.Id);

   // Check for error 
   if (job.State == JobState.Error)
   {
      Console.WriteLine("\nExiting method due to job error.");
   }

   return job;
}

Convert Smooth Streaming Files to Apple HLS Format

TipTip
If you have a set of multi-bitrate MP4 (ISO Base Media 14496-12) files or Smooth Streaming files that you want to serve to clients that understand HLS or Smooth Streaming, you should take advantage of Media Services dynamic packaging. For more information, see Walkthrough: Dynamically Packaging Assets.

This section shows how to convert smooth streaming files to the Apple HTTP Live Streaming (HLS) format. This lets you serve streaming content on demand to Apple iOS devices. You can obtain the preset configuration file for the conversion from the topic Task Preset for Windows Azure Media Packager. Save the preset file locally and then load it into configuration data when you create a task.

noteNote
To convert Smooth Streaming files to Apple HLS format, the Smooth Streaming asset must be encoded with the H.264 and AAC coding standard. You can use a preset such as “H264 Smooth Streaming 720p” to perform the encoding task. For information about available presets see, Task Preset Strings for Windows Azure Media Encoder.

The following code example shows how to convert a Smooth Streaming asset to Apple HLS format. It uses the EncodeToSmoothStreaming method discussed previously to focus on the conversion process. For information on how to retrieve or access the encoded files and job outputs, see Deliver Assets with the Media Services SDK for .NET.

This code performs the following steps:

  1. Calls EncodeToSmoothStreaming to encode an MP4 file to Smooth Streaming

  2. Retrieves the output Smooth Streaming Asset

  3. Finds the .ism file and sets it as the primary file

  4. Creates a new Job

  5. Gets an instance of the Windows Azure Media Packager

  6. Reads in the XML configuration for the packager

  7. Adds a new Task to perform the conversion passing in a Task name. the packager, the configuration, and encryption options

  8. Submits the Job

  9. Checks for errors

static IJob ConvertSmoothToHLS(string configFilePath, string inputMediaFilePath)
{
   // Call method to encode an MP4 file to Smooth Streaming
   IJob encodeJob = EncodeToSmoothStreaming(inputMediaFilePath);

   // Get the Smooth Streaming output asset
   IAsset smoothAsset = encodeJob.OutputMediaAssets[0];
            
   // Find the .ism file and set as the primary file
   var ismAssetFiles = smoothAsset.AssetFiles.ToList().
      Where(f => f.Name.EndsWith(".ism", StringComparison.OrdinalIgnoreCase)).ToArray();

   if (ismAssetFiles.Count() != 1)
      throw new ArgumentException("The asset should have only one, .ism file");

   ismAssetFiles.First().IsPrimary = true;
   ismAssetFiles.First().Update();

   // Create a new job.
      IJob job = _context.Jobs.Create("Convert Smooth Stream to Apple HLS");

   // Get an instance of the Windows Azure Media Packager
   IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Packager");

   // Read the configuration data into a string. 
   string configuration = File.ReadAllText(Path.GetFullPath(configFilePath
      + @"\MediaPackager_SmoothToHLS.xml"));

   // Create a task with the encoding details, using a configuration file.
   ITask task = job.Tasks.AddNew("My Smooth to HLS Task",
      processor,
      configuration,
      _protectedConfig);

   // Specify the input asset to be encoded.
   task.InputAssets.Add(smoothAsset);

   // Add an output asset to contain the results of the job.
   task.OutputAssets.AddNew("HLS asset", AssetCreationOptions.None);

   // Use the following event handler to check job progress.  
   job.StateChanged += new
      EventHandler<JobStateChangedEventArgs>(StateChanged);

   // Launch the job.
   job.Submit();

   // Optionally log job details.
   LogJobDetails(job.Id);

   // Check job execution and wait for job to finish. 
      Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
      progressJobTask.Wait();

   // Get a refreshed job reference after waiting on a thread.
   job = GetJob(job.Id);

   // Check for errors
   if (job.State == JobState.Error)
   {
      Console.WriteLine("\nExiting method due to job error.");
   }

   return job;
}

Protect a Video with Microsoft PlayReady

When you work with assets in Media Services, you can submit a job that integrates with Microsoft PlayReady Protection to encrypt a set of media files. The code in this section takes several streaming files from an input folder, creates a task and encrypts them with PlayReady Protection. This is done using two tasks. The first task takes the input media file and creates a smooth streaming version. The second task takes the smooth streaming asset and protects it with the Windows Azure Media Encryptor.

noteNote
Both tasks use a configuration file rather than a preset string to specify options to the media processor. Only the Windows Azure Encoder media processor can interpret string presets as shown in previous sections. All other media processors require that you use a configuration file to specify settings. For more information about creating such a configuration file, see Task Presets for Windows Azure Media Services.

For information on how to retrieve or access the generated files or other job outputs, see Deliver Assets with the Media Services SDK for .NET.

WarningWarning
If you are creating a PlayReady Protection Job, the task will always set the AssetCreationOptions of the output asset to CommonEncryptionProtected because this is the result of a PlayReady Protection Job.

private static IJob ProtectWithPlayReady ( string inputMediaFilePath, string configFilePath)
{
   // Create a storage-encrypted asset and upload the mp4. 
   IAsset asset = CreateAssetAndUploadSingleFile(AssetCreationOptions.StorageEncrypted, inputMediaFilePath);

   // Declare a new job to contain the tasks
   IJob job = _context.Jobs.Create("My PlayReady Protection job");

   // Set up the first task. 

   // Read the task configuration data into a string
   string configMp4ToSmooth = File.ReadAllText(Path.GetFullPath(configFilePath + @"\MediaPackager_MP4ToSmooth.xml"));

   // Get a media processor reference
   IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Packager");

   // Create a task with the conversion details, using the configuration data
   ITask task = job.Tasks.AddNew("My Mp4 to Smooth Task",
      processor,
      configMp4ToSmooth,
      _clearConfig);

   // Specify the input asset to be converted.
   task.InputAssets.Add(asset);

   // Add an output asset to contain the results of the job.
   task.OutputAssets.AddNew("Streaming output asset", AssetCreationOptions.None);

   IAsset smoothOutputAsset = task.OutputAssets[0];

   // Set up the second task. 

   // Read the configuration data into a string. 
   string configPlayReady = File.ReadAllText(Path.GetFullPath(configFilePath + @"\MediaEncryptor_PlayReadyProtection.xml"));

   // Get a media processor reference
   IMediaProcessor playreadyProcessor = GetLatestMediaProcessorByName("Windows Azure Media Encryptor");

   // Create a second task. 
   ITask playreadyTask = job.Tasks.AddNew("My PlayReady Task",
      playreadyProcessor,
      configPlayReady,
      _protectedConfig);

   // Add the input asset, which is the smooth streaming output asset from the first task. 
   playreadyTask.InputAssets.Add(smoothOutputAsset);

   // Add an output asset to contain the results of the job.
   playreadyTask.OutputAssets.AddNew("PlayReady protected output asset",
      AssetCreationOptions.None);

   // Use the following event handler to check job progress. 
   job.StateChanged += new EventHandler<JobStateChangedEventArgs>(StateChanged);

   // Launch the job.
   job.Submit();

   // Optionally log job details. 
   LogJobDetails(job.Id);

   // Check job execution and wait for job to finish. 
   Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
      progressJobTask.Wait();

   // Get a refreshed job reference after waiting on a thread.
   job = GetJob(job.Id);

   // Check for errors
   if (job.State == JobState.Error)
   {
      Console.WriteLine("\nExiting method due to job error.");
   }

   return job;
}

Create a Thumbnail for a Video

In Media Services, another common processing task is generating thumbnail image files from a video file.

The following example shows how to create thumbnail images from a video file. The example below uses the “Thumbnails” preset string which provides the default settings. To customize the settings of your thumbnail file, see the Task Preset for Thumbnail Generation topic.

For information on how to retrieve or access the generated files or other job outputs, see Deliver Assets with the Media Services SDK for .NET.

public static ITask CreateThumbnail ( string configFilePath, string inputFilePath, string outputFolder)
{
    IAsset asset = CreateAssetAndUploadSingleFile(AssetCreationOptions.StorageEncrypted, inputFilePath);

    // Declare a new job.
    IJob job = _context.Jobs.Create("My Thumbnail job");
    // Get a media processor reference, and pass to it the name of the 
    // processor to use for the specific task.
    IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Encoder");


    ITask task = job.Tasks.AddNew("My thumbnail task",
        processor,
        "Thumbnails",
        _protectedConfig);
    // Specify the input asset to be encoded.
    task.InputAssets.Add(asset);
    // Add an output asset to contain the results of the job.
    task.OutputAssets.AddNew("Output asset",
        AssetCreationOptions.None);

    // Use the following event handler to check job progress.  
    job.StateChanged += new
            EventHandler<JobStateChangedEventArgs>(StateChanged);

    // Launch the job.
    job.Submit();

    // Optionally log job details. This displays basic job details
    // to the console and saves them to a JobDetails-{JobId}.txt file 
    // in your output folder.
    LogJobDetails(job.Id);

    // Check job execution and wait for job to finish. 
    Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);
    progressJobTask.Wait();

     // Get an updated job reference after waiting for a job on 
     // a thread.
     job = GetJob(job.Id);

      // If job state is Error, the event handling 
      // method for job progress should log errors.  Here we check 
      // for error state and exit if needed.
      if (job.State == JobState.Error)
      {
         Console.WriteLine("\nExiting method due to job error.");
         return task;
      }
    return task;
}

See Also


Build Date:

2013-04-26
Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.
facebook page visit twitter rss feed newsletter