blog.atwork.at

news and know-how about microsoft, technology, cloud and more.

Using Windows Azure Media Services

Windows Azure offers an easy and modern way to work with media files. With Azure Media Services you can upload video files, encode them and offer them for streaming clients. A great way to use multimedia content in your webs and apps!

For example Azure Media Services have been used in the Olympic Games 2012 in London for delivering more than 2,300 hours of live and HD content to more than 20 countries for multiple Olympics broadcasters, see Windows Azure Media Services Case Study.

In this article I will show you how easy Azure media services can be used, not too much in detail but showing the process and how to use the streaming content in your web apps.

Create your media service

In Windows Azure portal create a new media service in Media Services/Create. In App Services choose a name, region and if your want to use a new or existing storage account for storing the BLOBs.

image_thumb19

Supported formats

A video file consits of a container (which wraps the audio and video codecs, but doesn't contain the raw data itself), a video codec and the audio codec . When using good codecs, you get smaller resulting video files without any quality loss.

Today mainly these formats are used in Internet, see MP4 Video Encoding:

Which format works where?

  • MP4 works on devices, on browsers in Flash and on half the browsers in HTML5.
  • WebM only works on half the browsers in HTML5.
  • FLV only works on browsers in Flash.

In many cases the HTML5 video is first choice, supported by most modern browsers, like Internet Explorer 9+, Firefox, Opera, Chrome, and Safari. This is the HTML5 code:

   1: <video width="600" height="420" controls>
   2:   <source src="mymovie.mp4" type="video/mp4">
   3:   <source src="mymovie.ogg" type="video/ogg">
   4:   Your browser does not support the video tag.
   5: </video>

Currently, there are 3 supported video formats for the <video> element: MP4, WebM, and Ogg.
IE supports MP4 only, Chrome and Firefox (up from v21) both support MP4, WebM and Ogg.
Safari supports MP4 only and Opera only WebM and Ogg, see HTML5 Video

In Azure find the Supported Codecs and File Types for Windows Azure Media Encoder. For exporting you can choose between wmv, wma, mp4 and the smooth streaming file formats ismv and isma.

Uploading

The upload of your video files can be done in the Azure portal. Go to "content", click "upload" and here we go!

image_thumb16

In Uploading Media you find an overview of relevant concepts and different ways to upload your content.

Tip: Uploading only works for small video files...

Uploading large video files

If you want to upload a video file larger than 200MB the Azure portal denies the upload process, see:

image_thumb2

The solution: you can only upload file size less than 200MB through Azure portal. If you want to upload a file bigger than 200 MB, you have to use the Media Services API, see here.

Well, my demo video file "Deep-Dive-WAAD.mp4" is 263MB...
I guess, Microsoft wants to avoid problems with timeouts in the portal website.

Use the API with an app

Ok, let´s create a small app for uploading my large video file. First I create a new WPF project in Visual Studio 2013. Now we need to install the Windows Azure Media Services .NET SDK, see  Windows Azure Media Services .NET SDK 3.0.0.
Run the following command in the Package Manager Console:

PM> Install-Package windowsazure.mediaservices

After we have all the necessary components in our project, we need some code from the Azure portal. We get the sample code directly from the start page of our media service.

image_thumb21

So simply copy and paste the generated code - including my media services key - to my project, f.e. in a button click event. So my slightly adapted code looks like this:

image_thumb22

When we run the application and start the upload the Azure portal already has the file in it´s content.

image_thumb7

The upload on my WiFi takes some time, something like 30 minutes.
Time to switch to cable...anyway, WiFi should be good enough, it´s sunday. Zwinkerndes Smiley

Improving the uploading app

The sample code of course doesn´t have any error handling built in - that would be on your side, at least a try-catch block and a retry-logic or similiar.

Also I would like to add a simple UI so that the desktop app can be used for any Media Service and any video. So let´s improve the app somehow. This shall be the frontend:

image_thumb[2]

The XAML now looks like this

   1: <Window x:Class="VideoUploader2.MainWindow"
   2:         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:         Title="Simple Windows Azure Media Services Video Uploader" Height="300" Width="558">
   5:     <Grid Margin="10,10,0,10" HorizontalAlignment="Left" Width="530">
   6:         <Grid.RowDefinitions>
   7:             <RowDefinition Height="30"/>
   8:             <RowDefinition Height="30"/>
   9:             <RowDefinition Height="30"/>
  10:             <RowDefinition Height="30"/>
  11:             <RowDefinition Height="30"/>
  12:             <RowDefinition Height="auto"/>
  13:         </Grid.RowDefinitions>
  14:         <Grid.ColumnDefinitions>
  15:             <ColumnDefinition Width="200"/>
  16:             <ColumnDefinition Width="*"/>
  17:             <ColumnDefinition Width="auto"/>
  18:         </Grid.ColumnDefinitions>
  19:         <Label Content="Put your Media Services data in .config and upload your video files to Azure storage." 
  20:                Name="welcome" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"/>
  21:         <Label Content="Media Service Name" Grid.Row="1" Grid.Column="0"/>
  22:         <TextBox Name="txtMediaServiceName" Text="" Margin="5" Grid.Row="1" Grid.Column="1"/>
  23:         <Label Content="Media Service Key" Grid.Row="2" Grid.Column="0"/>
  24:         <TextBox Name="txtMediaServiceKey" Text="" Margin="5" Grid.Row="2" Grid.Column="1"/>
  25:         <Label Content="Pick multimedia file" Grid.Row="3" Grid.Column="0"/>
  26:             <Grid Grid.Row="3" Grid.Column="1">
  27:                 <Grid.RowDefinitions>
  28:                     <RowDefinition Height="30"/>
  29:                 </Grid.RowDefinitions>
  30:                 <Grid.ColumnDefinitions>
  31:                     <ColumnDefinition Width="250"/>
  32:                     <ColumnDefinition Width="*"/>
  33:                 </Grid.ColumnDefinitions>
  34:                 <TextBox Name="txtFile" Margin="5" Grid.Column="0" Width="240"/>
  35:                 <Button Content="Browse" Grid.Column="1" Margin="5" 
  36:                         VerticalAlignment="Top" HorizontalAlignment="Left" Width="65" 
  37:                         Click="btnBrowse_Click"/>
  38:             </Grid>
  39:         <Label Content="Start Upload" Grid.Row="4" Grid.Column="0"/>
  40:         <Button Content="Upload" Grid.Row="4" Grid.Column="1" 
  41:                 HorizontalAlignment="Left" Margin="5" 
  42:                 VerticalAlignment="Top" Width="75" 
  43:                 Click="btnUpload_Click"/>
  44:         <Label Name="lblMsg" Content="" Grid.Row="5" Grid.Column="0"/>
  45:         <ProgressBar Name="Progress1" HorizontalAlignment="Left" 
  46:                      Height="10" Width="320" Margin="5"  
  47:                      Grid.Row="5" Grid.Column="1" VerticalAlignment="Top" 
  48:                      Minimum="0" Maximum="100" IsIndeterminate="True" 
  49:                      Visibility="Hidden"/>
  50:     </Grid>
  51: </Window>

Also we add the media service data in app.config with new keys "Media*".

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:   <appSettings>
   4:     <add key="MediaServiceName" value="mediademo02"/>
   5:     <add key="MediaServiceKey" value="m8cz..."/>
   6:     <add key="Directory" value="C:\Video"/>
   7:   </appSettings>
   8:     <startup> 
   9:         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  10:     </startup>
  11: </configuration>

And finally modify the code with some improvements like load media data, file picker, center screen and with async method.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Configuration;
   4: using System.Linq;
   5: using System.Text;
   6: using System.Threading.Tasks;
   7: using System.Windows;
   8: using System.Windows.Controls;
   9: using System.Windows.Data;
  10: using System.Windows.Documents;
  11: using System.Windows.Input;
  12: using System.Windows.Media;
  13: using System.Windows.Media.Imaging;
  14: using System.Windows.Navigation;
  15: using System.Windows.Shapes;
  16: using Microsoft.WindowsAzure.MediaServices.Client;
  17: using System.Windows.Forms;
  18:  
  19: namespace VideoUploader2
  20: {
  21:     /// <summary>
  22:     /// Interaction logic for MainWindow.xaml
  23:     /// </summary>
  24:     public partial class MainWindow : Window
  25:     {
  26:         public MainWindow()
  27:         {
  28:             InitializeComponent();
  29:             CenterWindowOnScreen();
  30:             txtMediaServiceName.Text = System.Configuration.ConfigurationManager.AppSettings["MediaServiceName"];
  31:             txtMediaServiceKey.Text = System.Configuration.ConfigurationManager.AppSettings["MediaServiceKey"];
  32:         }
  33:         private void DoIt(bool start,string message)
  34:         {
  35:             if (start)
  36:             {
  37:                 lblMsg.Content = message;
  38:                 Progress1.Visibility = Visibility.Visible;
  39:             }
  40:             else
  41:             {
  42:                 lblMsg.Content = message;
  43:                 Progress1.Visibility = Visibility.Hidden;
  44:             }
  45:             
  46:         }
  47:         private async void btnUpload_Click(object sender, RoutedEventArgs e)
  48:         {
  49:             DoIt(true, "uploading... (" + DateTime.Now.ToString() + ")");
  50:             var result = await UploadFile(txtFile.Text);
  51:             DoIt(false, result);
  52:         }
  53:  
  54:         private async Task<string> UploadFile(string uploadFilePath)
  55:         {
  56:             // Set the project properties to use the full .NET Framework (not Client Profile)
  57:             // With NuGet Package Manager, install windowsazure.mediaservices
  58:             // add: using Microsoft.WindowsAzure.MediaServices.Client;
  59:             try
  60:             {
  61:                 var context = new CloudMediaContext(txtMediaServiceName.Text.Trim(), txtMediaServiceKey.Text.Trim());
  62:                 var uploadAsset = context.Assets.Create(System.IO.Path.GetFileNameWithoutExtension(uploadFilePath), AssetCreationOptions.None);
  63:                 var assetFile = uploadAsset.AssetFiles.Create(System.IO.Path.GetFileName(uploadFilePath));
  64:                 // using await...
  65:                 await Task.Run(() => assetFile.Upload(uploadFilePath));
  66:                 return "Upload successful! (" + DateTime.Now.ToString() + ")";
  67:             }
  68:             catch (Exception ex)
  69:             {
  70:                 return "Error: " + ex.Message;
  71:             }
  72:         }
  73:         private async void  btnBrowse_Click(object sender, RoutedEventArgs e)
  74:         {
  75:             // Add Reference to System.Windows.Forms and create OpenFileDialog 
  76:             Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
  77:             // Set filter for file extension and default file extension 
  78:             dlg.DefaultExt = ".mp4";
  79:             dlg.Filter = "MP4 Files (*.mp4)|*.mp4|MPEG Files (*.mpeg)|*.mpeg|AVI Files (*.avi)|*.avi|All Files (*.*)|*.*";
  80:             // Display OpenFileDialog by calling ShowDialog method 
  81:             Nullable<bool> result = dlg.ShowDialog();
  82:             // Get the selected file name and display in a TextBox 
  83:             if (result == true)
  84:             {
  85:                 txtFile.Text = dlg.FileName;
  86:             }
  87:         }
  88:         private void CenterWindowOnScreen()
  89:         {
  90:             double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
  91:             double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
  92:             double windowWidth = this.Width;
  93:             double windowHeight = this.Height;
  94:             this.Left = (screenWidth / 2) - (windowWidth / 2);
  95:             this.Top = (screenHeight / 2) - (windowHeight / 2);
  96:         }
  97:     }
  98: }

When done, the app should run like this - and display a done message when finished.

SNAGHTMLeeaa31b_thumb[3]

If you plan to upload a large set of files take a look in this article here: Ingesting Assets in Bulk with the Media Services SDK for .NET.

Hint: In Windows Azure Store there´s a third party solution by Aspera for high-speed transportion to Windows Azure cloud-based object storage. Aspera uses fasp transport technology which means UDP upload, which is much faster than HTTPS - if you need more that the standard speed, for example greater than 100Mbps, as well as encryption of content content before it gets uploaded, see here.

Encoding

Now, when the video file is uploaded we can start working with it. As of today, the most used video formats are MP4, FLV, AVI, WebM and MOV. In Azure we can use  these formats (MP4, AVI, ASF, MPEG, MPG, MOD, WMV and some more).

So, let´s encode our video in one or more formats with the "encode" button. Choose a format and confirm the name of the suggested output file "<name>-<format>" or type your own filename.

image_thumb25

Now the encoding process is queued. You can watch the jobs and processes in "jobs".

image_thumb35

If you want to encode more than one task parallel, you can scale it.

By default, on-demand streaming is configured in a shared-instance model.
On-Demand Streaming reserved units provides dedicated egress capacity that can be purchased in increments of 200 Mbps, see How to Scale a Media Service.

image_thumb32

Tip: Remember that it takes up to 20 minutes till the allocation of any new units of on-demand streaming completes!

By default every Media Services account can scale to up to 25 Encoding and 5 On-Demand Streaming Reserved Units. For more performance you need to open a support ticket.

If you plan to automate the whole video upload and encoding process have a look at the ready-to-use snippet for encoding a video programmatically in the portal:

image_thumb[5]

The work to be done is to add a new task with a particullary MediaProcessor. Cool and easy to use.

Publish

Once the content is encoded, publish each version you would like to deliver.

image_thumb37

You get an URL for the video-file, like
https://mediasvc....blob.core.windows.net/asset-.../Deep-Dive-WAAD.mp4?...

image_thumb41

Testing

You can test the video file directly in the Azure portal by clicking the "play" button. Nice!

image_thumb44

Reuse the HTML-Code

Look at the player with the IE-Developer Tools (F12). Mark the video-player and you get the code.

image_thumb47

You see the <video> Tag containing the .mp4 video file.

   1: <video width="600" height="420" 
   2: src="https://mediasvc....blob.core.windows.net/asset-.../Deep-Dive-WAAD.mp4?sv=..." 
   3: autoplay="" controls="">
   4: Cannot play this content in your browser. 
   5: </video>

The application uses an HTML5 <video> tag to handle media streaming. Of course you can use this HTML-snippet in your own apps.

When playing the video and checking with the HTTP debugging proxy Fiddler you can see the tunnel to the Azure storage. When clicking f.e. in a later positions in the video you see the range adapting.

SNAGHTMLf1d294f_thumb[2]

Video Players

For building apps with a robust video player, Microsoft recommends the Microsoft Media Platform Player Framework from http://playerframework.codeplex.com/.

image84

The Player Framework can be used for Windows 8, HTML5, Silverlight, Windows Phone and other application platforms. You can define playlists and use many more features like localization and so on.

After installing Microsoft.PlayerFramework.vsix you have a bunch of Plugins on your computer, usually located in C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\Microsoft.PlayerFramework\1.8.2.2 .

For samples download Microsoft.PlayerFramework.Samples.zip.

image_thumb[11]

The basic usage of HTML5 Player Framework can look like this:

So have a look and use it for your own apps with streaming media content and play around. Zwinkerndes Smiley

Creating a basic Windows 8 app with streaming video

For Windows 8 apps you need the Smooth Streaming Client SDK for Windows 8.1. This enables developers to build Windows 8.1 Store applications that consume On-Demand and Live Smooth Streaming content with PlayReady protection.

Find a sample here: PlayReady sample for Windows 8.1 Store apps.

Azure Media Services conclusion

With Azure Media Services it´s simple to upload audio and video files into a Windows Azure storage and to start encoding tasks as well as using the streamed multimedia content.

If you plan to use streaming in your own apps Windows Azure Media Services are right here for you!

Comments (2) -

  • jake

    3/31/2015 9:04:00 AM |

    Hi
    Thank you for your article. I'd like to upload file more than 200mb, but I couldn't it by GUI mode in WindowsAzure, I am not a developer, so VB is not familiar to me. I didnt understand part of your this article "So simply copy and paste the generated code – including my media services key – to my project, f.e. in a button click event. So my slightly adapted code looks like this:", Where do I copy azure portal code? you said to copy my project, but I dont know this mean. My project? Can you explain this if you have time?

  • Toni Pohl

    3/31/2015 11:39:58 AM |

    Hi Jake,
    You need Microsoft Visual Studio, f.e. the free available community edition, to use the code. Since the original article is meant for developers, you would need some basic skills for how to develop a vs solution.
    Maybe ask a developer for help?
    Hth, best regards,
    Toni

Loading